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

@@ -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