Skip to content

Commit 197d910

Browse files
author
ZouYingjun
committed
实现文档大纲跳转:Markdown 标题树 + Cmd/Ctrl+Shift+O 快速跳转
1 parent 733b438 commit 197d910

10 files changed

Lines changed: 343 additions & 0 deletions

File tree

‎docs/design-outline.md‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# 文档大纲(TOC)跳转 · 技术设计
2+
3+
> 状态:✅ 已实现(2025-08-08)
4+
> 日期:2025-08-08
5+
> 关联:`docs/research-text-editor-needs.md`(需求 #2:大纲 / TOC 跳转,iA Writer 用户因缺它打 1★)
6+
> 目标:长文(Markdown)里按标题层级快速跳转。
7+
8+
---
9+
10+
## 一、方案:按需唤出的「大纲」面板(overlay)
11+
12+
延续 Jotpad「按需、不常驻」哲学(同 QuickOpen / CrossSearch),而非侧边常驻面板:
13+
14+
- **快捷键** `Cmd/Ctrl+Shift+O`(业界 "Go to Symbol in File" 惯例)+ 「编辑」菜单「文档大纲…」。
15+
- overlay 列出当前 tab 的标题树:层级缩进(`#`=顶层,`##` 缩进…),`↑/↓` 移动、`Enter` 跳转、输入即过滤。
16+
- 跳转 = 选中标题行 + 滚动到视口。
17+
18+
> 不做常驻侧栏:小窗口的记事本,常驻大纲挤占编辑区;Bear 用户"别臃肿"警告适用。
19+
20+
## 二、解析器 `src/lib/outline.ts`
21+
22+
- **ATX 标题**:`^(#{1,6})\s+(.*)$`(每个逻辑行一次匹配)。
23+
- **跳过代码围栏**:行首 ``` / ~~~ 开启的 fence 内不解析(防把代码里的 `#` 当标题)。
24+
- 跳过空标题文本(`# ` 后为空)。
25+
- 返回 `{ level, text, from, line }[]`:`from` 为标题行起始偏移(跳转选区用)、`line` 为 1-based 行号(展示)。
26+
- 非 Markdown / 无标题 → 空数组 → 空态提示("无标题——用 # 开始一行试试")。
27+
28+
```ts
29+
export interface OutlineItem { level: number; text: string; from: number; line: number; }
30+
export function parseOutline(text: string): OutlineItem[];
31+
```
32+
33+
## 三、组件 `src/components/Outline.tsx`
34+
35+
镜像 QuickOpen 交互范式:
36+
37+
- 打开时解析 active tab `content`(内存,纯同步,无需防抖)。
38+
- 输入框过滤:复用 `fuzzyFilter`(按标题文本)。
39+
- 列表行:缩进 `(level-1)*14px` + `H{level}` 小徽标 + 标题文本。
40+
- `Enter` → 关闭 → `view.dispatch({selection: {anchor: from}, scrollIntoView: true})` → 聚焦。
41+
- tab 切换时若面板开着 → 重新解析(依赖 activeTabId)。
42+
43+
## 四、接入(同 CrossSearch 模式)
44+
45+
- store:`outlineOpen` / `setOutlineOpen`
46+
- shortcuts:`outline` = `Cmd/Ctrl+Shift+O`
47+
- 菜单:「编辑」goto 之后加「文档大纲…」
48+
- i18n:`outline.*` 中英;App.tsx 渲染;CSS 复用 quick-open + 少量缩进/徽标样式
49+
50+
## 五、测试
51+
52+
- 单测(`outline.test.ts`):ATX 各级、fence 内忽略、空文本忽略、偏移/行号正确、空文档。
53+
- 手动:`#`~`######` 展示与缩进、过滤、跳转滚动、无标题空态。
54+
- 回归:全量 vitest + tsc。
55+
56+
## 六、成本
57+
58+
~半天:解析器 + 测试 1 小时、组件 + 接入 2 小时、联调 1 小时。零后端改动、零依赖。

‎src/App.tsx‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import { PageSetup } from "@/components/PageSetup";
2121
import { DiffDialog } from "@/components/DiffDialog";
2222
import { QuickOpen } from "@/components/QuickOpen";
2323
import { CrossSearch } from "@/components/CrossSearch";
24+
import { Outline } from "@/components/Outline";
2425
import { About, ConfirmDialog, GotoDialog, ReloadDialog, SessionNameDialog } from "@/components/Dialogs";
2526
import { HistoryPanel } from "@/components/HistoryPanel";
2627
import { ToastHost } from "@/components/ToastHost";
@@ -172,6 +173,8 @@ export function App() {
172173
s.voiceOpen ||
173174
s.voiceSetupOpen ||
174175
s.quickOpenOpen ||
176+
s.crossSearchOpen ||
177+
s.outlineOpen ||
175178
s.findOpen ||
176179
s.gotoOpen ||
177180
s.settingsOpen ||
@@ -191,6 +194,12 @@ export function App() {
191194
} else if (s.quickOpenOpen) {
192195
s.setQuickOpenOpen(false);
193196
getEditorView()?.focus();
197+
} else if (s.crossSearchOpen) {
198+
s.setCrossSearchOpen(false);
199+
getEditorView()?.focus();
200+
} else if (s.outlineOpen) {
201+
s.setOutlineOpen(false);
202+
getEditorView()?.focus();
194203
} else if (s.findOpen) {
195204
s.setFindOpen(false);
196205
s.setReplaceOpen(false);
@@ -342,6 +351,7 @@ export function App() {
342351
<ContextMenu />
343352
<QuickOpen />
344353
<CrossSearch />
354+
<Outline />
345355
<ConfirmDialog />
346356
<SessionNameDialog />
347357
<ReloadDialog />

‎src/components/Outline.tsx‎

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
2+
import { useStore } from "@/store/useStore";
3+
import { useT } from "@/lib/i18n";
4+
import { getEditorView } from "@/lib/editorRef";
5+
import { fuzzyFilter } from "@/lib/fuzzy";
6+
import { parseOutline } from "@/lib/outline";
7+
8+
export function Outline() {
9+
const open = useStore((s) => s.outlineOpen);
10+
const setOpen = useStore((s) => s.setOutlineOpen);
11+
const activeTabId = useStore((s) => s.activeTabId);
12+
const content = useStore((s) => s.tabs.find((t) => t.id === s.activeTabId)?.content);
13+
const t = useT();
14+
15+
const [query, setQuery] = useState("");
16+
const [index, setIndex] = useState(0);
17+
const inputRef = useRef<HTMLInputElement>(null);
18+
const listRef = useRef<HTMLDivElement>(null);
19+
20+
// 打开时重置;tab 切换时保持打开并重置过滤(内容变化由 content 依赖驱动重解析)
21+
useEffect(() => {
22+
if (!open) return;
23+
setQuery("");
24+
setIndex(0);
25+
requestAnimationFrame(() => inputRef.current?.focus());
26+
}, [open, activeTabId]);
27+
28+
const items = useMemo(() => parseOutline(content ?? ""), [content]);
29+
30+
const filtered = useMemo(
31+
() => (query.trim() ? fuzzyFilter(items, query.trim(), (it) => it.text) : items),
32+
[items, query],
33+
);
34+
35+
useEffect(() => {
36+
setIndex(0);
37+
}, [query]);
38+
39+
useEffect(() => {
40+
const el = listRef.current?.querySelector<HTMLElement>(`[data-oi="${index}"]`);
41+
el?.scrollIntoView({ block: "nearest" });
42+
}, [index, filtered.length]);
43+
44+
if (!open) return null;
45+
46+
const close = () => {
47+
setOpen(false);
48+
getEditorView()?.focus();
49+
};
50+
51+
const jump = (from: number) => {
52+
setOpen(false);
53+
requestAnimationFrame(() => {
54+
const v = getEditorView();
55+
if (v) {
56+
const pos = Math.min(from, v.state.doc.length);
57+
v.dispatch({ selection: { anchor: pos }, scrollIntoView: true });
58+
v.focus();
59+
}
60+
});
61+
};
62+
63+
const onKeyDown = (e: KeyboardEvent) => {
64+
if (e.key === "Escape") {
65+
e.preventDefault();
66+
close();
67+
return;
68+
}
69+
if (e.key === "ArrowDown") {
70+
e.preventDefault();
71+
if (!filtered.length) return;
72+
setIndex((i) => (i + 1) % filtered.length);
73+
return;
74+
}
75+
if (e.key === "ArrowUp") {
76+
e.preventDefault();
77+
if (!filtered.length) return;
78+
setIndex((i) => (i - 1 + filtered.length) % filtered.length);
79+
return;
80+
}
81+
if (e.key === "Enter") {
82+
e.preventDefault();
83+
const it = filtered[index];
84+
if (it) jump(it.from);
85+
}
86+
};
87+
88+
return (
89+
<div
90+
className="overlay quick-open-overlay outline-overlay"
91+
onMouseDown={(e) => e.target === e.currentTarget && close()}
92+
>
93+
<div className="quick-open outline-panel" role="dialog" aria-label={t("outline.title")}>
94+
<input
95+
ref={inputRef}
96+
className="quick-open-input"
97+
value={query}
98+
onChange={(e) => setQuery(e.target.value)}
99+
placeholder={t("outline.placeholder")}
100+
onKeyDown={onKeyDown}
101+
spellCheck={false}
102+
aria-autocomplete="list"
103+
aria-controls="outline-list"
104+
/>
105+
<div className="quick-open-list" id="outline-list" ref={listRef} role="listbox">
106+
{filtered.length === 0 ? (
107+
<div className="quick-open-empty muted">
108+
{items.length === 0 ? t("outline.noHeadings") : t("quickOpen.empty")}
109+
</div>
110+
) : (
111+
filtered.map((it, i) => (
112+
<div
113+
key={`${it.line}-${it.from}`}
114+
data-oi={i}
115+
role="option"
116+
aria-selected={i === index}
117+
className={"quick-open-row outline-row" + (i === index ? " active" : "")}
118+
style={{ paddingLeft: 10 + (it.level - 1) * 14 }}
119+
onMouseEnter={() => setIndex(i)}
120+
onClick={() => jump(it.from)}
121+
>
122+
<span className="outline-badge">H{it.level}</span>
123+
<span className="quick-open-label">{it.text}</span>
124+
<span className="quick-open-detail muted">L{it.line}</span>
125+
</div>
126+
))
127+
)}
128+
</div>
129+
</div>
130+
</div>
131+
);
132+
}

‎src/lib/i18n.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ const zhCN: Dict = {
5656
"edit.findPrev": "查找上一个",
5757
"edit.replace": "替换…",
5858
"edit.crossSearch": "在文件中查找…",
59+
"edit.outline": "文档大纲…",
5960
"edit.goto": "转到…",
6061
"edit.selectAll": "全选",
6162
"edit.timeDate": "时间/日期",
@@ -165,6 +166,11 @@ const zhCN: Dict = {
165166
"crossSearch.wholeWord": "整词",
166167
"crossSearch.results": "{n} 个结果 · {m} 个文件",
167168

169+
// Outline
170+
"outline.title": "文档大纲",
171+
"outline.placeholder": "筛选标题…",
172+
"outline.noHeadings": "无标题——用 # 开始一行试试",
173+
168174
// Goto
169175
"goto.title": "转到行",
170176
"goto.line": "行号",
@@ -349,6 +355,7 @@ const en: Dict = {
349355
"edit.findPrev": "Find Previous",
350356
"edit.replace": "Replace…",
351357
"edit.crossSearch": "Find in Files…",
358+
"edit.outline": "Document Outline…",
352359
"edit.goto": "Go To…",
353360
"edit.selectAll": "Select All",
354361
"edit.timeDate": "Time/Date",
@@ -452,6 +459,11 @@ const en: Dict = {
452459
"crossSearch.wholeWord": "Whole word",
453460
"crossSearch.results": "{n} results · {m} files",
454461

462+
// Outline
463+
"outline.title": "Document Outline",
464+
"outline.placeholder": "Filter headings…",
465+
"outline.noHeadings": "No headings — start a line with # to add one",
466+
455467
"goto.title": "Go to Line",
456468
"goto.line": "Line number",
457469

‎src/lib/menuActions.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,7 @@ export function getMenuModel(): MenuModel {
193193
{ id: "findPrev", label: t("edit.findPrev"), ...sc("findPrev") },
194194
{ id: "replace", label: t("edit.replace"), ...sc("replace") },
195195
{ id: "crossSearch", label: t("edit.crossSearch"), ...sc("crossSearch") },
196+
{ id: "outline", label: t("edit.outline"), ...sc("outline") },
196197
{ id: "goto", label: t("edit.goto"), ...sc("goto") },
197198
{ id: "voice", label: t("edit.voice"), ...sc("voice") },
198199
{ sep: true },
@@ -401,6 +402,9 @@ export function runMenuAction(id: string): void {
401402
case "crossSearch":
402403
s.setCrossSearchOpen(true);
403404
break;
405+
case "outline":
406+
s.setOutlineOpen(true);
407+
break;
404408
case "goto":
405409
s.setGotoOpen(true);
406410
break;

‎src/lib/outline.test.ts‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import { describe, expect, it } from "vitest";
2+
import { parseOutline } from "@/lib/outline";
3+
4+
describe("parseOutline", () => {
5+
it("解析各级 ATX 标题,偏移与行号正确", () => {
6+
const text = "# Title\nintro\n## Sec A\nbody\n### Sub\n## Sec B";
7+
const items = parseOutline(text);
8+
expect(items).toHaveLength(4);
9+
expect(items[0]).toMatchObject({ level: 1, text: "Title", from: 0, line: 1 });
10+
// offsets: "# Title\n"=8 → intro(8)+6=14 → "## Sec A" at 14
11+
expect(items[1]).toMatchObject({ level: 2, text: "Sec A", from: 14, line: 3 });
12+
expect(items[2]).toMatchObject({ level: 3, text: "Sub", line: 5 });
13+
expect(items[3]).toMatchObject({ level: 2, text: "Sec B", line: 6 });
14+
});
15+
16+
it("代码围栏内的 # 不算标题", () => {
17+
const text = "# Real\n```md\n# Fake\n## AlsoFake\n```\n## After";
18+
const items = parseOutline(text);
19+
expect(items.map((i) => i.text)).toEqual(["Real", "After"]);
20+
});
21+
22+
it("~~~ 围栏与配对开关", () => {
23+
const text = "# A\n~~~\n# B\n~~~\n# C";
24+
expect(parseOutline(text).map((i) => i.text)).toEqual(["A", "C"]);
25+
});
26+
27+
it("无空格的 # 、超过 6 级、空标题文本均忽略", () => {
28+
const text = "#nospace\n####### seven\n#\n# \n# OK";
29+
const items = parseOutline(text);
30+
expect(items.map((i) => i.text)).toEqual(["OK"]);
31+
});
32+
33+
it("尾部闭合 # 序列被去除", () => {
34+
expect(parseOutline("# Head ##")[0]!.text).toBe("Head");
35+
});
36+
37+
it("空文本与纯文本无标题", () => {
38+
expect(parseOutline("")).toEqual([]);
39+
expect(parseOutline("plain\ntext only")).toEqual([]);
40+
});
41+
42+
it("CRLF 不影响(内容已归一化 LF,防御性验证)", () => {
43+
expect(parseOutline("# A\r\n## B").map((i) => i.level)).toEqual([1, 2]);
44+
});
45+
});

‎src/lib/outline.ts‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
// 文档大纲(TOC):从 Markdown 文本解析标题树。设计详见 docs/design-outline.md。
2+
3+
export interface OutlineItem {
4+
/** 标题层级 1-6(# 数)。 */
5+
level: number;
6+
/** 标题文本(已 trim,去掉尾部 # 序列)。 */
7+
text: string;
8+
/** 标题行起始在全文中的偏移(跳转选区用)。 */
9+
from: number;
10+
/** 1-based 行号(展示用)。 */
11+
line: number;
12+
}
13+
14+
const ATX_RE = /^(#{1,6})[ \t]+(\S.*?)(?:[ \t]+#+)?[ \t]*$/;
15+
const FENCE_RE = /^[ \t]{0,3}(```|~~~)/;
16+
17+
/** 解析 ATX 标题;代码围栏(``` / ~~~)内部不解析。 */
18+
export function parseOutline(text: string): OutlineItem[] {
19+
const out: OutlineItem[] = [];
20+
let inFence = false;
21+
let fenceMark = "";
22+
let offset = 0; // 当前行起始偏移
23+
let line = 0;
24+
for (const raw of text.split("\n")) {
25+
line++;
26+
const body = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
27+
const fence = FENCE_RE.exec(body);
28+
if (fence) {
29+
if (!inFence) {
30+
inFence = true;
31+
fenceMark = fence[1]!;
32+
} else if (fence[1] === fenceMark) {
33+
inFence = false;
34+
fenceMark = "";
35+
}
36+
offset += raw.length + 1;
37+
continue;
38+
}
39+
if (!inFence) {
40+
const m = ATX_RE.exec(body);
41+
if (m) {
42+
out.push({
43+
level: m[1]!.length,
44+
text: m[2]!.trim(),
45+
from: offset,
46+
line,
47+
});
48+
}
49+
}
50+
offset += raw.length + 1;
51+
}
52+
return out;
53+
}

0 commit comments

Comments
 (0)