feat(compose): 正文内嵌隐藏块并升级 Markdown 编辑器
去掉整帖可见性表单,改为 :::hide 按块脱敏;工具栏补齐代码块、链接/图片对话框与粘贴拖拽上传。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -1320,9 +1320,137 @@ body {
|
||||
color: var(--accent);
|
||||
}
|
||||
.j13-md-tool:disabled { opacity: 0.4; }
|
||||
.j13-md-tool:focus-visible {
|
||||
.j13-md-tool.is-active {
|
||||
background: var(--accent-soft);
|
||||
color: var(--accent);
|
||||
}
|
||||
.j13-md-sep {
|
||||
width: 1px;
|
||||
height: 18px;
|
||||
margin: 0 4px;
|
||||
background: var(--line);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.j13-md-popover-anchor {
|
||||
position: relative;
|
||||
}
|
||||
.j13-md-popover {
|
||||
position: absolute;
|
||||
top: calc(100% + 6px);
|
||||
left: 0;
|
||||
z-index: 40;
|
||||
min-width: 168px;
|
||||
padding: 6px;
|
||||
border-radius: 12px;
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
box-shadow: var(--shadow-lg);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
.j13-md-popover-wide {
|
||||
min-width: 200px;
|
||||
max-height: 280px;
|
||||
}
|
||||
.j13-md-popover-form {
|
||||
min-width: 260px;
|
||||
padding: 10px;
|
||||
gap: 8px;
|
||||
}
|
||||
.j13-md-popover button[role="menuitem"],
|
||||
.j13-md-menu-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
padding: 8px 10px;
|
||||
border-radius: 8px;
|
||||
font-size: 13px;
|
||||
color: var(--ink);
|
||||
background: transparent;
|
||||
}
|
||||
.j13-md-popover button[role="menuitem"]:hover,
|
||||
.j13-md-menu-item:hover {
|
||||
background: var(--accent-soft);
|
||||
color: var(--accent);
|
||||
}
|
||||
.j13-md-popover-input {
|
||||
width: 100%;
|
||||
height: 34px;
|
||||
padding: 0 10px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--line);
|
||||
background: var(--bg);
|
||||
color: var(--ink);
|
||||
font-size: 13px;
|
||||
}
|
||||
.j13-md-popover-input:focus {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 1px;
|
||||
outline-offset: 0;
|
||||
}
|
||||
.j13-md-popover-list {
|
||||
max-height: 200px;
|
||||
overflow-y: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
}
|
||||
.j13-md-popover-list button {
|
||||
text-align: left;
|
||||
padding: 7px 10px;
|
||||
border-radius: 8px;
|
||||
font-size: 12.5px;
|
||||
font-family: var(--font-mono, ui-monospace, monospace);
|
||||
color: var(--ink-2);
|
||||
}
|
||||
.j13-md-popover-list button:hover {
|
||||
background: var(--accent-soft);
|
||||
color: var(--accent);
|
||||
}
|
||||
.j13-md-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
font-size: 12px;
|
||||
color: var(--ink-3);
|
||||
}
|
||||
.j13-md-popover-footer {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
margin-top: 2px;
|
||||
}
|
||||
.btn-sm {
|
||||
height: 30px;
|
||||
padding: 0 12px;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
.j13-md-write-wrap {
|
||||
position: relative;
|
||||
flex: 1 1 auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
}
|
||||
.j13-md-write-wrap.is-dragover .j13-md-textarea {
|
||||
opacity: 0.35;
|
||||
}
|
||||
.j13-md-drop-mask {
|
||||
position: absolute;
|
||||
inset: 8px 0;
|
||||
z-index: 5;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 12px;
|
||||
border: 2px dashed var(--accent);
|
||||
background: color-mix(in srgb, var(--accent-soft) 80%, transparent);
|
||||
color: var(--accent);
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
pointer-events: none;
|
||||
}
|
||||
.j13-md-mode {
|
||||
display: inline-flex;
|
||||
@@ -1394,6 +1522,66 @@ body {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
/* 正文内嵌隐藏块 */
|
||||
.j13-hide-block {
|
||||
margin: 1.1rem 0;
|
||||
border-radius: 14px;
|
||||
border: 1px solid color-mix(in srgb, var(--accent) 22%, var(--line));
|
||||
background: color-mix(in srgb, var(--accent-soft) 55%, var(--panel));
|
||||
overflow: hidden;
|
||||
}
|
||||
.j13-hide-block-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 8px 14px;
|
||||
border-bottom: 1px solid color-mix(in srgb, var(--accent) 14%, var(--line));
|
||||
}
|
||||
.j13-hide-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
height: 22px;
|
||||
padding: 0 9px;
|
||||
border-radius: 999px;
|
||||
font-size: 11.5px;
|
||||
font-weight: 600;
|
||||
color: var(--accent);
|
||||
background: var(--accent-soft);
|
||||
}
|
||||
.j13-hide-block-body {
|
||||
padding: 12px 16px 14px;
|
||||
}
|
||||
.j13-hide-block-body > :first-child { margin-top: 0; }
|
||||
.j13-hide-block-body > :last-child { margin-bottom: 0; }
|
||||
.j13-hide-gate {
|
||||
margin: 1.1rem 0;
|
||||
border-radius: 14px;
|
||||
padding: 1.35rem 1.25rem;
|
||||
text-align: center;
|
||||
background: var(--accent-soft);
|
||||
border: 1px dashed color-mix(in srgb, var(--accent) 35%, transparent);
|
||||
}
|
||||
.j13-hide-gate-icon {
|
||||
margin: 0 auto 0.55rem;
|
||||
color: var(--accent);
|
||||
}
|
||||
.j13-hide-gate-title {
|
||||
font-weight: 700;
|
||||
font-size: 15px;
|
||||
color: var(--ink);
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
.j13-hide-gate-desc {
|
||||
margin-bottom: 0.9rem;
|
||||
font-size: 13px;
|
||||
}
|
||||
.j13-hide-gate-actions {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.j13-compose-shell {
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
|
||||
@@ -9,8 +9,6 @@ type Props = {
|
||||
initialContent: string;
|
||||
initialTags: string;
|
||||
initialPostType?: string;
|
||||
initialContentAccess?: string;
|
||||
initialAccessPoints?: number;
|
||||
initialTypeMeta?: string;
|
||||
initialAttachments?: PostAttachment[];
|
||||
canEditPollOptions?: boolean;
|
||||
@@ -26,8 +24,6 @@ export default function EditPostClient({
|
||||
initialContent,
|
||||
initialTags,
|
||||
initialPostType,
|
||||
initialContentAccess,
|
||||
initialAccessPoints,
|
||||
initialTypeMeta,
|
||||
initialAttachments,
|
||||
canEditPollOptions,
|
||||
@@ -44,8 +40,6 @@ export default function EditPostClient({
|
||||
initialContent={initialContent}
|
||||
initialTags={initialTags}
|
||||
initialPostType={initialPostType}
|
||||
initialContentAccess={initialContentAccess}
|
||||
initialAccessPoints={initialAccessPoints}
|
||||
initialTypeMeta={initialTypeMeta}
|
||||
initialAttachments={initialAttachments}
|
||||
canEditPollOptions={canEditPollOptions}
|
||||
|
||||
@@ -60,8 +60,6 @@ export default async function EditPostPage({ params }: PageProps) {
|
||||
initialContent={post.content}
|
||||
initialTags={post.tags || ""}
|
||||
initialPostType={post.post_type}
|
||||
initialContentAccess={post.content_access}
|
||||
initialAccessPoints={post.access_points}
|
||||
initialTypeMeta={post.type_meta}
|
||||
initialAttachments={post.attachments || []}
|
||||
canEditPollOptions={post.poll?.can_edit_options !== false}
|
||||
|
||||
@@ -34,7 +34,7 @@ import MobilePostBar from "@/components/MobilePostBar";
|
||||
import Avatar from "@/components/Avatar";
|
||||
import RoleBadge from "@/components/RoleBadge";
|
||||
import MarkdownBody from "@/components/MarkdownBody";
|
||||
import ContentLockGate from "@/components/ContentLockGate";
|
||||
import { publicMarkdownForSeo } from "@/lib/hideBlocks";
|
||||
import PostAttachments from "@/components/PostAttachments";
|
||||
import PostInteractPanels, { QuestionStatusCard } from "@/components/PostInteractPanels";
|
||||
import AcceptedAnswerCard from "@/components/AcceptedAnswerCard";
|
||||
@@ -60,9 +60,10 @@ export async function generateMetadata({ params }: PageProps): Promise<Metadata>
|
||||
robots: { index: false, follow: false },
|
||||
};
|
||||
}
|
||||
const desc = post.content_locked
|
||||
? post.access_hint || "部分内容需满足条件后可见"
|
||||
: (post.content || "").slice(0, 160);
|
||||
const publicBody = publicMarkdownForSeo(post.content || "");
|
||||
const desc = publicBody
|
||||
? publicBody.slice(0, 160)
|
||||
: post.access_hint || "部分内容需满足条件后可见";
|
||||
return {
|
||||
title: post.title,
|
||||
description: desc,
|
||||
@@ -481,10 +482,11 @@ export default async function PostDetailPage({ params, searchParams }: PageProps
|
||||
const related = (relatedData?.posts ?? []).filter((p) => p.id !== post.id).slice(0, 5);
|
||||
const authorPosts = (profile?.posts ?? []).filter((p) => p.id !== post.id).slice(0, 5);
|
||||
|
||||
const toc = post.content_locked ? [] : extractToc(post.content);
|
||||
const publicBody = publicMarkdownForSeo(post.content || "");
|
||||
const toc = extractToc(publicBody);
|
||||
const readingMinutes = Math.max(
|
||||
1,
|
||||
Math.ceil((post.content_locked ? post.title.length : post.content.length) / 400)
|
||||
Math.ceil((publicBody.length > 0 ? publicBody.length : post.title.length) / 400)
|
||||
);
|
||||
const edited =
|
||||
new Date(post.updated_at).getTime() - new Date(post.created_at).getTime() > 60_000;
|
||||
@@ -527,8 +529,8 @@ export default async function PostDetailPage({ params, searchParams }: PageProps
|
||||
"@context": "https://schema.org",
|
||||
"@type": "DiscussionForumPosting",
|
||||
headline: post.title,
|
||||
// 锁定正文不进 JSON-LD,避免 SEO 泄露付费/回复可见内容
|
||||
articleBody: post.content_locked ? undefined : post.content,
|
||||
// 仅公开片段进 JSON-LD,避免 SEO 泄露隐藏块原文
|
||||
articleBody: publicBody || undefined,
|
||||
datePublished: post.created_at,
|
||||
dateModified: post.updated_at,
|
||||
author: { "@type": "Person", name: post.user.nickname },
|
||||
@@ -541,7 +543,7 @@ export default async function PostDetailPage({ params, searchParams }: PageProps
|
||||
...(allowComments &&
|
||||
acceptedAnswer &&
|
||||
!acceptedAnswer.deleted &&
|
||||
!post.content_locked && {
|
||||
!!publicBody && {
|
||||
acceptedAnswer: {
|
||||
"@type": "Comment",
|
||||
text: acceptedAnswer.content,
|
||||
@@ -718,24 +720,14 @@ export default async function PostDetailPage({ params, searchParams }: PageProps
|
||||
</div>
|
||||
)}
|
||||
|
||||
{post.content_locked ? (
|
||||
<ContentLockGate
|
||||
postId={post.id}
|
||||
hint={post.access_hint}
|
||||
access={post.content_access}
|
||||
points={post.access_points}
|
||||
loggedIn={!!me.user}
|
||||
/>
|
||||
) : (
|
||||
<MarkdownBody
|
||||
content={post.content}
|
||||
components={{ h2: headingRenderer("h2"), h3: headingRenderer("h3") }}
|
||||
/>
|
||||
)}
|
||||
<MarkdownBody
|
||||
content={post.content}
|
||||
postId={post.id}
|
||||
loggedIn={!!me.user}
|
||||
components={{ h2: headingRenderer("h2"), h3: headingRenderer("h3") }}
|
||||
/>
|
||||
|
||||
{!post.content_locked && (
|
||||
<PostAttachments postId={post.id} items={post.attachments || []} />
|
||||
)}
|
||||
<PostAttachments postId={post.id} items={post.attachments || []} />
|
||||
|
||||
{/* 类型特殊块(投票/悬赏/抽奖/问答)统一放正文最下方 */}
|
||||
<PostInteractPanels
|
||||
@@ -745,7 +737,7 @@ export default async function PostDetailPage({ params, searchParams }: PageProps
|
||||
lottery={post.lottery}
|
||||
loggedIn={!!me.user}
|
||||
/>
|
||||
{!post.content_locked && allowComments && acceptedAnswer ? (
|
||||
{allowComments && acceptedAnswer ? (
|
||||
<AcceptedAnswerCard
|
||||
answer={acceptedAnswer}
|
||||
variant={acceptedAnswerVariant}
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { Lock } from "lucide-react";
|
||||
import { apiUnlockPost } from "@/lib/api";
|
||||
import { toast } from "@/lib/toast";
|
||||
|
||||
export default function ContentLockGate({
|
||||
postId,
|
||||
hint,
|
||||
access,
|
||||
points,
|
||||
loggedIn,
|
||||
}: {
|
||||
postId: number;
|
||||
hint?: string;
|
||||
access?: string;
|
||||
points?: number;
|
||||
loggedIn: boolean;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const unlock = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await apiUnlockPost(String(postId));
|
||||
if (res.post) {
|
||||
toast("已解锁全文", "ok");
|
||||
router.refresh();
|
||||
} else {
|
||||
toast(res.error || "解锁失败", "error");
|
||||
}
|
||||
} catch {
|
||||
toast("解锁失败", "error");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className="rounded-[14px] px-6 py-10 text-center my-4"
|
||||
style={{
|
||||
background: "var(--accent-soft)",
|
||||
border: "1px solid color-mix(in srgb, var(--accent) 20%, transparent)",
|
||||
}}
|
||||
>
|
||||
<Lock size={28} className="mx-auto mb-3" style={{ color: "var(--accent)" }} />
|
||||
<p className="font-bold text-[16px] mb-1" style={{ color: "var(--ink)" }}>
|
||||
{hint || "正文暂不可见"}
|
||||
</p>
|
||||
<p className="meta text-[13px] mb-5">
|
||||
{access === "points"
|
||||
? `支付 ${points || 0} 积分后可阅读全文`
|
||||
: access === "reply"
|
||||
? "发表一条回复后即可阅读全文"
|
||||
: access === "login"
|
||||
? "登录后即可阅读全文"
|
||||
: null}
|
||||
</p>
|
||||
{access === "login" && !loggedIn && (
|
||||
<Link
|
||||
href={`/login?redirect=${encodeURIComponent(`/post/${postId}`)}`}
|
||||
className="btn btn-primary"
|
||||
>
|
||||
去登录
|
||||
</Link>
|
||||
)}
|
||||
{access === "points" && loggedIn && (
|
||||
<button type="button" className="btn btn-primary" disabled={busy} onClick={() => void unlock()}>
|
||||
{busy ? "解锁中…" : `支付 ${points || 0} 积分解锁`}
|
||||
</button>
|
||||
)}
|
||||
{access === "points" && !loggedIn && (
|
||||
<Link
|
||||
href={`/login?redirect=${encodeURIComponent(`/post/${postId}`)}`}
|
||||
className="btn btn-primary"
|
||||
>
|
||||
登录后解锁
|
||||
</Link>
|
||||
)}
|
||||
{access === "reply" && (
|
||||
<a href="#comments" className="btn btn-primary">
|
||||
去回复
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,21 +1,61 @@
|
||||
import type { Components } from "react-markdown";
|
||||
import { renderMarkdownToReact } from "@/components/markdown/renderMarkdown";
|
||||
import { splitHideSegments, type HideKind } from "@/lib/hideBlocks";
|
||||
import MdHideBlock from "@/components/markdown/MdHideBlock";
|
||||
|
||||
type MarkdownBodyProps = {
|
||||
content: string;
|
||||
className?: string;
|
||||
components?: Components;
|
||||
/** 详情页解锁门禁需要 */
|
||||
postId?: number;
|
||||
loggedIn?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* 站点统一 Markdown 渲染(服务端):GFM + Shiki 双主题、图箱、代码块复制/折叠。
|
||||
* 客户端预览请用 MarkdownBodyClient。
|
||||
* 站点统一 Markdown 渲染(服务端):GFM + Shiki;支持 :::hide 内嵌块。
|
||||
*/
|
||||
export default async function MarkdownBody({
|
||||
content,
|
||||
className = "prose-content",
|
||||
components,
|
||||
postId,
|
||||
loggedIn = false,
|
||||
}: MarkdownBodyProps) {
|
||||
const tree = await renderMarkdownToReact(content, components);
|
||||
return <div className={className}>{tree}</div>;
|
||||
const segs = splitHideSegments(content || "");
|
||||
const nodes = [];
|
||||
for (let i = 0; i < segs.length; i++) {
|
||||
const seg = segs[i];
|
||||
if (seg.type === "md") {
|
||||
if (!seg.text.trim()) continue;
|
||||
nodes.push(
|
||||
<div key={`md-${i}`}>{await renderMarkdownToReact(seg.text, components)}</div>
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const kind = seg.kind as HideKind;
|
||||
if (seg.locked) {
|
||||
nodes.push(
|
||||
<MdHideBlock
|
||||
key={`hide-${i}`}
|
||||
kind={kind}
|
||||
points={seg.points}
|
||||
locked
|
||||
postId={postId}
|
||||
loggedIn={loggedIn}
|
||||
/>
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const inner = seg.body.trim()
|
||||
? await renderMarkdownToReact(seg.body, components)
|
||||
: null;
|
||||
nodes.push(
|
||||
<MdHideBlock key={`hide-${i}`} kind={kind} points={seg.points}>
|
||||
{inner}
|
||||
</MdHideBlock>
|
||||
);
|
||||
}
|
||||
|
||||
return <div className={className}>{nodes}</div>;
|
||||
}
|
||||
|
||||
@@ -3,30 +3,64 @@
|
||||
import ReactMarkdown, { type Components } from "react-markdown";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import { mergeMarkdownComponents } from "@/components/markdown/mergeComponents";
|
||||
import { splitHideSegments, type HideKind } from "@/lib/hideBlocks";
|
||||
import MdHideBlock from "@/components/markdown/MdHideBlock";
|
||||
|
||||
type MarkdownBodyClientProps = {
|
||||
content: string;
|
||||
className?: string;
|
||||
components?: Components;
|
||||
postId?: number;
|
||||
loggedIn?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* 客户端 Markdown(发帖预览 / 评论):GFM + 图箱 / 代码折叠复制。
|
||||
* 语法高亮在 MdCodeBlock 内按需用 Shiki 补齐。
|
||||
* 客户端 Markdown(发帖预览 / 评论):GFM + 隐藏块徽章预览。
|
||||
*/
|
||||
export default function MarkdownBodyClient({
|
||||
content,
|
||||
className = "prose-content",
|
||||
components,
|
||||
postId,
|
||||
loggedIn = false,
|
||||
}: MarkdownBodyClientProps) {
|
||||
const segs = splitHideSegments(content || "");
|
||||
const mdComponents = mergeMarkdownComponents(components);
|
||||
|
||||
return (
|
||||
<div className={className}>
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
components={mergeMarkdownComponents(components)}
|
||||
>
|
||||
{content || ""}
|
||||
</ReactMarkdown>
|
||||
{segs.map((seg, i) => {
|
||||
if (seg.type === "md") {
|
||||
if (!seg.text.trim()) return null;
|
||||
return (
|
||||
<ReactMarkdown key={`md-${i}`} remarkPlugins={[remarkGfm]} components={mdComponents}>
|
||||
{seg.text}
|
||||
</ReactMarkdown>
|
||||
);
|
||||
}
|
||||
const kind = seg.kind as HideKind;
|
||||
if (seg.locked) {
|
||||
return (
|
||||
<MdHideBlock
|
||||
key={`hide-${i}`}
|
||||
kind={kind}
|
||||
points={seg.points}
|
||||
locked
|
||||
postId={postId}
|
||||
loggedIn={loggedIn}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<MdHideBlock key={`hide-${i}`} kind={kind} points={seg.points}>
|
||||
{seg.body.trim() ? (
|
||||
<ReactMarkdown remarkPlugins={[remarkGfm]} components={mdComponents}>
|
||||
{seg.body}
|
||||
</ReactMarkdown>
|
||||
) : null}
|
||||
</MdHideBlock>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,23 +1,41 @@
|
||||
"use client";
|
||||
|
||||
import { useRef, useState, useCallback, useEffect, type ReactNode } from "react";
|
||||
import {
|
||||
useRef,
|
||||
useState,
|
||||
useCallback,
|
||||
useEffect,
|
||||
type ReactNode,
|
||||
type KeyboardEvent as ReactKeyboardEvent,
|
||||
} from "react";
|
||||
import {
|
||||
Bold,
|
||||
Italic,
|
||||
Strikethrough,
|
||||
Code,
|
||||
Code2,
|
||||
Quote,
|
||||
List,
|
||||
ListOrdered,
|
||||
Heading2,
|
||||
Heading3,
|
||||
Link as LinkIcon,
|
||||
Image as ImageIcon,
|
||||
Table,
|
||||
Minus,
|
||||
Eye,
|
||||
Pencil,
|
||||
Maximize2,
|
||||
Minimize2,
|
||||
Lock,
|
||||
ChevronDown,
|
||||
Upload,
|
||||
Link2,
|
||||
} from "lucide-react";
|
||||
import { apiUploadPostImage } from "@/lib/api";
|
||||
import { toast } from "@/lib/toast";
|
||||
import MarkdownBodyClient from "@/components/MarkdownBodyClient";
|
||||
import { SHIKI_LANG_IDS } from "@/components/markdown/shikiHighlighter";
|
||||
|
||||
type MarkdownEditorProps = {
|
||||
value: string;
|
||||
@@ -36,6 +54,10 @@ type WrapOpts = {
|
||||
linePrefix?: string;
|
||||
};
|
||||
|
||||
type PopoverKind = "link" | "imageUrl" | "code" | "hide" | "heading" | "image" | null;
|
||||
|
||||
const CODE_LANGS = ["plaintext", "aardio", ...SHIKI_LANG_IDS.filter((l) => l !== "plaintext")] as const;
|
||||
|
||||
function applyWrap(
|
||||
el: HTMLTextAreaElement,
|
||||
value: string,
|
||||
@@ -53,11 +75,7 @@ function applyWrap(
|
||||
);
|
||||
const inserted = lines.join("\n");
|
||||
const next = value.slice(0, start) + inserted + value.slice(end);
|
||||
return {
|
||||
next,
|
||||
selStart: start,
|
||||
selEnd: start + inserted.length,
|
||||
};
|
||||
return { next, selStart: start, selEnd: start + inserted.length };
|
||||
}
|
||||
|
||||
const inner = selected || opts.placeholder || "";
|
||||
@@ -68,6 +86,15 @@ function applyWrap(
|
||||
return { next, selStart, selEnd };
|
||||
}
|
||||
|
||||
function isHttpUrl(raw: string): boolean {
|
||||
try {
|
||||
const u = new URL(raw.trim());
|
||||
return u.protocol === "http:" || u.protocol === "https:";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export default function MarkdownEditor({
|
||||
value,
|
||||
onChange,
|
||||
@@ -79,16 +106,28 @@ export default function MarkdownEditor({
|
||||
}: MarkdownEditorProps) {
|
||||
const taRef = useRef<HTMLTextAreaElement>(null);
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
const toolbarRef = useRef<HTMLDivElement>(null);
|
||||
const [mode, setMode] = useState<"write" | "preview">("write");
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [fullscreen, setFullscreen] = useState(false);
|
||||
const [dragOver, setDragOver] = useState(false);
|
||||
const [popover, setPopover] = useState<PopoverKind>(null);
|
||||
const [linkText, setLinkText] = useState("");
|
||||
const [linkUrl, setLinkUrl] = useState("https://");
|
||||
const [imageUrl, setImageUrl] = useState("https://");
|
||||
const [imageAlt, setImageAlt] = useState("图片");
|
||||
const [codeQuery, setCodeQuery] = useState("");
|
||||
const [hidePoints, setHidePoints] = useState(10);
|
||||
const [hideStep, setHideStep] = useState<"menu" | "points">("menu");
|
||||
const savedSel = useRef<{ start: number; end: number } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!fullscreen) return;
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") {
|
||||
e.preventDefault();
|
||||
setFullscreen(false);
|
||||
if (popover) setPopover(null);
|
||||
else setFullscreen(false);
|
||||
}
|
||||
};
|
||||
const prev = document.body.style.overflow;
|
||||
@@ -98,7 +137,40 @@ export default function MarkdownEditor({
|
||||
document.body.style.overflow = prev;
|
||||
window.removeEventListener("keydown", onKey);
|
||||
};
|
||||
}, [fullscreen]);
|
||||
}, [fullscreen, popover]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!popover) return;
|
||||
const onDoc = (e: MouseEvent) => {
|
||||
const t = e.target as Node;
|
||||
if (toolbarRef.current && !toolbarRef.current.contains(t)) {
|
||||
setPopover(null);
|
||||
}
|
||||
};
|
||||
const onEsc = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") setPopover(null);
|
||||
};
|
||||
document.addEventListener("mousedown", onDoc);
|
||||
document.addEventListener("keydown", onEsc);
|
||||
return () => {
|
||||
document.removeEventListener("mousedown", onDoc);
|
||||
document.removeEventListener("keydown", onEsc);
|
||||
};
|
||||
}, [popover]);
|
||||
|
||||
const rememberSel = () => {
|
||||
const el = taRef.current;
|
||||
if (!el) return;
|
||||
savedSel.current = { start: el.selectionStart, end: el.selectionEnd };
|
||||
};
|
||||
|
||||
const restoreSel = () => {
|
||||
const el = taRef.current;
|
||||
const sel = savedSel.current;
|
||||
if (!el || !sel) return;
|
||||
el.focus();
|
||||
el.setSelectionRange(sel.start, sel.end);
|
||||
};
|
||||
|
||||
const runWrap = useCallback(
|
||||
(opts: WrapOpts) => {
|
||||
@@ -115,29 +187,35 @@ export default function MarkdownEditor({
|
||||
);
|
||||
|
||||
const insertAtCursor = useCallback(
|
||||
(text: string) => {
|
||||
(text: string, selectInner?: { offset: number; length: number }) => {
|
||||
const el = taRef.current;
|
||||
if (!el) {
|
||||
onChange(value + (value.endsWith("\n") || !value ? "" : "\n") + text);
|
||||
return;
|
||||
}
|
||||
const start = el.selectionStart;
|
||||
const end = el.selectionEnd;
|
||||
const start = savedSel.current?.start ?? el.selectionStart;
|
||||
const end = savedSel.current?.end ?? el.selectionEnd;
|
||||
const padBefore = start > 0 && value[start - 1] !== "\n" ? "\n" : "";
|
||||
const padAfter = end < value.length && value[end] !== "\n" ? "\n" : "";
|
||||
const inserted = padBefore + text + padAfter;
|
||||
const next = value.slice(0, start) + inserted + value.slice(end);
|
||||
onChange(next);
|
||||
const caret = start + inserted.length;
|
||||
requestAnimationFrame(() => {
|
||||
el.focus();
|
||||
el.setSelectionRange(caret, caret);
|
||||
if (selectInner) {
|
||||
const a = start + padBefore.length + selectInner.offset;
|
||||
el.setSelectionRange(a, a + selectInner.length);
|
||||
} else {
|
||||
const caret = start + inserted.length;
|
||||
el.setSelectionRange(caret, caret);
|
||||
}
|
||||
});
|
||||
savedSel.current = null;
|
||||
},
|
||||
[value, onChange]
|
||||
);
|
||||
|
||||
const handleImagePick = async (file: File | null) => {
|
||||
const uploadImageFile = async (file: File | null) => {
|
||||
if (!file || disabled) return;
|
||||
if (!/^image\/(jpeg|png|webp)$/i.test(file.type)) {
|
||||
toast("仅支持 JPEG / PNG / WebP", "error");
|
||||
@@ -166,82 +244,536 @@ export default function MarkdownEditor({
|
||||
}
|
||||
};
|
||||
|
||||
const tools: {
|
||||
key: string;
|
||||
const openPopover = (kind: PopoverKind) => {
|
||||
rememberSel();
|
||||
if (kind === "link") {
|
||||
const el = taRef.current;
|
||||
const selected = el ? value.slice(el.selectionStart, el.selectionEnd) : "";
|
||||
setLinkText(selected || "链接文字");
|
||||
setLinkUrl("https://");
|
||||
}
|
||||
if (kind === "imageUrl") {
|
||||
setImageUrl("https://");
|
||||
setImageAlt("图片");
|
||||
}
|
||||
if (kind === "code") setCodeQuery("");
|
||||
if (kind === "hide") {
|
||||
setHideStep("menu");
|
||||
setHidePoints(10);
|
||||
}
|
||||
setPopover((prev) => (prev === kind ? null : kind));
|
||||
};
|
||||
|
||||
const applyLink = () => {
|
||||
const url = linkUrl.trim();
|
||||
if (!isHttpUrl(url)) {
|
||||
toast("请输入有效的 http(s) 链接", "error");
|
||||
return;
|
||||
}
|
||||
const el = taRef.current;
|
||||
restoreSel();
|
||||
const start = el?.selectionStart ?? 0;
|
||||
const end = el?.selectionEnd ?? 0;
|
||||
const selected = value.slice(start, end);
|
||||
const label = (selected || linkText.trim() || url).trim() || url;
|
||||
const md = `[${label}](${url})`;
|
||||
const next = value.slice(0, start) + md + value.slice(end);
|
||||
onChange(next);
|
||||
requestAnimationFrame(() => {
|
||||
if (!el) return;
|
||||
el.focus();
|
||||
el.setSelectionRange(start + md.length, start + md.length);
|
||||
});
|
||||
setPopover(null);
|
||||
};
|
||||
|
||||
const applyImageUrl = () => {
|
||||
const url = imageUrl.trim();
|
||||
if (!isHttpUrl(url)) {
|
||||
toast("请输入有效的图片 URL(http/https)", "error");
|
||||
return;
|
||||
}
|
||||
const alt = imageAlt.trim() || "图片";
|
||||
insertAtCursor(``);
|
||||
setPopover(null);
|
||||
};
|
||||
|
||||
const insertCodeBlock = (lang: string) => {
|
||||
const el = taRef.current;
|
||||
restoreSel();
|
||||
const start = el?.selectionStart ?? 0;
|
||||
const end = el?.selectionEnd ?? 0;
|
||||
const selected = value.slice(start, end);
|
||||
const body = selected || "代码";
|
||||
const fence = "```" + lang + "\n" + body + "\n```";
|
||||
const padBefore = start > 0 && value[start - 1] !== "\n" ? "\n" : "";
|
||||
const padAfter = end < value.length && value[end] !== "\n" ? "\n" : "";
|
||||
const inserted = padBefore + fence + padAfter;
|
||||
const next = value.slice(0, start) + inserted + value.slice(end);
|
||||
onChange(next);
|
||||
requestAnimationFrame(() => {
|
||||
if (!el) return;
|
||||
el.focus();
|
||||
const bodyStart = start + padBefore.length + 3 + lang.length + 1;
|
||||
el.setSelectionRange(bodyStart, bodyStart + body.length);
|
||||
});
|
||||
setPopover(null);
|
||||
};
|
||||
|
||||
const insertHide = (kind: "login" | "reply" | "points", points?: number) => {
|
||||
restoreSel();
|
||||
const el = taRef.current;
|
||||
const start = el?.selectionStart ?? 0;
|
||||
const end = el?.selectionEnd ?? 0;
|
||||
const selected = value.slice(start, end);
|
||||
const body = selected || "在此填写隐藏内容";
|
||||
const open =
|
||||
kind === "points"
|
||||
? `:::hide points ${points || 10}`
|
||||
: `:::hide ${kind}`;
|
||||
const block = `${open}\n${body}\n:::`;
|
||||
const padBefore = start > 0 && value[start - 1] !== "\n" ? "\n" : "";
|
||||
const padAfter = end < value.length && value[end] !== "\n" ? "\n" : "";
|
||||
const inserted = padBefore + block + padAfter;
|
||||
const next = value.slice(0, start) + inserted + value.slice(end);
|
||||
onChange(next);
|
||||
requestAnimationFrame(() => {
|
||||
if (!el) return;
|
||||
el.focus();
|
||||
const bodyStart = start + padBefore.length + open.length + 1;
|
||||
el.setSelectionRange(bodyStart, bodyStart + body.length);
|
||||
});
|
||||
setPopover(null);
|
||||
};
|
||||
|
||||
const insertOrderedList = () => {
|
||||
const el = taRef.current;
|
||||
if (!el || disabled) return;
|
||||
const start = el.selectionStart;
|
||||
const end = el.selectionEnd;
|
||||
const selected = value.slice(start, end) || "列表项";
|
||||
const lines = selected.split("\n").map((l, i) => {
|
||||
if (/^\d+\.\s/.test(l)) return l;
|
||||
return `${i + 1}. ${l}`;
|
||||
});
|
||||
const inserted = lines.join("\n");
|
||||
const next = value.slice(0, start) + inserted + value.slice(end);
|
||||
onChange(next);
|
||||
requestAnimationFrame(() => {
|
||||
el.focus();
|
||||
el.setSelectionRange(start, start + inserted.length);
|
||||
});
|
||||
};
|
||||
|
||||
const insertTable = () => {
|
||||
insertAtCursor(
|
||||
"| 列1 | 列2 | 列3 |\n| --- | --- | --- |\n| | | |\n| | | |"
|
||||
);
|
||||
};
|
||||
|
||||
const onTextareaKeyDown = (e: ReactKeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
onSubmitShortcut?.();
|
||||
return;
|
||||
}
|
||||
if ((e.ctrlKey || e.metaKey) && !e.shiftKey && e.key.toLowerCase() === "b") {
|
||||
e.preventDefault();
|
||||
runWrap({ before: "**", after: "**", placeholder: "粗体" });
|
||||
return;
|
||||
}
|
||||
if ((e.ctrlKey || e.metaKey) && !e.shiftKey && e.key.toLowerCase() === "i") {
|
||||
e.preventDefault();
|
||||
runWrap({ before: "*", after: "*", placeholder: "斜体" });
|
||||
return;
|
||||
}
|
||||
if ((e.ctrlKey || e.metaKey) && !e.shiftKey && e.key.toLowerCase() === "k") {
|
||||
e.preventDefault();
|
||||
openPopover("link");
|
||||
return;
|
||||
}
|
||||
if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key.toLowerCase() === "c") {
|
||||
e.preventDefault();
|
||||
openPopover("code");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
const onPaste = async (e: React.ClipboardEvent<HTMLTextAreaElement>) => {
|
||||
const items = e.clipboardData?.items;
|
||||
if (items) {
|
||||
for (const item of items) {
|
||||
if (item.type.startsWith("image/")) {
|
||||
e.preventDefault();
|
||||
const file = item.getAsFile();
|
||||
await uploadImageFile(file);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
const text = e.clipboardData?.getData("text/plain")?.trim() || "";
|
||||
if (text && isHttpUrl(text)) {
|
||||
const el = taRef.current;
|
||||
if (el && el.selectionStart !== el.selectionEnd) {
|
||||
e.preventDefault();
|
||||
const start = el.selectionStart;
|
||||
const end = el.selectionEnd;
|
||||
const selected = value.slice(start, end);
|
||||
const md = `[${selected}](${text})`;
|
||||
const next = value.slice(0, start) + md + value.slice(end);
|
||||
onChange(next);
|
||||
requestAnimationFrame(() => {
|
||||
el.focus();
|
||||
el.setSelectionRange(start + md.length, start + md.length);
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const filteredLangs = CODE_LANGS.filter((l) =>
|
||||
l.toLowerCase().includes(codeQuery.trim().toLowerCase())
|
||||
);
|
||||
|
||||
const ToolBtn = ({
|
||||
label,
|
||||
icon,
|
||||
onClick,
|
||||
active,
|
||||
disabled: dis,
|
||||
}: {
|
||||
label: string;
|
||||
icon: ReactNode;
|
||||
onClick: () => void;
|
||||
}[] = [
|
||||
{
|
||||
key: "bold",
|
||||
label: "粗体",
|
||||
icon: <Bold size={15} />,
|
||||
onClick: () => runWrap({ before: "**", after: "**", placeholder: "粗体" }),
|
||||
},
|
||||
{
|
||||
key: "italic",
|
||||
label: "斜体",
|
||||
icon: <Italic size={15} />,
|
||||
onClick: () => runWrap({ before: "*", after: "*", placeholder: "斜体" }),
|
||||
},
|
||||
{
|
||||
key: "code",
|
||||
label: "行内代码",
|
||||
icon: <Code size={15} />,
|
||||
onClick: () => runWrap({ before: "`", after: "`", placeholder: "code" }),
|
||||
},
|
||||
{
|
||||
key: "quote",
|
||||
label: "引用",
|
||||
icon: <Quote size={15} />,
|
||||
onClick: () =>
|
||||
runWrap({ before: "", linePrefix: "> ", placeholder: "引用内容" }),
|
||||
},
|
||||
{
|
||||
key: "list",
|
||||
label: "列表",
|
||||
icon: <List size={15} />,
|
||||
onClick: () =>
|
||||
runWrap({ before: "", linePrefix: "- ", placeholder: "列表项" }),
|
||||
},
|
||||
{
|
||||
key: "h2",
|
||||
label: "二级标题",
|
||||
icon: <Heading2 size={15} />,
|
||||
onClick: () => runWrap({ before: "## ", after: "", placeholder: "标题" }),
|
||||
},
|
||||
{
|
||||
key: "link",
|
||||
label: "链接",
|
||||
icon: <LinkIcon size={15} />,
|
||||
onClick: () =>
|
||||
runWrap({ before: "[", after: "](https://)", placeholder: "链接文字" }),
|
||||
},
|
||||
{
|
||||
key: "image",
|
||||
label: uploading ? "上传中…" : "插入图片",
|
||||
icon: <ImageIcon size={15} />,
|
||||
onClick: () => fileRef.current?.click(),
|
||||
},
|
||||
];
|
||||
active?: boolean;
|
||||
disabled?: boolean;
|
||||
}) => (
|
||||
<button
|
||||
type="button"
|
||||
className={`j13-md-tool${active ? " is-active" : ""}`}
|
||||
data-tip={label}
|
||||
aria-label={label}
|
||||
disabled={disabled || dis}
|
||||
onClick={onClick}
|
||||
>
|
||||
{icon}
|
||||
</button>
|
||||
);
|
||||
|
||||
const Sep = () => <span className="j13-md-sep" aria-hidden />;
|
||||
|
||||
return (
|
||||
<div className={`j13-md-editor${fullscreen ? " is-fullscreen" : ""}`}>
|
||||
<div className="j13-md-toolbar">
|
||||
<div className="flex items-center gap-0.5 flex-1 flex-wrap min-w-0">
|
||||
{tools.map((t) => (
|
||||
<button
|
||||
key={t.key}
|
||||
type="button"
|
||||
className="j13-md-tool"
|
||||
data-tip={t.label}
|
||||
aria-label={t.label}
|
||||
disabled={disabled || (t.key === "image" && uploading)}
|
||||
onClick={t.onClick}
|
||||
>
|
||||
{t.icon}
|
||||
</button>
|
||||
))}
|
||||
<div className="j13-md-toolbar" ref={toolbarRef}>
|
||||
<div className="j13-md-tool-groups flex items-center gap-0.5 flex-1 flex-wrap min-w-0">
|
||||
<ToolBtn
|
||||
label="粗体 Ctrl+B"
|
||||
icon={<Bold size={15} />}
|
||||
onClick={() => runWrap({ before: "**", after: "**", placeholder: "粗体" })}
|
||||
/>
|
||||
<ToolBtn
|
||||
label="斜体 Ctrl+I"
|
||||
icon={<Italic size={15} />}
|
||||
onClick={() => runWrap({ before: "*", after: "*", placeholder: "斜体" })}
|
||||
/>
|
||||
<ToolBtn
|
||||
label="删除线"
|
||||
icon={<Strikethrough size={15} />}
|
||||
onClick={() => runWrap({ before: "~~", after: "~~", placeholder: "删除线" })}
|
||||
/>
|
||||
<Sep />
|
||||
<div className="j13-md-popover-anchor relative">
|
||||
<ToolBtn
|
||||
label="标题"
|
||||
icon={
|
||||
<span className="inline-flex items-center gap-0.5">
|
||||
<Heading2 size={15} />
|
||||
<ChevronDown size={11} />
|
||||
</span>
|
||||
}
|
||||
active={popover === "heading"}
|
||||
onClick={() => openPopover("heading")}
|
||||
/>
|
||||
{popover === "heading" && (
|
||||
<div className="j13-md-popover" role="menu">
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
onClick={() => {
|
||||
runWrap({ before: "## ", after: "", placeholder: "二级标题" });
|
||||
setPopover(null);
|
||||
}}
|
||||
>
|
||||
<Heading2 size={14} /> 二级标题
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
onClick={() => {
|
||||
runWrap({ before: "### ", after: "", placeholder: "三级标题" });
|
||||
setPopover(null);
|
||||
}}
|
||||
>
|
||||
<Heading3 size={14} /> 三级标题
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Sep />
|
||||
<ToolBtn
|
||||
label="引用"
|
||||
icon={<Quote size={15} />}
|
||||
onClick={() =>
|
||||
runWrap({ before: "", linePrefix: "> ", placeholder: "引用内容" })
|
||||
}
|
||||
/>
|
||||
<ToolBtn
|
||||
label="无序列表"
|
||||
icon={<List size={15} />}
|
||||
onClick={() =>
|
||||
runWrap({ before: "", linePrefix: "- ", placeholder: "列表项" })
|
||||
}
|
||||
/>
|
||||
<ToolBtn
|
||||
label="有序列表"
|
||||
icon={<ListOrdered size={15} />}
|
||||
onClick={insertOrderedList}
|
||||
/>
|
||||
<ToolBtn label="表格" icon={<Table size={15} />} onClick={insertTable} />
|
||||
<ToolBtn
|
||||
label="分割线"
|
||||
icon={<Minus size={15} />}
|
||||
onClick={() => insertAtCursor("---")}
|
||||
/>
|
||||
<Sep />
|
||||
<ToolBtn
|
||||
label="行内代码"
|
||||
icon={<Code size={15} />}
|
||||
onClick={() => runWrap({ before: "`", after: "`", placeholder: "code" })}
|
||||
/>
|
||||
<div className="j13-md-popover-anchor relative">
|
||||
<ToolBtn
|
||||
label="代码块 Ctrl+Shift+C"
|
||||
icon={<Code2 size={15} />}
|
||||
active={popover === "code"}
|
||||
onClick={() => openPopover("code")}
|
||||
/>
|
||||
{popover === "code" && (
|
||||
<div className="j13-md-popover j13-md-popover-wide" role="dialog" aria-label="选择语言">
|
||||
<input
|
||||
autoFocus
|
||||
className="j13-md-popover-input"
|
||||
placeholder="搜索语言…"
|
||||
value={codeQuery}
|
||||
onChange={(e) => setCodeQuery(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && filteredLangs[0]) {
|
||||
e.preventDefault();
|
||||
insertCodeBlock(filteredLangs[0]);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<div className="j13-md-popover-list">
|
||||
{filteredLangs.map((lang) => (
|
||||
<button
|
||||
key={lang}
|
||||
type="button"
|
||||
onClick={() => insertCodeBlock(lang)}
|
||||
>
|
||||
{lang}
|
||||
</button>
|
||||
))}
|
||||
{filteredLangs.length === 0 && (
|
||||
<p className="meta px-2 py-3 text-center">无匹配语言</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Sep />
|
||||
<div className="j13-md-popover-anchor relative">
|
||||
<ToolBtn
|
||||
label="链接 Ctrl+K"
|
||||
icon={<LinkIcon size={15} />}
|
||||
active={popover === "link"}
|
||||
onClick={() => openPopover("link")}
|
||||
/>
|
||||
{popover === "link" && (
|
||||
<div className="j13-md-popover j13-md-popover-form" role="dialog" aria-label="插入链接">
|
||||
<label className="j13-md-field">
|
||||
<span>文字</span>
|
||||
<input
|
||||
value={linkText}
|
||||
onChange={(e) => setLinkText(e.target.value)}
|
||||
className="j13-md-popover-input"
|
||||
/>
|
||||
</label>
|
||||
<label className="j13-md-field">
|
||||
<span>URL</span>
|
||||
<input
|
||||
autoFocus
|
||||
value={linkUrl}
|
||||
onChange={(e) => setLinkUrl(e.target.value)}
|
||||
className="j13-md-popover-input"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
applyLink();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<div className="j13-md-popover-footer">
|
||||
<button type="button" className="btn btn-line btn-sm" onClick={() => setPopover(null)}>
|
||||
取消
|
||||
</button>
|
||||
<button type="button" className="btn btn-primary btn-sm" onClick={applyLink}>
|
||||
插入
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="j13-md-popover-anchor relative">
|
||||
<ToolBtn
|
||||
label={uploading ? "上传中…" : "图片"}
|
||||
icon={<ImageIcon size={15} />}
|
||||
active={popover === "image" || popover === "imageUrl"}
|
||||
disabled={uploading}
|
||||
onClick={() => openPopover("image")}
|
||||
/>
|
||||
{popover === "image" && (
|
||||
<div className="j13-md-popover" role="menu">
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
disabled={uploading}
|
||||
onClick={() => {
|
||||
setPopover(null);
|
||||
fileRef.current?.click();
|
||||
}}
|
||||
>
|
||||
<Upload size={14} /> 上传图片
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
onClick={() => openPopover("imageUrl")}
|
||||
>
|
||||
<Link2 size={14} /> 图片地址
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{popover === "imageUrl" && (
|
||||
<div className="j13-md-popover j13-md-popover-form" role="dialog" aria-label="插入图片 URL">
|
||||
<label className="j13-md-field">
|
||||
<span>说明</span>
|
||||
<input
|
||||
value={imageAlt}
|
||||
onChange={(e) => setImageAlt(e.target.value)}
|
||||
className="j13-md-popover-input"
|
||||
/>
|
||||
</label>
|
||||
<label className="j13-md-field">
|
||||
<span>URL</span>
|
||||
<input
|
||||
autoFocus
|
||||
value={imageUrl}
|
||||
onChange={(e) => setImageUrl(e.target.value)}
|
||||
className="j13-md-popover-input"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
applyImageUrl();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<div className="j13-md-popover-footer">
|
||||
<button type="button" className="btn btn-line btn-sm" onClick={() => setPopover(null)}>
|
||||
取消
|
||||
</button>
|
||||
<button type="button" className="btn btn-primary btn-sm" onClick={applyImageUrl}>
|
||||
插入
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Sep />
|
||||
<div className="j13-md-popover-anchor relative">
|
||||
<ToolBtn
|
||||
label="隐藏内容"
|
||||
icon={<Lock size={15} />}
|
||||
active={popover === "hide"}
|
||||
onClick={() => openPopover("hide")}
|
||||
/>
|
||||
{popover === "hide" && (
|
||||
<div className="j13-md-popover j13-md-popover-form" role="dialog" aria-label="插入隐藏内容">
|
||||
{hideStep === "menu" ? (
|
||||
<>
|
||||
<button type="button" className="j13-md-menu-item" onClick={() => insertHide("login")}>
|
||||
登录可见
|
||||
</button>
|
||||
<button type="button" className="j13-md-menu-item" onClick={() => insertHide("reply")}>
|
||||
回复可见
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="j13-md-menu-item"
|
||||
onClick={() => setHideStep("points")}
|
||||
>
|
||||
积分可见…
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<label className="j13-md-field">
|
||||
<span>所需积分</span>
|
||||
<input
|
||||
autoFocus
|
||||
type="number"
|
||||
min={1}
|
||||
max={100000}
|
||||
value={hidePoints}
|
||||
onChange={(e) => setHidePoints(Number(e.target.value) || 1)}
|
||||
className="j13-md-popover-input"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
if (hidePoints >= 1 && hidePoints <= 100000) {
|
||||
insertHide("points", hidePoints);
|
||||
}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<div className="j13-md-popover-footer">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-line btn-sm"
|
||||
onClick={() => setHideStep("menu")}
|
||||
>
|
||||
返回
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary btn-sm"
|
||||
onClick={() => {
|
||||
if (hidePoints < 1 || hidePoints > 100000) {
|
||||
toast("积分须在 1–100000", "error");
|
||||
return;
|
||||
}
|
||||
insertHide("points", hidePoints);
|
||||
}}
|
||||
>
|
||||
插入
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
<div className="j13-md-mode" role="tablist" aria-label="编辑模式">
|
||||
@@ -281,26 +813,46 @@ export default function MarkdownEditor({
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/webp"
|
||||
className="hidden"
|
||||
onChange={(e) => handleImagePick(e.target.files?.[0] ?? null)}
|
||||
onChange={(e) => void uploadImageFile(e.target.files?.[0] ?? null)}
|
||||
/>
|
||||
|
||||
{mode === "write" ? (
|
||||
<textarea
|
||||
ref={taRef}
|
||||
id={id}
|
||||
value={value}
|
||||
disabled={disabled}
|
||||
rows={rows}
|
||||
placeholder={placeholder}
|
||||
className="j13-md-textarea"
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
onSubmitShortcut?.();
|
||||
}
|
||||
<div
|
||||
className={`j13-md-write-wrap${dragOver ? " is-dragover" : ""}`}
|
||||
onDragEnter={(e) => {
|
||||
e.preventDefault();
|
||||
if (e.dataTransfer.types.includes("Files")) setDragOver(true);
|
||||
}}
|
||||
/>
|
||||
onDragOver={(e) => e.preventDefault()}
|
||||
onDragLeave={(e) => {
|
||||
if (e.currentTarget === e.target) setDragOver(false);
|
||||
}}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault();
|
||||
setDragOver(false);
|
||||
const file = e.dataTransfer.files?.[0];
|
||||
if (file) void uploadImageFile(file);
|
||||
}}
|
||||
>
|
||||
{dragOver && (
|
||||
<div className="j13-md-drop-mask" aria-hidden>
|
||||
放开以上传图片
|
||||
</div>
|
||||
)}
|
||||
<textarea
|
||||
ref={taRef}
|
||||
id={id}
|
||||
value={value}
|
||||
disabled={disabled}
|
||||
rows={rows}
|
||||
placeholder={placeholder}
|
||||
className="j13-md-textarea"
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
onKeyDown={onTextareaKeyDown}
|
||||
onPaste={(e) => void onPaste(e)}
|
||||
onSelect={rememberSel}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="j13-md-preview">
|
||||
{value.trim() ? (
|
||||
@@ -312,7 +864,7 @@ export default function MarkdownEditor({
|
||||
)}
|
||||
|
||||
<div className="j13-md-foot">
|
||||
<span>Markdown · Ctrl/⌘ + Enter 提交</span>
|
||||
<span>支持粘贴/拖拽图片 · Markdown · Ctrl/⌘ + Enter 提交</span>
|
||||
<span className="tabular-nums">{value.length} 字</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -17,13 +17,11 @@ import {
|
||||
} from "@/lib/api";
|
||||
import {
|
||||
POST_TYPES,
|
||||
CONTENT_ACCESS,
|
||||
BOUNTY_EXPIRE_DAYS,
|
||||
LOTTERY_EXPIRE_DAYS,
|
||||
POLL_EXPIRE_DAYS,
|
||||
normalizePostType,
|
||||
type PostTypeValue,
|
||||
type ContentAccessValue,
|
||||
} from "@/lib/postMeta";
|
||||
import { toast } from "@/lib/toast";
|
||||
import MarkdownEditor from "@/components/MarkdownEditor";
|
||||
@@ -44,8 +42,6 @@ type ComposeDraft = {
|
||||
tags: string;
|
||||
boardId: number;
|
||||
postType?: string;
|
||||
contentAccess?: string;
|
||||
accessPoints?: number;
|
||||
typeMeta?: string;
|
||||
updatedAt: number;
|
||||
};
|
||||
@@ -128,8 +124,6 @@ type EditProps = {
|
||||
initialContent: string;
|
||||
initialTags?: string;
|
||||
initialPostType?: string;
|
||||
initialContentAccess?: string;
|
||||
initialAccessPoints?: number;
|
||||
initialTypeMeta?: string;
|
||||
initialAttachments?: PostAttachment[];
|
||||
/** 投票帖:有票后禁止改选项 */
|
||||
@@ -162,14 +156,6 @@ export default function PostComposer(props: PostComposerProps) {
|
||||
const [postType, setPostType] = useState<PostTypeValue>(
|
||||
normalizePostType(isCreate ? "discussion" : props.initialPostType)
|
||||
);
|
||||
const [contentAccess, setContentAccess] = useState<ContentAccessValue>(
|
||||
(isCreate
|
||||
? "public"
|
||||
: (props.initialContentAccess as ContentAccessValue) || "public") as ContentAccessValue
|
||||
);
|
||||
const [accessPoints, setAccessPoints] = useState(
|
||||
isCreate ? 10 : props.initialAccessPoints || 10
|
||||
);
|
||||
const [typeMeta, setTypeMeta] = useState(
|
||||
isCreate ? "" : props.initialTypeMeta || ""
|
||||
);
|
||||
@@ -364,8 +350,6 @@ export default function PostComposer(props: PostComposerProps) {
|
||||
tags: serializeTags(tagList),
|
||||
boardId,
|
||||
postType,
|
||||
contentAccess,
|
||||
accessPoints,
|
||||
typeMeta,
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
@@ -380,8 +364,6 @@ export default function PostComposer(props: PostComposerProps) {
|
||||
tagList,
|
||||
boardId,
|
||||
postType,
|
||||
contentAccess,
|
||||
accessPoints,
|
||||
typeMeta,
|
||||
]);
|
||||
|
||||
@@ -392,10 +374,6 @@ export default function PostComposer(props: PostComposerProps) {
|
||||
setTagList(parseTags(draftBanner.tags || ""));
|
||||
if (draftBanner.boardId) setBoardId(draftBanner.boardId);
|
||||
if (draftBanner.postType) setPostType(normalizePostType(draftBanner.postType));
|
||||
if (draftBanner.contentAccess) {
|
||||
setContentAccess(draftBanner.contentAccess as ContentAccessValue);
|
||||
}
|
||||
if (draftBanner.accessPoints) setAccessPoints(draftBanner.accessPoints);
|
||||
if (draftBanner.typeMeta) setTypeMeta(draftBanner.typeMeta);
|
||||
setDraftBanner(null);
|
||||
skipDraftSave.current = false;
|
||||
@@ -533,7 +511,6 @@ export default function PostComposer(props: PostComposerProps) {
|
||||
title.trim().length > 0 &&
|
||||
content.trim().length > 0 &&
|
||||
(isCreate ? boardsReady && boardId > 0 : true) &&
|
||||
(contentAccess !== "points" || accessPoints > 0) &&
|
||||
(postType !== "poll" ||
|
||||
pollOptions.map((o) => o.trim()).filter(Boolean).length >= 2) &&
|
||||
(postType !== "bounty" ||
|
||||
@@ -609,8 +586,6 @@ export default function PostComposer(props: PostComposerProps) {
|
||||
content: content.trim(),
|
||||
tags,
|
||||
post_type: postType,
|
||||
content_access: contentAccess,
|
||||
access_points: contentAccess === "points" ? accessPoints : 0,
|
||||
type_meta: meta,
|
||||
attachment_ids: attIds,
|
||||
});
|
||||
@@ -634,8 +609,6 @@ export default function PostComposer(props: PostComposerProps) {
|
||||
title: title.trim(),
|
||||
content: content.trim(),
|
||||
tags,
|
||||
content_access: contentAccess,
|
||||
access_points: contentAccess === "points" ? accessPoints : 0,
|
||||
type_meta: meta,
|
||||
attachment_ids: attIds,
|
||||
});
|
||||
@@ -818,42 +791,6 @@ export default function PostComposer(props: PostComposerProps) {
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="j13-compose-meta-access">
|
||||
<label className="field-label" htmlFor="compose-access">
|
||||
正文可见性
|
||||
</label>
|
||||
<select
|
||||
id="compose-access"
|
||||
className="j13-compose-field"
|
||||
value={contentAccess}
|
||||
disabled={loading}
|
||||
onChange={(e) => setContentAccess(e.target.value as ContentAccessValue)}
|
||||
>
|
||||
{CONTENT_ACCESS.map((a) => (
|
||||
<option key={a.value} value={a.value}>
|
||||
{a.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{contentAccess === "points" && (
|
||||
<div className="mt-2 flex items-center gap-2">
|
||||
<label className="meta text-[12.5px] shrink-0" htmlFor="compose-access-pts">
|
||||
所需积分
|
||||
</label>
|
||||
<input
|
||||
id="compose-access-pts"
|
||||
type="number"
|
||||
min={1}
|
||||
max={100000}
|
||||
value={accessPoints}
|
||||
disabled={loading}
|
||||
onChange={(e) => setAccessPoints(Number(e.target.value) || 0)}
|
||||
className="j13-compose-field !py-1.5 w-28"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</section>
|
||||
@@ -1241,7 +1178,7 @@ export default function PostComposer(props: PostComposerProps) {
|
||||
disabled={loading}
|
||||
rows={18}
|
||||
placeholder={
|
||||
"从这里开始写正文…\n\n支持 Markdown;可用工具栏插入格式与图片。可点全屏沉浸写作。"
|
||||
"从这里开始写正文…\n\n工具栏可插入格式、代码块、链接、图片与隐藏内容(登录/回复/积分可见)。支持粘贴与拖拽上传图片。"
|
||||
}
|
||||
onSubmitShortcut={() => {
|
||||
if (canSubmit) void handleSubmit();
|
||||
|
||||
116
frontend/components/markdown/MdHideBlock.tsx
Normal file
116
frontend/components/markdown/MdHideBlock.tsx
Normal file
@@ -0,0 +1,116 @@
|
||||
"use client";
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { Lock } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { apiUnlockPost } from "@/lib/api";
|
||||
import { toast } from "@/lib/toast";
|
||||
import { hideKindLabel, type HideKind } from "@/lib/hideBlocks";
|
||||
|
||||
type MdHideBlockProps = {
|
||||
kind: HideKind;
|
||||
points?: number;
|
||||
locked?: boolean;
|
||||
postId?: number;
|
||||
loggedIn?: boolean;
|
||||
children?: ReactNode;
|
||||
};
|
||||
|
||||
/** 正文内嵌隐藏块:已解锁显示徽章容器;locked 显示就地门禁 */
|
||||
export default function MdHideBlock({
|
||||
kind,
|
||||
points = 0,
|
||||
locked = false,
|
||||
postId,
|
||||
loggedIn = false,
|
||||
children,
|
||||
}: MdHideBlockProps) {
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const label = hideKindLabel(kind);
|
||||
|
||||
if (locked) {
|
||||
const unlock = async () => {
|
||||
if (!postId) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await apiUnlockPost(String(postId));
|
||||
if (res.post) {
|
||||
toast("已解锁隐藏内容", "ok");
|
||||
router.refresh();
|
||||
} else {
|
||||
toast(res.error || "解锁失败", "error");
|
||||
}
|
||||
} catch {
|
||||
toast("解锁失败", "error");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<aside
|
||||
className="j13-hide-gate"
|
||||
role="note"
|
||||
aria-label={`${label}(未解锁)`}
|
||||
>
|
||||
<Lock size={22} className="j13-hide-gate-icon" aria-hidden />
|
||||
<p className="j13-hide-gate-title">此段内容{label}</p>
|
||||
<p className="j13-hide-gate-desc meta">
|
||||
{kind === "points"
|
||||
? `支付 ${points || 0} 积分后可阅读此段`
|
||||
: kind === "reply"
|
||||
? "发表一条回复后即可阅读此段"
|
||||
: "登录后即可阅读此段"}
|
||||
</p>
|
||||
<div className="j13-hide-gate-actions">
|
||||
{kind === "login" && !loggedIn && postId && (
|
||||
<Link
|
||||
href={`/login?redirect=${encodeURIComponent(`/post/${postId}`)}`}
|
||||
className="btn btn-primary"
|
||||
>
|
||||
去登录
|
||||
</Link>
|
||||
)}
|
||||
{kind === "points" && loggedIn && postId && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
disabled={busy}
|
||||
onClick={() => void unlock()}
|
||||
>
|
||||
{busy ? "解锁中…" : `支付 ${points || 0} 积分解锁`}
|
||||
</button>
|
||||
)}
|
||||
{kind === "points" && !loggedIn && postId && (
|
||||
<Link
|
||||
href={`/login?redirect=${encodeURIComponent(`/post/${postId}`)}`}
|
||||
className="btn btn-primary"
|
||||
>
|
||||
登录后解锁
|
||||
</Link>
|
||||
)}
|
||||
{kind === "reply" && (
|
||||
<a href="#comments" className="btn btn-primary">
|
||||
去回复
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="j13-hide-block" data-hide-kind={kind}>
|
||||
<div className="j13-hide-block-bar">
|
||||
<span className="j13-hide-badge">{label}</span>
|
||||
{kind === "points" && points > 0 && (
|
||||
<span className="meta text-[12px]">{points} 积分</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="j13-hide-block-body">{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -792,8 +792,6 @@ export async function apiCreatePost(data: {
|
||||
content: string;
|
||||
tags?: string;
|
||||
post_type?: string;
|
||||
content_access?: string;
|
||||
access_points?: number;
|
||||
type_meta?: string;
|
||||
attachment_ids?: number[];
|
||||
}) {
|
||||
@@ -820,8 +818,6 @@ export async function apiUpdatePost(
|
||||
title?: string;
|
||||
content?: string;
|
||||
tags?: string;
|
||||
content_access?: string;
|
||||
access_points?: number;
|
||||
type_meta?: string;
|
||||
attachment_ids?: number[];
|
||||
}
|
||||
|
||||
154
frontend/lib/hideBlocks.ts
Normal file
154
frontend/lib/hideBlocks.ts
Normal file
@@ -0,0 +1,154 @@
|
||||
/** 正文 :::hide 块解析(与 backend/markdown/hide.go 契约一致) */
|
||||
|
||||
export type HideKind = "login" | "reply" | "points";
|
||||
|
||||
export type HideSegment =
|
||||
| { type: "md"; text: string }
|
||||
| {
|
||||
type: "hide";
|
||||
kind: HideKind;
|
||||
points: number;
|
||||
locked: boolean;
|
||||
body: string;
|
||||
};
|
||||
|
||||
const OPEN_RE = /^:::hide\s+(login|reply|points)(?:\s+(\d+))?(?:\s+(locked))?\s*$/;
|
||||
|
||||
function isClose(line: string): boolean {
|
||||
return line.trim() === ":::";
|
||||
}
|
||||
|
||||
function parseOpen(trimmed: string): {
|
||||
kind: HideKind;
|
||||
points: number;
|
||||
locked: boolean;
|
||||
} | null {
|
||||
const m = OPEN_RE.exec(trimmed);
|
||||
if (!m) return null;
|
||||
const kind = m[1] as HideKind;
|
||||
const points = m[2] ? Number(m[2]) : 0;
|
||||
const locked = m[3] === "locked";
|
||||
if (kind === "points" && (!Number.isFinite(points) || points < 1)) {
|
||||
return null;
|
||||
}
|
||||
return { kind, points: kind === "points" ? points : 0, locked };
|
||||
}
|
||||
|
||||
/**
|
||||
* 将正文拆成公开 Markdown 段与隐藏块(忽略代码围栏内伪语法)。
|
||||
* 解析失败时整篇当作普通 Markdown,避免渲染崩溃。
|
||||
*/
|
||||
export function splitHideSegments(content: string): HideSegment[] {
|
||||
if (!content) return [{ type: "md", text: "" }];
|
||||
const lines = content.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
|
||||
const out: HideSegment[] = [];
|
||||
let buf: string[] = [];
|
||||
let inCode = false;
|
||||
let i = 0;
|
||||
|
||||
const flushMd = () => {
|
||||
if (buf.length === 0) return;
|
||||
out.push({ type: "md", text: buf.join("\n") });
|
||||
buf = [];
|
||||
};
|
||||
|
||||
while (i < lines.length) {
|
||||
const trimmed = lines[i].trim();
|
||||
if (trimmed.startsWith("```")) {
|
||||
inCode = !inCode;
|
||||
buf.push(lines[i]);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (inCode) {
|
||||
buf.push(lines[i]);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
const open = parseOpen(trimmed);
|
||||
if (open) {
|
||||
flushMd();
|
||||
const bodyLines: string[] = [];
|
||||
let j = i + 1;
|
||||
let innerCode = false;
|
||||
let found = false;
|
||||
while (j < lines.length) {
|
||||
const inner = lines[j].trim();
|
||||
if (inner.startsWith("```")) {
|
||||
innerCode = !innerCode;
|
||||
bodyLines.push(lines[j]);
|
||||
j++;
|
||||
continue;
|
||||
}
|
||||
if (innerCode) {
|
||||
bodyLines.push(lines[j]);
|
||||
j++;
|
||||
continue;
|
||||
}
|
||||
if (parseOpen(inner)) {
|
||||
// 嵌套:放弃隐藏语义,整段当普通文本
|
||||
buf.push(lines[i]);
|
||||
i++;
|
||||
found = false;
|
||||
break;
|
||||
}
|
||||
if (isClose(inner)) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
bodyLines.push(lines[j]);
|
||||
j++;
|
||||
}
|
||||
if (!found) {
|
||||
// 未闭合:开标记行起当普通文本
|
||||
buf.push(lines[i]);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
out.push({
|
||||
type: "hide",
|
||||
kind: open.kind,
|
||||
points: open.points,
|
||||
locked: open.locked,
|
||||
body: bodyLines.join("\n"),
|
||||
});
|
||||
i = j + 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
buf.push(lines[i]);
|
||||
i++;
|
||||
}
|
||||
flushMd();
|
||||
return out.length > 0 ? out : [{ type: "md", text: content }];
|
||||
}
|
||||
|
||||
/** 去掉锁块与标记后,供 SEO / TOC / description 使用的公开纯文本片段 */
|
||||
export function publicMarkdownForSeo(content: string): string {
|
||||
const segs = splitHideSegments(content);
|
||||
return segs
|
||||
.filter((s): s is Extract<HideSegment, { type: "md" }> => s.type === "md")
|
||||
.map((s) => s.text)
|
||||
.concat(
|
||||
segs
|
||||
.filter(
|
||||
(s): s is Extract<HideSegment, { type: "hide" }> =>
|
||||
s.type === "hide" && !s.locked
|
||||
)
|
||||
.map((s) => s.body)
|
||||
)
|
||||
.join("\n\n")
|
||||
.trim();
|
||||
}
|
||||
|
||||
export function hideKindLabel(kind: HideKind): string {
|
||||
switch (kind) {
|
||||
case "login":
|
||||
return "登录可见";
|
||||
case "reply":
|
||||
return "回复可见";
|
||||
case "points":
|
||||
return "积分可见";
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ export const CONTENT_ACCESS = [
|
||||
{ value: "login", label: "登录可见" },
|
||||
{ value: "reply", label: "回复可见" },
|
||||
{ value: "points", label: "积分可见" },
|
||||
{ value: "mixed", label: "含隐藏内容" },
|
||||
] as const;
|
||||
|
||||
export type ContentAccessValue = (typeof CONTENT_ACCESS)[number]["value"];
|
||||
|
||||
Reference in New Issue
Block a user