feat(hide): 密码可见隐藏块,发帖双栏预览与门禁体验修复

增加密码解锁与游客签名 cookie;发帖页对齐 1440 并默认双栏预览;修复 locked 解析、按钮对比度与回复聚焦。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-09-17 05:46:42 +08:00
parent 01e2fd05ca
commit c44b0efa7d
23 changed files with 911 additions and 132 deletions

View File

@@ -10,7 +10,7 @@ export default function ComposeLayout({
return (
<div
data-compose-viewport
className="flex flex-col flex-1 min-h-0 w-full max-w-6xl mx-auto"
className="flex flex-col flex-1 min-h-0 w-full"
>
{children}
</div>

View File

@@ -1367,14 +1367,26 @@ body {
text-align: left;
padding: 8px 10px;
border-radius: 8px;
border: 0;
appearance: none;
-webkit-appearance: none;
font-size: 13px;
color: var(--ink);
background: transparent;
font-weight: 500;
line-height: 1.35;
cursor: pointer;
/* 强制可读对比:避免暗色下系统 buttonface 浅底 + 浅字 */
color: var(--ink) !important;
background: transparent !important;
}
.j13-md-popover button[role="menuitem"]:hover,
.j13-md-menu-item:hover {
background: var(--accent-soft);
color: var(--accent);
background: var(--panel-2) !important;
color: var(--ink) !important;
}
.j13-md-popover button[role="menuitem"]:focus-visible,
.j13-md-menu-item:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 0;
}
.j13-md-popover-input {
width: 100%;
@@ -1401,13 +1413,18 @@ body {
text-align: left;
padding: 7px 10px;
border-radius: 8px;
border: 0;
appearance: none;
-webkit-appearance: none;
font-size: 12.5px;
font-family: var(--font-mono, ui-monospace, monospace);
color: var(--ink-2);
cursor: pointer;
color: var(--ink-2) !important;
background: transparent !important;
}
.j13-md-popover-list button:hover {
background: var(--accent-soft);
color: var(--accent);
background: var(--panel-2) !important;
color: var(--ink) !important;
}
.j13-md-field {
display: flex;
@@ -1433,6 +1450,8 @@ body {
display: flex;
flex-direction: column;
min-height: 0;
min-width: 0;
height: 100%;
}
.j13-md-write-wrap.is-dragover .j13-md-textarea {
opacity: 0.35;
@@ -1462,18 +1481,65 @@ body {
}
.j13-md-mode button {
height: 30px;
padding: 0 12px;
padding: 0 10px;
border-radius: 999px;
border: 0;
appearance: none;
-webkit-appearance: none;
font-size: 12.5px;
font-weight: 500;
display: inline-flex;
align-items: center;
gap: 5px;
color: var(--ink-3);
cursor: pointer;
color: var(--ink-2);
background: transparent;
}
.j13-md-mode button.is-on {
background: var(--accent-soft);
background: color-mix(in srgb, var(--accent) 18%, var(--panel));
color: var(--accent);
font-weight: 600;
}
.j13-md-panes {
flex: 1 1 auto;
display: grid;
grid-template-columns: 1fr;
grid-template-rows: minmax(0, 1fr);
min-height: 0;
gap: 0;
}
.j13-md-panes.is-split {
grid-template-columns: 1fr;
}
@media (min-width: 960px) {
.j13-md-panes.is-split {
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
}
.j13-md-panes.is-split .j13-md-write-wrap {
border-right: 1px solid var(--line);
padding-right: 1rem;
margin-right: 0;
}
.j13-md-panes.is-split .j13-md-preview {
padding-left: 1rem;
}
}
/* 窄屏双栏:上下分栏仍同时显示 */
@media (max-width: 959px) {
.j13-md-panes.is-split {
grid-template-rows: minmax(220px, 1fr) minmax(220px, 1fr);
gap: 0;
}
.j13-md-panes.is-split .j13-md-write-wrap {
border-bottom: 1px solid var(--line);
padding-bottom: 0.5rem;
}
.j13-md-panes.is-split .j13-md-preview {
padding-top: 0.35rem;
}
}
.j13-md-panes > [hidden] {
display: none !important;
}
.j13-md-textarea {
flex: 1 1 auto;
@@ -1505,9 +1571,23 @@ body {
.j13-md-preview {
flex: 1 1 auto;
min-height: 320px;
height: 100%;
overflow-y: auto;
padding: 1rem 0 0.75rem;
padding: 0.65rem 0 0.75rem;
background: transparent;
min-width: 0;
}
.j13-md-preview-label {
font-size: 11.5px;
font-weight: 600;
letter-spacing: 0.04em;
text-transform: uppercase;
margin-bottom: 0.35rem;
color: var(--ink-3);
}
.j13-md-panes.is-preview .j13-md-preview-label,
.j13-md-panes.is-write .j13-md-preview-label {
display: none;
}
.j13-md-foot {
flex-shrink: 0;
@@ -1545,8 +1625,8 @@ body {
border-radius: 999px;
font-size: 11.5px;
font-weight: 600;
color: var(--accent);
background: var(--accent-soft);
color: var(--accent-on);
background: var(--accent);
}
.j13-hide-block-body {
padding: 12px 16px 14px;
@@ -1581,6 +1661,52 @@ body {
gap: 8px;
flex-wrap: wrap;
}
.j13-hide-pwd-wrap {
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
width: 100%;
max-width: 360px;
margin: 0 auto;
}
.j13-hide-pwd-form {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
justify-content: center;
width: 100%;
}
.j13-hide-pwd-input {
flex: 1 1 160px;
min-width: 140px;
height: 36px;
padding: 0 12px;
border-radius: 10px;
border: 1px solid var(--line-2);
background: var(--panel);
color: var(--ink);
font-size: 14px;
}
.j13-hide-pwd-input:focus {
outline: 2px solid var(--accent);
outline-offset: 0;
}
.j13-hide-pwd-input.is-invalid {
border-color: var(--danger);
outline: none;
box-shadow: 0 0 0 2px color-mix(in srgb, var(--danger) 22%, transparent);
}
.j13-hide-pwd-error {
margin: 0;
width: 100%;
text-align: center;
font-size: 13px;
font-weight: 600;
line-height: 1.4;
color: var(--danger);
}
.j13-compose-shell {
background: var(--panel);
@@ -3703,6 +3829,18 @@ a.j13-mention-token:hover {
text-underline-offset: 3px;
font-weight: 500;
}
/* 正文内嵌按钮链接:未分层的 .prose-content a 会盖掉 @layer 的 .btn-primary 字色 */
.prose-content a.btn,
.prose-content a.btn-primary,
.prose-content a.btn-accent {
color: var(--accent-on) !important;
text-decoration: none;
font-weight: 500;
}
.prose-content a.btn-line {
color: var(--ink) !important;
text-decoration: none;
}
.prose-content img,
.prose-content .md-content-img {
max-width: 100%;

View File

@@ -37,7 +37,7 @@ export default async function EditPostPage({ params }: PageProps) {
return (
<div
data-compose-viewport
className="j13-compose-page w-full max-w-6xl mx-auto"
className="j13-compose-page w-full"
>
<nav className="meta mb-4 flex items-center gap-1.5 flex-wrap text-[13px] shrink-0">
<Link href="/" className="hover:text-[var(--accent)] transition-colors">

View File

@@ -24,7 +24,7 @@ import {
type Board,
type CommentsResponse,
} from "@/lib/api";
import { authCookieHeader } from "@/lib/cookies";
import { postViewerCookieHeader } from "@/lib/cookies";
import { getMeCached, getPublicSettingsCached } from "@/lib/serverData";
import CommentSection from "@/components/CommentSection";
import PostActions from "@/components/PostActions";
@@ -52,7 +52,7 @@ export async function generateMetadata({ params }: PageProps): Promise<Metadata>
const { id } = await params;
try {
// 带登录态:作者/管理团队看待审帖时标签标题也应是真实标题而非"帖子不存在"
const { post } = await fetchPostDetail(id, authCookieHeader(await cookies()));
const { post } = await fetchPostDetail(id, postViewerCookieHeader(await cookies()));
if (post.tombstone) {
return {
title: post.title || "帖子已删除",
@@ -402,7 +402,7 @@ export default async function PostDetailPage({ params, searchParams }: PageProps
const { id } = await params;
const sp = await searchParams;
const commentPage = Math.max(1, parseInt(sp.page || "1", 10) || 1);
const cookie = authCookieHeader(await cookies());
const cookie = postViewerCookieHeader(await cookies());
// 待审/被拒帖子对无权访问者由后端返回 404,这里落到全局 not-found 页而非 500
let post: Awaited<ReturnType<typeof fetchPostDetail>>["post"];
try {

View File

@@ -136,6 +136,22 @@ export default function CommentSection({
}
}, [commentsOpen]);
// 登录回跳 / 隐藏块「去回复」:滚到评论框并聚焦
useEffect(() => {
if (!user || !commentsOpen) return;
const focusComposer = () => {
const hash = window.location.hash;
if (hash !== "#comment-input" && hash !== "#comments") return;
const el = textareaRef.current ?? document.getElementById("comment-input");
if (!(el instanceof HTMLTextAreaElement)) return;
el.scrollIntoView({ behavior: "smooth", block: "center" });
window.setTimeout(() => el.focus({ preventScroll: true }), 280);
};
focusComposer();
window.addEventListener("hashchange", focusComposer);
return () => window.removeEventListener("hashchange", focusComposer);
}, [user, commentsOpen]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!commentsOpen || !content.trim()) return;
@@ -1034,7 +1050,7 @@ export default function CommentSection({
}
return (
<section className="panel p-6 sm:p-8 mt-6" aria-label="评论区">
<section id="comments" className="panel p-6 sm:p-8 mt-6 scroll-mt-24" aria-label="评论区">
<div className="flex items-center gap-2.5 mb-6">
<h2 className="text-lg font-semibold" style={{ color: "var(--ink)" }}>
评论
@@ -1063,7 +1079,7 @@ export default function CommentSection({
}}
placeholder="友善发言,发表一个新楼层..."
rows={3}
className="field"
className="field scroll-mt-28"
aria-label="写评论"
/>
<div className="flex items-center justify-between gap-3 mt-2.5">

View File

@@ -5,6 +5,7 @@ import {
useState,
useCallback,
useEffect,
useDeferredValue,
type ReactNode,
type KeyboardEvent as ReactKeyboardEvent,
} from "react";
@@ -27,6 +28,7 @@ import {
Pencil,
Maximize2,
Minimize2,
Columns2,
Lock,
ChevronDown,
Upload,
@@ -47,6 +49,8 @@ type MarkdownEditorProps = {
id?: string;
};
type EditorMode = "split" | "write" | "preview";
type WrapOpts = {
before: string;
after?: string;
@@ -107,7 +111,8 @@ export default function MarkdownEditor({
const taRef = useRef<HTMLTextAreaElement>(null);
const fileRef = useRef<HTMLInputElement>(null);
const toolbarRef = useRef<HTMLDivElement>(null);
const [mode, setMode] = useState<"write" | "preview">("write");
const [mode, setMode] = useState<EditorMode>("split");
const deferredValue = useDeferredValue(value);
const [uploading, setUploading] = useState(false);
const [fullscreen, setFullscreen] = useState(false);
const [dragOver, setDragOver] = useState(false);
@@ -118,7 +123,8 @@ export default function MarkdownEditor({
const [imageAlt, setImageAlt] = useState("图片");
const [codeQuery, setCodeQuery] = useState("");
const [hidePoints, setHidePoints] = useState(10);
const [hideStep, setHideStep] = useState<"menu" | "points">("menu");
const [hidePassword, setHidePassword] = useState("");
const [hideStep, setHideStep] = useState<"menu" | "points" | "password">("menu");
const savedSel = useRef<{ start: number; end: number } | null>(null);
useEffect(() => {
@@ -260,6 +266,7 @@ export default function MarkdownEditor({
if (kind === "hide") {
setHideStep("menu");
setHidePoints(10);
setHidePassword("");
}
setPopover((prev) => (prev === kind ? null : kind));
};
@@ -320,17 +327,23 @@ export default function MarkdownEditor({
setPopover(null);
};
const insertHide = (kind: "login" | "reply" | "points", points?: number) => {
const insertHide = (
kind: "login" | "reply" | "points" | "password",
points?: number,
password?: string
) => {
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}`;
let open = `:::hide ${kind}`;
if (kind === "points") {
open = `:::hide points ${points || 10}`;
} else if (kind === "password") {
open = `:::hide password ${password || "password"}`;
}
const block = `${open}\n${body}\n:::`;
const padBefore = start > 0 && value[start - 1] !== "\n" ? "\n" : "";
const padAfter = end < value.length && value[end] !== "\n" ? "\n" : "";
@@ -724,8 +737,15 @@ export default function MarkdownEditor({
>
积分可见…
</button>
<button
type="button"
className="j13-md-menu-item"
onClick={() => setHideStep("password")}
>
密码可见…
</button>
</>
) : (
) : hideStep === "points" ? (
<>
<label className="j13-md-field">
<span>所需积分</span>
@@ -770,6 +790,53 @@ export default function MarkdownEditor({
</button>
</div>
</>
) : (
<>
<label className="j13-md-field">
<span>查看密码(不含空格,1–64 字)</span>
<input
autoFocus
type="text"
value={hidePassword}
maxLength={64}
placeholder="例如:secret"
onChange={(e) => setHidePassword(e.target.value)}
className="j13-md-popover-input"
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
const p = hidePassword.trim();
if (p && !/\s/.test(p)) {
insertHide("password", undefined, p);
}
}
}}
/>
</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={() => {
const p = hidePassword.trim();
if (!p || /\s/.test(p) || p.length > 64) {
toast("密码须为 1–64 字符且不含空格", "error");
return;
}
insertHide("password", undefined, p);
}}
>
插入
</button>
</div>
</>
)}
</div>
)}
@@ -786,6 +853,15 @@ export default function MarkdownEditor({
>
<Pencil size={12} /> 编写
</button>
<button
type="button"
role="tab"
aria-selected={mode === "split"}
className={mode === "split" ? "is-on" : ""}
onClick={() => setMode("split")}
>
<Columns2 size={12} /> 双栏
</button>
<button
type="button"
role="tab"
@@ -816,9 +892,10 @@ export default function MarkdownEditor({
onChange={(e) => void uploadImageFile(e.target.files?.[0] ?? null)}
/>
{mode === "write" ? (
<div className={`j13-md-panes is-${mode}`}>
<div
className={`j13-md-write-wrap${dragOver ? " is-dragover" : ""}`}
hidden={mode === "preview"}
onDragEnter={(e) => {
e.preventDefault();
if (e.dataTransfer.types.includes("Files")) setDragOver(true);
@@ -853,15 +930,17 @@ export default function MarkdownEditor({
onSelect={rememberSel}
/>
</div>
) : (
<div className="j13-md-preview">
{value.trim() ? (
<MarkdownBodyClient content={value} />
<div className="j13-md-preview" hidden={mode === "write"}>
<div className="j13-md-preview-label meta" aria-hidden>
预览
</div>
{deferredValue.trim() ? (
<MarkdownBodyClient content={deferredValue} />
) : (
<p className="meta text-center py-16">暂无内容可预览</p>
)}
</div>
)}
</div>
<div className="j13-md-foot">
<span>支持粘贴/拖拽图片 · Markdown · Ctrl/⌘ + Enter 提交</span>

View File

@@ -1178,7 +1178,7 @@ export default function PostComposer(props: PostComposerProps) {
disabled={loading}
rows={18}
placeholder={
"从这里开始写正文…\n\n工具栏可插入格式、代码块、链接、图片与隐藏内容(登录/回复/积分可见)。支持粘贴与拖拽上传图片。"
"从这里开始写正文…\n\n工具栏可插入格式、代码块、链接、图片与隐藏内容(登录/回复/积分/密码可见)。支持粘贴与拖拽上传图片;默认双栏实时预览。"
}
onSubmitShortcut={() => {
if (canSubmit) void handleSubmit();

View File

@@ -1,14 +1,27 @@
"use client";
import type { ReactNode } from "react";
import type { ReactNode, FormEvent } 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 { useId, useState } from "react";
import { apiUnlockPost, apiUnlockPostPassword } from "@/lib/api";
import { CSRF_COOKIE } from "@/lib/cookies";
import { toast } from "@/lib/toast";
import { hideKindLabel, type HideKind } from "@/lib/hideBlocks";
/** 若浏览器尚无 CSRF cookie,请求公开接口以触发后端签发 */
async function ensureGuestCSRF() {
if (typeof document === "undefined") return;
const escaped = CSRF_COOKIE.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
if (new RegExp(`(?:^|;\\s*)${escaped}=`).test(document.cookie)) return;
try {
await fetch("/api/me", { credentials: "include", cache: "no-store" });
} catch {
/* 忽略:后续解锁会报 CSRF 错误 */
}
}
type MdHideBlockProps = {
kind: HideKind;
points?: number;
@@ -28,11 +41,14 @@ export default function MdHideBlock({
children,
}: MdHideBlockProps) {
const router = useRouter();
const pwdErrId = useId();
const [busy, setBusy] = useState(false);
const [pwd, setPwd] = useState("");
const [pwdError, setPwdError] = useState("");
const label = hideKindLabel(kind);
if (locked) {
const unlock = async () => {
const unlockPoints = async () => {
if (!postId) return;
setBusy(true);
try {
@@ -50,6 +66,35 @@ export default function MdHideBlock({
}
};
const unlockPassword = async (e: FormEvent) => {
e.preventDefault();
if (!postId) return;
const password = pwd.trim();
if (!password) {
setPwdError("请输入密码");
return;
}
setBusy(true);
setPwdError("");
try {
// 游客可能尚无 CSRF:先打一次公开 GET 让后端签发,再提交解锁
await ensureGuestCSRF();
const res = await apiUnlockPostPassword(String(postId), password);
if (res.post) {
toast("密码正确,已解锁", "ok");
setPwd("");
setPwdError("");
router.refresh();
} else {
setPwdError(res.error || "密码错误,请重试");
}
} catch {
setPwdError("验证失败,请稍后重试");
} finally {
setBusy(false);
}
};
return (
<aside
className="j13-hide-gate"
@@ -62,8 +107,12 @@ export default function MdHideBlock({
{kind === "points"
? `支付 ${points || 0} 积分后可阅读此段`
: kind === "reply"
? "发表一条回复后即可阅读此段"
: "登录后即可阅读此段"}
? loggedIn
? "发表一条回复后即可阅读此段"
: "登录并发表一条回复后即可阅读此段"
: kind === "password"
? "输入正确密码后可阅读此段"
: "登录后即可阅读此段"}
</p>
<div className="j13-hide-gate-actions">
{kind === "login" && !loggedIn && postId && (
@@ -79,7 +128,7 @@ export default function MdHideBlock({
type="button"
className="btn btn-primary"
disabled={busy}
onClick={() => void unlock()}
onClick={() => void unlockPoints()}
>
{busy ? "解锁中…" : `支付 ${points || 0} 积分解锁`}
</button>
@@ -92,11 +141,67 @@ export default function MdHideBlock({
登录后解锁
</Link>
)}
{kind === "reply" && (
<a href="#comments" className="btn btn-primary">
{kind === "reply" && postId && !loggedIn && (
<Link
href={`/login?redirect=${encodeURIComponent(`/post/${postId}#comment-input`)}`}
className="btn btn-primary"
>
登录后去回复
</Link>
)}
{kind === "reply" && loggedIn && (
<a
href="#comment-input"
className="btn btn-primary"
onClick={(e) => {
e.preventDefault();
const el = document.getElementById("comment-input");
if (!(el instanceof HTMLTextAreaElement)) {
document.getElementById("comments")?.scrollIntoView({
behavior: "smooth",
block: "start",
});
return;
}
el.scrollIntoView({ behavior: "smooth", block: "center" });
window.setTimeout(() => {
el.focus({ preventScroll: true });
}, 280);
}}
>
去回复
</a>
)}
{kind === "password" && postId && (
<div className="j13-hide-pwd-wrap">
<form className="j13-hide-pwd-form" onSubmit={(e) => void unlockPassword(e)}>
<input
type="password"
className={`j13-hide-pwd-input${pwdError ? " is-invalid" : ""}`}
placeholder="输入密码"
value={pwd}
maxLength={64}
autoComplete="off"
disabled={busy}
aria-invalid={pwdError ? true : undefined}
aria-describedby={pwdError ? pwdErrId : undefined}
onChange={(e) => {
setPwd(e.target.value);
if (pwdError) setPwdError("");
}}
aria-label="隐藏内容密码"
/>
<button type="submit" className="btn btn-primary" disabled={busy}>
{busy ? "验证中…" : "查看"}
</button>
</form>
{pwdError && (
<p id={pwdErrId} className="j13-hide-pwd-error" role="alert">
{pwdError}
</p>
)}
</div>
)}
</div>
</aside>
);

View File

@@ -838,6 +838,15 @@ export async function apiUnlockPost(postId: string) {
return res.json();
}
export async function apiUnlockPostPassword(postId: string, password: string) {
const res = await fetchWithRefresh(`/api/posts/${postId}/unlock-password`, {
method: "POST",
headers: clientHeaders({ "Content-Type": "application/json" }),
body: JSON.stringify({ password }),
});
return res.json();
}
export async function apiGetPoints(): Promise<{ points: number }> {
const res = await fetchWithRefresh("/api/points", {
method: "GET",

View File

@@ -7,10 +7,17 @@ export const TOKEN_COOKIE = `${HOST_PREFIX}j13_token`;
export const REFRESH_COOKIE = `${HOST_PREFIX}j13_refresh`;
export const CSRF_COOKIE = `${HOST_PREFIX}j13_csrf`;
/** 密码隐藏块解锁 cookie 前缀(与 backend HidePasswordCookie 一致) */
export const HIDE_PWD_COOKIE_PREFIX = "j13_hp_";
type CookieReader = {
get(name: string): { value: string } | undefined;
};
type CookieStoreLike = CookieReader & {
getAll?: () => { name: string; value: string }[];
};
// 构造转发给后端的最小 Cookie 头:SSR 公开/鉴权接口只需要 access token 来
// 识别用户(填充 liked 等状态),不应把 refresh token、主题等无关 cookie 全量转发。
// 返回空串表示当前无登录凭据,调用方应省略 Cookie 头。
@@ -19,6 +26,24 @@ export function authCookieHeader(store: CookieReader): string {
return token ? `${TOKEN_COOKIE}=${token.value}` : "";
}
/**
* 帖子详情 SSR:access token + 密码隐藏块解锁 cookie。
* 解锁 cookie 为 HttpOnly,必须随 SSR 转发,否则 refresh 后密码块会再次锁上。
*/
export function postViewerCookieHeader(store: CookieStoreLike): string {
const parts: string[] = [];
const auth = authCookieHeader(store);
if (auth) parts.push(auth);
if (typeof store.getAll === "function") {
for (const c of store.getAll()) {
if (c.name.startsWith(HIDE_PWD_COOKIE_PREFIX)) {
parts.push(`${c.name}=${c.value}`);
}
}
}
return parts.join("; ");
}
// 客户端判断浏览器是否可能持有登录态:j13_csrf 非 HttpOnly 可读,
// 生命周期与 refresh 一致,适合作为挂载后静默校正的触发信号。
export function hasAuthCookieHint(): boolean {

View File

@@ -1,6 +1,6 @@
/** 正文 :::hide 块解析(与 backend/markdown/hide.go 契约一致) */
export type HideKind = "login" | "reply" | "points";
export type HideKind = "login" | "reply" | "points" | "password";
export type HideSegment =
| { type: "md"; text: string }
@@ -12,26 +12,50 @@ export type HideSegment =
body: string;
};
const OPEN_RE = /^:::hide\s+(login|reply|points)(?:\s+(\d+))?(?:\s+(locked))?\s*$/;
const HIDE_KINDS = new Set<HideKind>(["login", "reply", "points", "password"]);
function isClose(line: string): boolean {
return line.trim() === ":::";
}
/** 与 Go parseOpenMarker 对齐::::hide <kind> [points|password] [locked] */
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;
if (!trimmed.startsWith(":::hide")) return null;
const parts = trimmed
.slice(":::hide".length)
.trim()
.split(/\s+/)
.filter(Boolean);
if (parts.length === 0) return null;
const kind = parts[0] as HideKind;
if (!HIDE_KINDS.has(kind)) return null;
let idx = 1;
let points = 0;
let locked = false;
if (kind === "points") {
if (idx >= parts.length) return null;
const n = Number(parts[idx]);
if (!Number.isFinite(n) || n < 1 || n > 100000) return null;
points = n;
idx++;
} else if (kind === "password") {
// 脱敏::::hide password locked;原文::::hide password <pwd> [locked]
if (idx < parts.length && parts[idx] !== "locked") {
idx++;
}
}
return { kind, points: kind === "points" ? points : 0, locked };
for (; idx < parts.length; idx++) {
if (parts[idx] === "locked") locked = true;
else return null;
}
return { kind, points, locked };
}
/**
@@ -87,7 +111,6 @@ export function splitHideSegments(content: string): HideSegment[] {
continue;
}
if (parseOpen(inner)) {
// 嵌套:放弃隐藏语义,整段当普通文本
buf.push(lines[i]);
i++;
found = false;
@@ -101,7 +124,6 @@ export function splitHideSegments(content: string): HideSegment[] {
j++;
}
if (!found) {
// 未闭合:开标记行起当普通文本
buf.push(lines[i]);
i++;
continue;
@@ -150,5 +172,7 @@ export function hideKindLabel(kind: HideKind): string {
return "回复可见";
case "points":
return "积分可见";
case "password":
return "密码可见";
}
}

View File

@@ -15,6 +15,7 @@ export const CONTENT_ACCESS = [
{ value: "login", label: "登录可见" },
{ value: "reply", label: "回复可见" },
{ value: "points", label: "积分可见" },
{ value: "password", label: "密码可见" },
{ value: "mixed", label: "含隐藏内容" },
] as const;