feat(settings): 后台可配置 Markdown 代码块自动折叠与阈值行数

支持开关与 0–100 行阈值(0 为无预览),经站点设置与 WS 热更新;短代码在视口内收起时不再回滚浏览位置。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-09-16 06:43:37 +08:00
parent b6e9966ba8
commit 809d8f1df7
8 changed files with 349 additions and 23 deletions

View File

@@ -2,6 +2,7 @@
import { useState } from "react";
import {
Code2,
Globe,
Loader2,
Save,
@@ -47,13 +48,25 @@ export default function SettingsAdmin({ initial }: { initial: PublicSettings })
const [siteName, setSiteName] = useState(initial.site_name);
const [siteDescription, setSiteDescription] = useState(initial.site_description);
const [allowRegister, setAllowRegister] = useState(initial.allow_register);
const [codeAutoFold, setCodeAutoFold] = useState(
initial.code_block_auto_fold !== false
);
const [foldLines, setFoldLines] = useState(
Number.isFinite(initial.code_block_fold_lines) ? initial.code_block_fold_lines : 5
);
const [savedFoldLines, setSavedFoldLines] = useState(
Number.isFinite(initial.code_block_fold_lines) ? initial.code_block_fold_lines : 5
);
const [savedName, setSavedName] = useState(initial.site_name);
const [savedDesc, setSavedDesc] = useState(initial.site_description);
const [saving, setSaving] = useState(false);
const [togglingReg, setTogglingReg] = useState(false);
const [togglingFold, setTogglingFold] = useState(false);
const [savingFoldLines, setSavingFoldLines] = useState(false);
const dirty =
siteName.trim() !== savedName || siteDescription.trim() !== savedDesc;
const foldLinesDirty = foldLines !== savedFoldLines;
const saveIdentity = async () => {
if (saving) return;
@@ -95,6 +108,49 @@ export default function SettingsAdmin({ initial }: { initial: PublicSettings })
}
};
const toggleCodeFold = async () => {
if (togglingFold) return;
const next = !codeAutoFold;
setTogglingFold(true);
try {
const res = await apiUpdateSiteSettings({ code_block_auto_fold: next });
setCodeAutoFold(res.code_block_auto_fold);
toast(
res.code_block_auto_fold
? `已开启代码块自动折叠(超过 ${res.code_block_fold_lines} 行)`
: "已关闭代码块自动折叠",
"ok"
);
} catch (e) {
toast(e instanceof Error ? e.message : "保存失败");
} finally {
setTogglingFold(false);
}
};
const saveFoldLines = async () => {
if (savingFoldLines) return;
const raw = Math.round(Number(foldLines));
const n = Number.isFinite(raw) ? Math.max(0, Math.min(100, raw)) : 5;
setSavingFoldLines(true);
try {
const res = await apiUpdateSiteSettings({ code_block_fold_lines: n });
setFoldLines(res.code_block_fold_lines);
setSavedFoldLines(res.code_block_fold_lines);
toast(
res.code_block_fold_lines === 0
? "折叠预览已设为 0 行(无预览)"
: `折叠阈值已设为超过 ${res.code_block_fold_lines} 行`,
"ok"
);
} catch (e) {
toast(e instanceof Error ? e.message : "保存失败");
} finally {
setSavingFoldLines(false);
}
};
return (
<div className="max-w-3xl">
<div className="mb-5">
@@ -174,6 +230,62 @@ export default function SettingsAdmin({ initial }: { initial: PublicSettings })
label="开放注册"
/>
</section>
<section className="j13-module p-5 sm:p-6 mb-5">
<div className="flex items-start justify-between gap-4 flex-wrap">
<div className="min-w-0 flex-1">
<h2 className="text-[15px] font-semibold flex items-center gap-1.5" style={{ color: "var(--ink)" }}>
<Code2 size={15} /> 代码块自动折叠
</h2>
<p className="meta text-[12.5px] mt-1 leading-relaxed">
开启后,帖子与评论中超过阈值行数的 Markdown 代码块默认折叠,读者可点「展开全部」。关闭则始终完整展示。
</p>
</div>
<Switch
checked={codeAutoFold}
disabled={togglingFold}
onChange={() => void toggleCodeFold()}
label="代码块自动折叠"
/>
</div>
{codeAutoFold ? (
<div className="mt-4 pt-4 border-t border-[var(--line)]">
<label className="field-label" htmlFor="fold-lines">
折叠行数阈值
</label>
<p className="meta text-[12.5px] mb-2.5 leading-relaxed">
代码块行数超过该值时折叠;折叠后约露出同样行数。设为 0 表示无预览。范围 0–100,默认 5。
</p>
<div className="flex flex-wrap items-center gap-2.5">
<input
id="fold-lines"
type="number"
min={0}
max={100}
className="field w-24"
value={foldLines}
onChange={(e) => setFoldLines(Number(e.target.value))}
aria-label="折叠行数阈值"
/>
<span className="meta text-[12.5px]">行</span>
<button
type="button"
className="btn btn-line btn-sm"
disabled={!foldLinesDirty || savingFoldLines}
onClick={() => void saveFoldLines()}
>
{savingFoldLines ? (
<Loader2 size={14} className="animate-spin" />
) : (
<Save size={14} />
)}
保存
</button>
</div>
</div>
) : null}
</section>
</div>
);
}

View File

@@ -9,6 +9,7 @@ import TipHost from "@/components/TipHost";
import AccountGuard from "@/components/AccountGuard";
import ThemeSync from "@/components/ThemeSync";
import RealtimeProvider from "@/components/RealtimeProvider";
import CodeFoldProvider from "@/components/markdown/CodeFoldProvider";
import type { User } from "@/lib/api";
import { getMeCached, getPublicSettingsCached } from "@/lib/serverData";
import { TOKEN_COOKIE, authCookieHeader } from "@/lib/cookies";
@@ -115,7 +116,12 @@ export default async function RootLayout({
tabIndex={-1}
className="flex-1 w-full max-w-[1440px] mx-auto px-4 sm:px-6 py-7 sm:py-9 outline-none"
>
{children}
<CodeFoldProvider
initialEnabled={settings.code_block_auto_fold}
initialFoldLines={settings.code_block_fold_lines}
>
{children}
</CodeFoldProvider>
</main>
<Footer siteName={settings.site_name} />
<Toaster />

View File

@@ -0,0 +1,78 @@
"use client";
import {
createContext,
useContext,
useEffect,
useState,
type ReactNode,
} from "react";
import { realtime, RT_SETTINGS_CHANGED, type RtSettingsData } from "@/lib/realtime";
export type CodeFoldConfig = {
/** 是否启用自动折叠 */
enabled: boolean;
/** 超过该行数则折叠(预览高度约同;0=无预览) */
foldLines: number;
};
const DEFAULT_CONFIG: CodeFoldConfig = { enabled: true, foldLines: 5 };
const CodeFoldContext = createContext<CodeFoldConfig>(DEFAULT_CONFIG);
/** 代码块自动折叠配置(站点设置) */
export function useCodeFoldConfig(): CodeFoldConfig {
return useContext(CodeFoldContext);
}
function clampFoldLines(n: unknown): number {
if (typeof n !== "number" || !Number.isFinite(n)) return DEFAULT_CONFIG.foldLines;
const r = Math.round(n);
if (r < 0 || r > 100) return DEFAULT_CONFIG.foldLines;
return r;
}
/**
* 根布局注入:SSR 初值 + settings:changed 热更新。
*/
export default function CodeFoldProvider({
initialEnabled = true,
initialFoldLines = 5,
children,
}: {
initialEnabled?: boolean;
initialFoldLines?: number;
children: ReactNode;
}) {
const [config, setConfig] = useState<CodeFoldConfig>(() => ({
enabled: initialEnabled !== false,
foldLines: clampFoldLines(initialFoldLines),
}));
useEffect(() => {
setConfig({
enabled: initialEnabled !== false,
foldLines: clampFoldLines(initialFoldLines),
});
}, [initialEnabled, initialFoldLines]);
useEffect(() => {
return realtime.on<RtSettingsData>(RT_SETTINGS_CHANGED, (data) => {
if (!data) return;
setConfig((prev) => ({
enabled:
typeof data.code_block_auto_fold === "boolean"
? data.code_block_auto_fold
: prev.enabled,
foldLines:
typeof data.code_block_fold_lines === "number"
? clampFoldLines(data.code_block_fold_lines)
: prev.foldLines,
}));
});
}, []);
return (
<CodeFoldContext.Provider value={config}>{children}</CodeFoldContext.Provider>
);
}

View File

@@ -11,11 +11,13 @@ import {
} from "react";
import { Check, Copy, ChevronDown, ChevronUp } from "lucide-react";
import { toast } from "@/lib/toast";
import { useCodeFoldConfig } from "./CodeFoldProvider";
const COLLAPSE_LINE_THRESHOLD = 5;
/** 约 5 行代码高度(含行高) */
const COLLAPSED_MAX_HEIGHT = "7.75rem";
/** 折叠预览高度:0=无预览;否则上下 padding ≈1.7rem + 每行 ≈1.21em */
function collapsedMaxHeight(foldLines: number): string {
if (foldLines <= 0) return "0px";
return `calc(1.7rem + ${foldLines} * 1.21em)`;
}
type MdCodeBlockProps = HTMLAttributes<HTMLPreElement> & {
children?: ReactNode;
};
@@ -125,10 +127,11 @@ function hasShikiTokens(node: ReactNode): boolean {
return hasShikiTokens(props.children as ReactNode);
}
/** Markdown 代码块:语言标签、复制、>5 行默认折叠;客户端仅在未真正着色时补色 */
/** Markdown 代码块:语言标签、复制、超阈值行数默认折叠;客户端仅在未真正着色时补色 */
export default function MdCodeBlock({ children, className, ...rest }: MdCodeBlockProps) {
const rootRef = useRef<HTMLDivElement>(null);
const hostRef = useRef<HTMLDivElement>(null);
const { enabled: autoFold, foldLines } = useCodeFoldConfig();
const restMap = rest as Record<string, unknown>;
const dataLanguage = readProp(restMap, "data-language");
@@ -176,7 +179,7 @@ export default function MdCodeBlock({ children, className, ...rest }: MdCodeBloc
}, [plainText, className, dataLanguage, serverHighlighted]);
const effectiveLines = lineCount > 0 ? lineCount : approxLines;
const canCollapse = foldReady && effectiveLines > COLLAPSE_LINE_THRESHOLD;
const canCollapse = autoFold && foldReady && effectiveLines > foldLines;
const collapsed = canCollapse && !expanded;
const onCopy = async () => {
@@ -195,11 +198,21 @@ export default function MdCodeBlock({ children, className, ...rest }: MdCodeBloc
const toggleFold = () => {
if (expanded) {
const el = rootRef.current;
// 仅当代码块顶部已滚出可视区(长代码展开后往下读)才回顶;
// 短代码全程在视口内时保持浏览位置不变
let shouldScrollBack = false;
if (el) {
const top = el.getBoundingClientRect().top;
const headerPad = 88; // 与 scroll-margin-top: 5.5rem 对齐
shouldScrollBack = top < headerPad;
}
setExpanded(false);
// 收起后滚到该代码块顶部(含工具栏),便于继续往下读
requestAnimationFrame(() => {
rootRef.current?.scrollIntoView({ block: "start", behavior: "smooth" });
});
if (shouldScrollBack) {
requestAnimationFrame(() => {
rootRef.current?.scrollIntoView({ block: "start", behavior: "smooth" });
});
}
} else {
setExpanded(true);
}
@@ -224,7 +237,7 @@ export default function MdCodeBlock({ children, className, ...rest }: MdCodeBloc
<div
ref={hostRef}
className={`md-code-body${collapsed ? " md-code-collapsed" : ""}`}
style={collapsed ? { maxHeight: COLLAPSED_MAX_HEIGHT } : undefined}
style={collapsed ? { maxHeight: collapsedMaxHeight(foldLines) } : undefined}
>
{clientHtml ? (
<div

View File

@@ -226,6 +226,13 @@ export interface Post {
poll?: PollState | null;
bounty?: BountyState | null;
lottery?: LotteryState | null;
/** 软删专用页标记 */
tombstone?: boolean;
delete_type?: string;
delete_reason?: string;
deleted_by?: number;
staff_deleted?: boolean;
deleted_at?: string;
}
export interface QuestionState {
@@ -306,6 +313,8 @@ export interface Comment {
status: string;
created_at: string;
user: User;
/** 软删占位 */
deleted?: boolean;
}
// 评论树节点:主评论为根,replies 为其全部子回复(时间正序,全量 SSR 直出)
@@ -373,7 +382,7 @@ export interface NotificationItem {
id: number;
user_id: number;
actor_id: number;
type: "comment" | "reply" | "like" | "approved" | "rejected" | "mention" | "pending_review";
type: "comment" | "reply" | "like" | "approved" | "rejected" | "mention" | "pending_review" | "deleted";
post_id: number;
comment_id: number;
room_id?: number;
@@ -539,6 +548,10 @@ export interface PublicSettings {
site_description: string;
allow_register: boolean;
post_cooldown_hours: number;
/** 超过 N 行的代码块是否默认折叠;缺省 true */
code_block_auto_fold: boolean;
/** 折叠阈值行数(超过则折叠;0=无预览);缺省 5 */
code_block_fold_lines: number;
}
const DEFAULT_PUBLIC_SETTINGS: PublicSettings = {
@@ -548,6 +561,8 @@ const DEFAULT_PUBLIC_SETTINGS: PublicSettings = {
site_description: "姜十三论坛 - 技术分享与讨论社区",
allow_register: true,
post_cooldown_hours: 24,
code_block_auto_fold: true,
code_block_fold_lines: 5,
};
function normalizePublicSettings(data: Partial<PublicSettings> | null | undefined): PublicSettings {
@@ -564,6 +579,13 @@ function normalizePublicSettings(data: Partial<PublicSettings> | null | undefine
typeof data?.post_cooldown_hours === "number" && data.post_cooldown_hours >= 0
? data.post_cooldown_hours
: DEFAULT_PUBLIC_SETTINGS.post_cooldown_hours,
code_block_auto_fold: data?.code_block_auto_fold !== false,
code_block_fold_lines:
typeof data?.code_block_fold_lines === "number" &&
data.code_block_fold_lines >= 0 &&
data.code_block_fold_lines <= 100
? Math.round(data.code_block_fold_lines)
: DEFAULT_PUBLIC_SETTINGS.code_block_fold_lines,
};
}
@@ -1464,6 +1486,8 @@ export type UpdateSiteSettingsBody = {
site_description?: string;
allow_register?: boolean;
post_cooldown_hours?: number;
code_block_auto_fold?: boolean;
code_block_fold_lines?: number;
};
// 更新站点设置(字段可选);accent 传空串恢复默认主题色

View File

@@ -45,6 +45,8 @@ export interface RtSettingsData {
site_description?: string;
allow_register?: boolean;
post_cooldown_hours?: number;
code_block_auto_fold?: boolean;
code_block_fold_lines?: number;
}
// 群聊新消息:data 为落库的 ChatMessage(含 sender)