Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(markdown): 高亮文件内搜索在 markdown 表格中的命中

Zhang Yunjin215029fe6417
diff --git a/apps/desktop/src/renderer/__tests__/markdownTableSearchHighlight.test.ts b/apps/desktop/src/renderer/__tests__/markdownTableSearchHighlight.test.ts
new file mode 100644
index 0000000000..9bef2f1b40
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/markdownTableSearchHighlight.test.ts
@@ -0,0 +1,220 @@
+// @vitest-environment jsdom
+/**
+ * markdown 表格内的文件内搜索高亮。
+ *
+ * 背景:markdown 表格在 live preview 里是 `Decoration.replace({block: true,
+ * widget})` —— widget 覆盖区间内的文本不再由 CodeMirror 渲染,落在同一区间
+ * 的 `cm-doc-search-match` mark 装饰无处可显示。这些用例锁住"命中计数 =
+ * 可见高亮"这条口径:单元格文字由 widget 补高亮,表格结构字符与图片 alt
+ * 从命中里剔除。
+ */
+import { describe, expect, it } from 'vitest';
+import { EditorState, type Text as CodeMirrorText } from '@codemirror/state';
+import { EditorView, type DecorationSet, type WidgetType } from '@codemirror/view';
+import { SearchCursor } from '@codemirror/search';
+
+import {
+ collectMarkdownTableHiddenRanges,
+ markdownTableDecorationField,
+} from '@/components/markdown/markdownTableLivePreview';
+import { searchHighlightField } from '@/components/markdown/PlaintextEditor';
+import {
+ docSearchRangesField,
+ filterVisibleDocSearchRanges,
+ setDocSearchRangesEffect,
+ type DocSearchRange,
+} from '@/components/markdown/docSearchRanges';
+
+const DOC = [
+ 'alpha outside table',
+ '',
+ '| Name | Status |',
+ '| --- | --- |',
+ '| alpha | ready |',
+ '| beta | blocked |',
+].join('\n');
+
+/** TableWidget 是模块私有的,测试按结构取它暴露的两个成员。 */
+interface TableWidgetLike extends WidgetType {
+ highlights: DocSearchRange[];
+ updateDOM: (dom: HTMLElement, view: EditorView, from: WidgetType) => boolean;
+}
+
+function docOf(doc = DOC): CodeMirrorText {
+ return EditorState.create({ doc }).doc;
+}
+
+function findMatches(query: string, doc: CodeMirrorText): DocSearchRange[] {
+ const cursor = new SearchCursor(doc, query, 0, doc.length, (s) => s.toLowerCase());
+ const out: DocSearchRange[] = [];
+ while (!cursor.next().done) {
+ out.push({ from: cursor.value.from, to: cursor.value.to, active: false });
+ }
+ return out;
+}
+
+/** 复刻 PlaintextEditor.findAll 的可见性口径(表格结构字符 + 图片 alt)。 */
+function visibleMatches(query: string, doc: CodeMirrorText = docOf()): DocSearchRange[] {
+ return filterVisibleDocSearchRanges(
+ findMatches(query, doc),
+ collectMarkdownTableHiddenRanges(doc),
+ );
+}
+
+function mountView(doc = DOC): EditorView {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const view = new EditorView({
+ state: EditorState.create({
+ doc,
+ extensions: [docSearchRangesField, markdownTableDecorationField, searchHighlightField],
+ }),
+ parent: host,
+ });
+ view.requestMeasure();
+ return view;
+}
+
+function readTableWidget(view: EditorView): { dom: HTMLElement; widget: TableWidgetLike } {
+ const decorations = view.state.field(markdownTableDecorationField) as DecorationSet;
+ let widget: TableWidgetLike | undefined;
+ decorations.between(0, view.state.doc.length, (_from, _to, decoration) => {
+ if (!widget) widget = decoration.spec.widget as TableWidgetLike;
+ });
+ if (!widget) throw new Error('expected exactly one markdown table widget');
+ const dom = view.dom.querySelector('.cm-md-table-widget') as HTMLElement | null;
+ if (!dom) throw new Error('expected .cm-md-table-widget in editor DOM');
+ return { dom, widget };
+}
+
+function dispatchRanges(view: EditorView, ranges: DocSearchRange[]): void {
+ view.dispatch({ effects: setDocSearchRangesEffect.of(ranges) });
+ view.requestMeasure();
+}
+
+describe('markdown table hidden ranges (search visibility)', () => {
+ it('excludes structural characters but keeps every cell text', () => {
+ const doc = docOf();
+ const hidden = collectMarkdownTableHiddenRanges(doc);
+ const tableFrom = doc.line(3).from;
+ const tableTo = doc.line(6).to;
+ const isHidden = (from: number, to: number) =>
+ hidden.some((span) => from < span.to && to > span.from);
+
+ // 表格行起点是 "|",属于结构字符
+ expect(isHidden(tableFrom, tableFrom + 1)).toBe(true);
+ // 表头 / 单元格文字都算可见内容(在表格块内定位,不取文档开头的同名词)
+ const tableStart = DOC.indexOf('| Name');
+ for (const needle of ['Name', 'Status', 'alpha', 'ready', 'beta', 'blocked']) {
+ const at = DOC.indexOf(needle, tableStart);
+ expect(isHidden(at, at + needle.length)).toBe(false);
+ }
+ // 分隔行整行没有可见文字
+ const separator = doc.line(4);
+ expect(isHidden(separator.from, separator.to)).toBe(true);
+ // hidden 区间不溢出表格块
+ for (const span of hidden) {
+ expect(span.from).toBeGreaterThanOrEqual(tableFrom);
+ expect(span.to).toBeLessThanOrEqual(tableTo);
+ }
+ });
+
+ it('drops separator matches from the hit count but keeps cell matches', () => {
+ // "---" 只出现在分隔行,用户看不见 → 不计入命中
+ expect(visibleMatches('---')).toEqual([]);
+ // 表外的 alpha + 表格单元格里的 alpha 都保留
+ expect(visibleMatches('alpha')).toHaveLength(2);
+ });
+
+ it('keeps every match when the document has no markdown table', () => {
+ const doc = docOf('plain text without tables');
+ expect(collectMarkdownTableHiddenRanges(doc)).toEqual([]);
+ expect(visibleMatches('plain', doc)).toHaveLength(1);
+ });
+});
+
+describe('markdown table widget search highlight', () => {
+ it('highlights matches inside table cells, not just in the body text', () => {
+ const view = mountView();
+ const ranges = visibleMatches('alpha');
+ expect(ranges).toHaveLength(2);
+ dispatchRanges(view, ranges);
+
+ const bodyMarks = view.dom.querySelectorAll('.cm-content > .cm-line .cm-doc-search-match');
+ const widgetMarks = view.dom.querySelectorAll('.cm-md-table-widget .cm-doc-search-match');
+ expect(bodyMarks).toHaveLength(1);
+ expect(widgetMarks).toHaveLength(1);
+ expect(widgetMarks[0].textContent).toBe('alpha');
+ expect(widgetMarks[0].closest('td, th')?.getAttribute('data-source-text')).toBe('alpha');
+ view.destroy();
+ });
+
+ it('keeps the active match distinguishable inside cells', () => {
+ const view = mountView();
+ const ranges = visibleMatches('alpha');
+ dispatchRanges(
+ view,
+ ranges.map((range, index) => ({ ...range, active: index === 1 })),
+ );
+
+ const active = view.dom.querySelectorAll('.cm-md-table-widget .cm-doc-search-active');
+ expect(active).toHaveLength(1);
+ expect(active[0].textContent).toBe('alpha');
+ view.destroy();
+ });
+
+ it('paints highlighted cell text that still serializes back to the source', () => {
+ const view = mountView();
+ dispatchRanges(view, visibleMatches('alpha'));
+
+ const cell = view.dom.querySelector('.cm-md-table-widget td') as HTMLTableCellElement;
+ expect(cell.textContent).toBe(cell.dataset.sourceText);
+ view.destroy();
+ });
+
+ it('hands the widget the matches inside its own source range', () => {
+ const view = mountView();
+ const ranges = visibleMatches('alpha');
+ dispatchRanges(view, ranges);
+
+ const { widget } = readTableWidget(view);
+ const doc = docOf();
+ expect(widget.highlights).toHaveLength(1);
+ expect(doc.sliceString(widget.highlights[0].from, widget.highlights[0].to)).toBe('alpha');
+ expect(doc.lineAt(widget.highlights[0].from).number).toBe(5);
+ view.destroy();
+ });
+
+ it('repaints in place when the query changes, without dropping cell DOM', () => {
+ const view = mountView();
+ dispatchRanges(view, visibleMatches('alpha'));
+ const cell = view.dom.querySelector('.cm-md-table-widget td') as HTMLTableCellElement;
+
+ // 同一个 table widget 只换了 hits:CodeMirror 走 updateDOM 原地更新,
+ // 整表重建会打断正在编辑的单元格。
+ dispatchRanges(view, visibleMatches('ready'));
+
+ expect(view.dom.querySelector('.cm-md-table-widget td')).toBe(cell);
+ expect(view.dom.querySelector('.cm-md-table-widget .cm-doc-search-match')?.textContent).toBe(
+ 'ready',
+ );
+ expect(cell.textContent).toBe('alpha');
+ view.destroy();
+ });
+
+ it('leaves the cell being edited untouched so typing is not interrupted', () => {
+ const view = mountView();
+ dispatchRanges(view, visibleMatches('alpha'));
+ const cell = view.dom.querySelector('.cm-md-table-widget td') as HTMLTableCellElement;
+
+ // jsdom 不给 contentEditable 元素派发焦点,补一个 tabIndex 模拟“正在编辑”
+ cell.tabIndex = -1;
+ cell.focus();
+ cell.textContent = 'alpha edited';
+ dispatchRanges(view, visibleMatches('ready'));
+
+ expect(cell.textContent).toBe('alpha edited');
+ cell.blur();
+ view.destroy();
+ });
+});
diff --git a/apps/desktop/src/renderer/components/markdown/PlaintextEditor.tsx b/apps/desktop/src/renderer/components/markdown/PlaintextEditor.tsx
index b719cf825a..13a4fb6490 100644
--- a/apps/desktop/src/renderer/components/markdown/PlaintextEditor.tsx
+++ b/apps/desktop/src/renderer/components/markdown/PlaintextEditor.tsx
@@ -41,7 +41,6 @@ import {
EditorSelection,
Prec,
RangeSetBuilder,
- StateEffect,
StateField,
} from '@codemirror/state';
import {
@@ -74,6 +73,7 @@ import {
clamp,
findMarkdownTableAtLine,
markdownTableDecorationField,
+ collectMarkdownTableHiddenRanges,
runHistoryCommandPreservingScroll,
tableMenuLabelsFacet,
type TableMenuLabels,
@@ -86,7 +86,15 @@ import {
imageBaseDirFacet,
imageLocaleFacet,
markdownImageDecorationField,
+ findImageTargets,
} from './markdownImageLivePreview';
+import {
+ docSearchRangesField,
+ filterVisibleDocSearchRanges,
+ setDocSearchRangesEffect,
+ type DocSearchHiddenRange,
+ type DocSearchRange,
+} from './docSearchRanges';
import { computeFenceLineRoles, type FenceLineRole } from './markdownFenceLines';
import { getPlaintextEditorChrome } from './plaintextEditorChrome';
import { useIsDarkMode } from './useIsDarkMode';
@@ -204,38 +212,56 @@ function detectLargeDoc(doc: string): { largeDoc: boolean; longLine: boolean } {
return { largeDoc, longLine };
}
-// ── CodeMirror search highlight: StateField + StateEffect ──────────────────
-// The effect carries the active set of `{from, to, active}` ranges; the field
-// rebuilds a DecorationSet from it. Decoupling search state from the editor
-// state means clearing is just dispatching an empty effect — no extra refs.
-type SearchRange = { from: number; to: number; active: boolean };
-
-const setSearchRangesEffect = StateEffect.define<SearchRange[]>();
-
+// ── CodeMirror search highlight: mark decoration over the shared ranges ────
+// 命中集合本身挂在 docSearchRangesField 上(见 docSearchRanges.ts):markdown
+// 表格是 block replace widget,需要读到同一份命中才能在自己的 DOM 里补高亮。
+// 这里只负责把命中翻译成 CodeMirror 的 mark decoration。
const matchDeco = Decoration.mark({ class: 'cm-doc-search-match' });
const activeDeco = Decoration.mark({ class: 'cm-doc-search-match cm-doc-search-active' });
-const searchHighlightField = StateField.define<DecorationSet>({
+// 导出供测试直接复用:测试要验证"正文 mark 高亮与表格 widget 高亮同时存在",
+// 若测试自己重写一份 decoration 就会与生产实现漂移。
+export const searchHighlightField = StateField.define<DecorationSet>({
create: () => Decoration.none,
update(value, tr) {
let next = value.map(tr.changes);
for (const e of tr.effects) {
- if (e.is(setSearchRangesEffect)) {
- const ranges = e.value;
- if (ranges.length === 0) {
- next = Decoration.none;
- } else {
- next = Decoration.set(
- ranges.map((r) => (r.active ? activeDeco : matchDeco).range(r.from, r.to)),
- );
- }
- }
+ if (!e.is(setDocSearchRangesEffect)) continue;
+ // 直接用 effect 载荷(而不是回读 field):纯 code / 纯文本文档不注册
+ // docSearchRangesField,那里也要能正常高亮。
+ const ranges = e.value;
+ next =
+ ranges.length === 0
+ ? Decoration.none
+ : Decoration.set(ranges.map((r) => (r.active ? activeDeco : matchDeco).range(r.from, r.to)));
}
return next;
},
provide: (f) => EditorView.decorations.from(f),
});
+/**
+ * 收集"用户看不见"的 doc 区间,搜索命中落在其中就丢弃,保证搜索条的命中
+ * 计数与真正画出来的高亮一一对应。markdown 之外的文件没有任何 replace
+ * widget,直接返回空数组。
+ *
+ * - 表格:结构字符(分隔行、竖线、padding)由表格模块给出;单元格文字由表格
+ * widget 负责高亮,所以**不**在这里排除整个表格块。
+ * - 图片:预览只渲染 <img>,alt 文本不可见,整块排除。
+ * - mermaid:图上的 label 是可见的(用户搜的往往就是它),保留命中,只是
+ * 暂时无法在 SVG 里定位高亮 —— 详见 markdownMermaidLivePreview 顶部说明。
+ */
+function collectHiddenSearchRanges(
+ doc: EditorView['state']['doc'],
+ isMarkdown: boolean,
+): DocSearchHiddenRange[] {
+ if (!isMarkdown) return [];
+ return [
+ ...collectMarkdownTableHiddenRanges(doc),
+ ...findImageTargets(doc).map((target) => ({ from: target.from, to: target.to })),
+ ];
+}
+
class MarkdownMarkerWidget extends WidgetType {
constructor(
private readonly kind: 'empty' | 'bullet' | 'ordered' | 'checked' | 'unchecked',
@@ -987,6 +1013,10 @@ export const PlaintextEditor = forwardRef<PlaintextEditorHandle, PlaintextEditor
const currentLocale = i18nInst.language;
const editorChrome = getPlaintextEditorChrome(language);
const isMarkdown = editorChrome === 'markdown';
+ // search handle 建成 mount-only 的 useMemo(identity 稳定),isMarkdown 变化后
+ // 读不到新值 —— 用 ref 保鲜,与 onChange/onScroll 同一套路。
+ const isMarkdownRef = useRef(isMarkdown);
+ isMarkdownRef.current = isMarkdown;
// UI chrome 分三种:
// - code: monospace + 行号;parser 存在时才语法高亮。
// - markdown: sans 排版 + markdown parser/highlight + 无行号。
@@ -1028,7 +1058,7 @@ export const PlaintextEditor = forwardRef<PlaintextEditorHandle, PlaintextEditor
// Cached search positions — written by findAll(), read by setActive().
// Use a ref so search ops don't trigger re-renders.
- const matchesRef = useRef<{ from: number; to: number }[]>([]);
+ const matchesRef = useRef<DocSearchRange[]>([]);
// readOnly 用 Compartment 包起来,让 preview↔edit 可以 reconfigure 而不
// remount。否则父组件靠 key 切换 readOnly 会让 CodeMirror 整个销毁重建,
@@ -1073,7 +1103,7 @@ export const PlaintextEditor = forwardRef<PlaintextEditorHandle, PlaintextEditor
if (!view) return 0;
if (!query) {
matchesRef.current = [];
- view.dispatch({ effects: setSearchRangesEffect.of([]) });
+ view.dispatch({ effects: setDocSearchRangesEffect.of([]) });
return 0;
}
const doc = view.state.doc;
@@ -1081,17 +1111,19 @@ export const PlaintextEditor = forwardRef<PlaintextEditorHandle, PlaintextEditor
// the search term and the doc, so lowercase both sides → ascii-CI.
// Unicode folding could be added later if needed.
const cursor = new SearchCursor(doc, query, 0, doc.length, (s) => s.toLowerCase());
- const out: { from: number; to: number }[] = [];
+ const scanned: DocSearchRange[] = [];
while (!cursor.next().done) {
- out.push({ from: cursor.value.from, to: cursor.value.to });
+ scanned.push({ from: cursor.value.from, to: cursor.value.to, active: false });
}
+ // 丢掉用户看不见的区间(表格结构字符 / 图片 alt):命中计数必须等于
+ // 真正画得出来的高亮,否则搜索条会报一个点不到的高亮。
+ const out = filterVisibleDocSearchRanges(
+ scanned,
+ collectHiddenSearchRanges(doc, isMarkdownRef.current),
+ );
matchesRef.current = out;
// Render all matches; no active until setActive() picks one.
- view.dispatch({
- effects: setSearchRangesEffect.of(
- out.map((r) => ({ from: r.from, to: r.to, active: false })),
- ),
- });
+ view.dispatch({ effects: setDocSearchRangesEffect.of(out) });
return out.length;
},
setActive: (index: number): void => {
@@ -1105,7 +1137,7 @@ export const PlaintextEditor = forwardRef<PlaintextEditorHandle, PlaintextEditor
view.dispatch({
effects: [
EditorView.scrollIntoView(matches[index].from, { y: 'center' }),
- setSearchRangesEffect.of(
+ setDocSearchRangesEffect.of(
matches.map((r, i) => ({ from: r.from, to: r.to, active: i === index })),
),
],
@@ -1115,7 +1147,7 @@ export const PlaintextEditor = forwardRef<PlaintextEditorHandle, PlaintextEditor
matchesRef.current = [];
const view = cmViewRef.current;
if (!view) return;
- view.dispatch({ effects: setSearchRangesEffect.of([]) });
+ view.dispatch({ effects: setDocSearchRangesEffect.of([]) });
},
}),
[],
@@ -1198,6 +1230,9 @@ export const PlaintextEditor = forwardRef<PlaintextEditorHandle, PlaintextEditor
...highlightExtensions,
...(initialConfig.isMarkdown
? [
+ // 命中集合先于表格 decoration 挂上:markdownTableDecorationField
+ // 的 update 要在同一次事务里读到它(搜索变化 → 重建 widget)。
+ docSearchRangesField,
markdownTableDecorationField,
tableLabelsCompartment.of(tableMenuLabelsFacet.of(tableMenuLabelsRef.current)),
markdownFormattingKeymap,
diff --git a/apps/desktop/src/renderer/components/markdown/docSearchRanges.ts b/apps/desktop/src/renderer/components/markdown/docSearchRanges.ts
new file mode 100644
index 0000000000..b7ffe94c34
--- /dev/null
+++ b/apps/desktop/src/renderer/components/markdown/docSearchRanges.ts
@@ -0,0 +1,73 @@
+/**
+ * docSearchRanges — 文档内搜索命中的共享 state 契约。
+ *
+ * 为什么需要一个挂在 state 上的共享契约:markdown live preview 把表格 /
+ * mermaid / 图片整块换成 `Decoration.replace({block: true, widget})`。widget
+ * 覆盖区间内的文档文本不再由 CodeMirror 的行视图渲染,落在同一区间上的
+ * `Decoration.mark`(`cm-doc-search-match`)无处可显示 —— 搜索条会报
+ * "1/2",但表格里的那一处永远没有高亮。命中位置因此必须能被 widget 自己
+ * 读到,由 widget 在自己的 DOM 里补画高亮(见 markdownTableLivePreview)。
+ *
+ * 可见性口径由各 live-preview 模块自己提供区间(`collectMarkdownTableHiddenRanges`
+ * 等),本文件只提供命中集合的存取与纯过滤,不反向依赖任何渲染模块,避免循环。
+ */
+import { StateEffect, StateField } from '@codemirror/state';
+
+export interface DocSearchRange {
+ from: number;
+ to: number;
+ active: boolean;
+}
+
+/** 一次搜索运行的完整命中集合(含 active 标记)。派发空数组 = 清除高亮。 */
+export const setDocSearchRangesEffect = StateEffect.define<DocSearchRange[]>();
+
+/**
+ * 命中集合的单一真相源。
+ *
+ * 挂在 state 上而不是组件 ref 上,是为了让 live preview 的 decoration field
+ * 能在同一次事务里读到它(doc 变化时映射位置、搜索变化时重画 widget 高亮)。
+ * 纯 code / 纯文本文件可以只注册 mark decoration 而不注册本 field,读取方
+ * 一律用 `field(…, false)` 容忍缺席。
+ */
+export const docSearchRangesField = StateField.define<DocSearchRange[]>({
+ create: () => [],
+ update(value, tr) {
+ for (const e of tr.effects) {
+ if (e.is(setDocSearchRangesEffect)) return e.value;
+ }
+ if (!tr.docChanged || value.length === 0) return value;
+ // 编辑模式下用户敲字会挪动命中位置:跟随 changes 映射,避免高亮落在
+ // 错位的字符上(两端分别向外/向内贴边,保持区间语义)。
+ return value.map((range) => ({
+ ...range,
+ from: tr.changes.mapPos(range.from, 1),
+ to: tr.changes.mapPos(range.to, -1),
+ }));
+ },
+});
+
+export interface DocSearchHiddenRange {
+ from: number;
+ to: number;
+}
+
+/** 丢掉任何与不可见区间相交的命中,使"命中计数"与"可见高亮"始终一致。 */
+export function filterVisibleDocSearchRanges(
+ ranges: DocSearchRange[],
+ hidden: DocSearchHiddenRange[],
+): DocSearchRange[] {
+ if (hidden.length === 0) return ranges;
+ return ranges.filter(
+ (range) => !hidden.some((span) => range.from < span.to && range.to > span.from),
+ );
+}
+
+/** 取出落在 [from, to) 内的命中(表格 widget 用它在自己 DOM 里补画高亮)。 */
+export function selectDocSearchRangesWithin(
+ ranges: DocSearchRange[],
+ from: number,
+ to: number,
+): DocSearchRange[] {
+ return ranges.filter((range) => range.from < to && range.to > from);
+}
diff --git a/apps/desktop/src/renderer/components/markdown/markdownMermaidLivePreview.ts b/apps/desktop/src/renderer/components/markdown/markdownMermaidLivePreview.ts
index 0ddc0e2cf2..0d79660655 100644
--- a/apps/desktop/src/renderer/components/markdown/markdownMermaidLivePreview.ts
+++ b/apps/desktop/src/renderer/components/markdown/markdownMermaidLivePreview.ts
@@ -2,6 +2,13 @@
* markdownMermaidLivePreview — render ```mermaid fenced blocks as SVG inside
* the doc-mode CodeMirror editor (workdir-browse → FileBodyView).
*
+ * 搜索高亮的已知限制:mermaid 块同样是 `Decoration.replace({block: true,
+ * widget})`,源码区间上的 `cm-doc-search-match` mark 装饰不会渲染。图上的
+ * label 文字是用户看得见的、也确实是他们会搜的内容,所以**命中保留**(计数
+ * 与跳转仍然正确),只是暂时无法像 markdown 表格那样在 DOM 里补高亮 —— label
+ * 到 SVG 文本节点的可靠映射尚不存在。与表格相反,图片语法整块排除(alt 在
+ * 预览里不渲染)。口径集中在 PlaintextEditor.collectHiddenSearchRanges。
+ *
* Implementation shape mirrors `markdownTableLivePreview`:
* - StateField scans the whole doc on docChange (not on selection/viewport
* changes — those triggered an unbounded height-map growth where every
diff --git a/apps/desktop/src/renderer/components/markdown/markdownTableLivePreview.ts b/apps/desktop/src/renderer/components/markdown/markdownTableLivePreview.ts
index e485128279..8604b0e80a 100644
--- a/apps/desktop/src/renderer/components/markdown/markdownTableLivePreview.ts
+++ b/apps/desktop/src/renderer/components/markdown/markdownTableLivePreview.ts
@@ -2,6 +2,12 @@ import { Facet, RangeSetBuilder, StateField, type ChangeSpec } from '@codemirror
import { redo, undo } from '@codemirror/commands';
import { Decoration, EditorView, WidgetType } from '@codemirror/view';
+import {
+ docSearchRangesField,
+ selectDocSearchRangesWithin,
+ type DocSearchRange,
+} from './docSearchRanges';
+
export type TableMenuLabels = Record<TableAction, string>;
const defaultTableMenuLabels: TableMenuLabels = {
@@ -55,22 +61,38 @@ type TableMenuEntry =
export const markdownTableDecorationField = StateField.define({
create(state) {
- return buildMarkdownTableDecorations(state.doc);
+ return buildMarkdownTableDecorations(state.doc, readDocSearchRanges(state));
},
update(value, transaction) {
- if (!transaction.docChanged) return value;
- return buildMarkdownTableDecorations(transaction.state.doc);
+ // 搜索命中集合变了也要重建:widget 靠 eq 相同被复用,再由 updateDOM 就地
+ // 补画高亮(见 MarkdownTableWidget.updateDOM 的说明)。引用比较即可 ——
+ // setDocSearchRangesEffect 每次派发新数组,doc 变化时 field 自身也会返回新数组。
+ const nextRanges = readDocSearchRanges(transaction.state);
+ const prevRanges = readDocSearchRanges(transaction.startState);
+ if (!transaction.docChanged && nextRanges === prevRanges) return value;
+ return buildMarkdownTableDecorations(transaction.state.doc, nextRanges);
},
provide: (field) => EditorView.decorations.from(field),
});
-function buildMarkdownTableDecorations(doc: EditorView['state']['doc']) {
+/** 读取共享命中集合;未注册 docSearchRangesField 的宿主返回空数组。 */
+function readDocSearchRanges(state: EditorView['state']): DocSearchRange[] {
+ return state.field(docSearchRangesField, false) ?? [];
+}
+
+function buildMarkdownTableDecorations(
+ doc: EditorView['state']['doc'],
+ searchRanges: DocSearchRange[],
+) {
const builder = new RangeSetBuilder<Decoration>();
let line = doc.line(1);
while (line.number <= doc.lines) {
const block = findMarkdownTableAtLineInDoc(doc, line.number);
if (block) {
- const widget = new MarkdownTableWidget(block);
+ const widget = new MarkdownTableWidget(
+ block,
+ selectDocSearchRangesWithin(searchRanges, block.from, block.to),
+ );
builder.add(
block.from,
block.to,
@@ -146,6 +168,63 @@ function isMarkdownTableSeparator(text: unknown): boolean {
return cells.every((cell) => /^:?-{3,}:?$/.test(cell));
}
+/**
+ * 表格里"看得见但不是单元格文字"的区间:分隔行 `| --- | --- |`、单元格之间
+ * 的竖线、行首行尾空白。搜索命中落在这些区间时既没有可见文字、也不该计入
+ * 命中数(否则搜索条会报一个用户永远看不到的高亮)。
+ *
+ * markdown 表格是 block replace widget,这些区间由本函数按 doc 坐标提供,
+ * 调用方(PlaintextEditor.findAll)据此过滤命中集合。
+ */
+export function collectMarkdownTableHiddenRanges(
+ doc: EditorView['state']['doc'],
+): Array<{ from: number; to: number }> {
+ const out: Array<{ from: number; to: number }> = [];
+ let line = doc.line(1);
+ while (line.number <= doc.lines) {
+ const block = findMarkdownTableAtLineInDoc(doc, line.number);
+ if (block) {
+ out.push(...complementOfCellTextRanges(doc, block));
+ const blockEndLine = doc.lineAt(block.to).number;
+ if (blockEndLine >= doc.lines) break;
+ line = doc.line(blockEndLine + 1);
+ continue;
+ }
+ if (line.to >= doc.length) break;
+ line = doc.line(line.number + 1);
+ }
+ return out;
+}
+
+function complementOfCellTextRanges(
+ doc: EditorView['state']['doc'],
+ block: MarkdownTableBlock,
+): Array<{ from: number; to: number }> {
+ const visible: Array<{ from: number; to: number }> = [];
+ const firstLine = doc.lineAt(block.from).number;
+ const lastLine = doc.lineAt(block.to).number;
+ for (let number = firstLine; number <= lastLine; number++) {
+ const line = doc.line(number);
+ // 分隔行渲染成表格边框,`---` 不对应任何可见文字 → 整行算隐藏。
+ if (isMarkdownTableSeparator(line.text)) continue;
+ for (const cell of splitMarkdownTableRowWithRanges(line.text, line.from)) {
+ if (cell.contentTo > cell.contentFrom) {
+ visible.push({ from: cell.contentFrom, to: cell.contentTo });
+ }
+ }
+ }
+ visible.sort((a, b) => a.from - b.from);
+
+ const out: Array<{ from: number; to: number }> = [];
+ let cursor = block.from;
+ for (const span of visible) {
+ if (span.from > cursor) out.push({ from: cursor, to: span.from });
+ cursor = Math.max(cursor, span.to);
+ }
+ if (cursor < block.to) out.push({ from: cursor, to: block.to });
+ return out;
+}
+
export function parseMarkdownTable(text: string): MarkdownTableModel | null {
const lines = splitLinesWithOffsets(text);
if (lines.length < 2 || !isMarkdownTableSeparator(lines[1].text)) return null;
@@ -369,10 +448,35 @@ function escapeTableCell(text: string): string {
}
class MarkdownTableWidget extends WidgetType {
- constructor(private readonly block: MarkdownTableBlock) {
+ /**
+ * @param highlights 落在这张表格源码区间内的搜索命中(doc 坐标)。表格是
+ * block replace widget,落在同一区间的 `cm-doc-search-match` mark 装饰
+ * 不会被 CodeMirror 渲染,所以高亮由 widget 自己在单元格 DOM 里画。
+ */
+ constructor(
+ private readonly block: MarkdownTableBlock,
+ private readonly highlights: DocSearchRange[] = [],
+ ) {
super();
}
+ /**
+ * CodeMirror 复用 widget 的 DOM 时(hits 变了但表格本身没变)走这里就地补
+ * 高亮,而不是整表重建 —— 重建会打断正在编辑的单元格(焦点丢失、未提交
+ * 的输入回滚)。返回 true 表示 DOM 已经自行更新到新状态;表格源码变了就
+ * 返回 false,交回 CodeMirror 整表重建(那时连单元格文本一起刷新)。
+ */
+ updateDOM(dom: HTMLElement, view: EditorView, from: WidgetType): boolean {
+ const previous = from instanceof MarkdownTableWidget ? from : null;
+ if (!previous) return false;
+ if (previous.block.text !== this.block.text || previous.block.from !== this.block.from) {
+ return false;
+ }
+ if (sameSearchRanges(previous.highlights, this.highlights)) return true;
+ applyTableSearchHighlights(dom, this.block, this.highlights);
+ return true;
+ }
+
toDOM(view: EditorView): HTMLElement {
const wrapper = document.createElement('div');
wrapper.className = 'cm-md-table-widget';
@@ -427,7 +531,7 @@ class MarkdownTableWidget extends WidgetType {
thead.appendChild(headRow);
table.appendChild(thead);
this.block.model.header.forEach((cell, columnIndex) => {
- headRow.appendChild(this.createCell(view, 'th', 0, columnIndex, cell.text, wrapper));
+ headRow.appendChild(this.createCell(view, 'th', 0, columnIndex, cell, wrapper));
});
const tbody = document.createElement('tbody');
@@ -436,7 +540,7 @@ class MarkdownTableWidget extends WidgetType {
const tr = document.createElement('tr');
tbody.appendChild(tr);
row.forEach((cell, columnIndex) => {
- tr.appendChild(this.createCell(view, 'td', rowIndex + 1, columnIndex, cell.text, wrapper));
+ tr.appendChild(this.createCell(view, 'td', rowIndex + 1, columnIndex, cell, wrapper));
});
});
@@ -452,7 +556,14 @@ class MarkdownTableWidget extends WidgetType {
}
eq(other: MarkdownTableWidget): boolean {
- return this.block.text === other.block.text && this.block.from === other.block.from;
+ return (
+ this.block.text === other.block.text &&
+ this.block.from === other.block.from &&
+ // hits 参与比较是刻意的:eq 相等时 CodeMirror 直接复用旧 DOM 且**不会**调
+ // updateDOM,高亮会停在旧值上。让它不相等,CodeMirror 才会退到
+ // updateDOM 的原地更新路径(DOM 仍然复用,不打断单元格编辑)。
+ sameSearchRanges(this.highlights, other.highlights)
+ );
}
private createControls(view: EditorView, root: HTMLElement): HTMLElement {
@@ -522,7 +633,7 @@ class MarkdownTableWidget extends WidgetType {
tag: 'td' | 'th',
rowIndex: number,
columnIndex: number,
- text: string,
+ model: MarkdownTableCell,
root: HTMLElement,
): HTMLTableCellElement {
const cell = document.createElement(tag);
@@ -530,8 +641,10 @@ class MarkdownTableWidget extends WidgetType {
cell.spellcheck = false;
cell.dataset.row = String(rowIndex);
cell.dataset.column = String(columnIndex);
- cell.dataset.sourceText = text;
- renderInlineMarkdown(cell, text);
+ cell.dataset.sourceText = model.text;
+ const searchRanges = computeCellSearchRanges(model, this.highlights, this.block.from);
+ cell.dataset.searchHighlights = serializeSearchRanges(searchRanges);
+ renderInlineMarkdown(cell, model.text, [], searchRanges);
if (tag === 'th') {
const handle = document.createElement('span');
@@ -1083,7 +1196,13 @@ function rootOrSelf(cell: HTMLTableCellElement): Element {
function renderTableCells(root: Element, active: HTMLTableCellElement | null): void {
for (const cell of root.querySelectorAll<HTMLTableCellElement>('th, td')) {
if (cell === active) continue;
- renderInlineMarkdown(cell, cell.dataset.sourceText ?? '');
+ // 单元格离开编辑态后重绘,顺带把 dataset 里记着的搜索高亮恢复回来。
+ renderInlineMarkdown(
+ cell,
+ cell.dataset.sourceText ?? '',
+ [],
+ parseSearchRanges(cell.dataset.searchHighlights),
+ );
}
if (active) renderActiveCell(active);
}
@@ -1107,45 +1226,218 @@ function isComposingTableCell(cell: HTMLTableCellElement): boolean {
return cell.dataset.composing === 'true';
}
+/** 单元格渲染后的一个片段。renderedFrom/renderedTo 是它在"渲染文本"里的坐标。 */
+type RenderedCellSegment =
+ | { kind: 'text' | 'strong' | 'code'; text: string; renderedFrom: number; renderedTo: number }
+ | { kind: 'break'; renderedFrom: number; renderedTo: number };
+
+const SEARCH_HIGHLIGHT_CLASS = 'cm-doc-search-match';
+const SEARCH_ACTIVE_HIGHLIGHT_CLASS = 'cm-doc-search-match cm-doc-search-active';
+
function renderInlineMarkdown(
cell: HTMLTableCellElement,
source: string,
revealRanges: Array<{ from: number; to: number }> = [],
+ searchRanges: DocSearchRange[] = [],
): void {
const handle = cell.querySelector('.cm-md-table-resize-handle');
handle?.remove();
cell.textContent = '';
cell.dataset.revealRanges = serializeRevealRanges(revealRanges);
+ for (const segment of buildRenderedCellSegments(source, revealRanges)) {
+ appendRenderedCellSegment(cell, segment, searchRanges);
+ }
+ if (handle) cell.appendChild(handle);
+}
+
+/**
+ * 把 cell 源码切成渲染片段(纯文本 / strong / code / 换行)。坐标推进规则
+ * 必须与 `sourceOffsetToRenderedOffset` 一致(标记本身不占渲染长度,`<br>`
+ * 占 1),否则高亮会错位。
+ */
+function buildRenderedCellSegments(
+ source: string,
+ revealRanges: Array<{ from: number; to: number }>,
+): RenderedCellSegment[] {
+ const segments: RenderedCellSegment[] = [];
let pos = 0;
+ let rendered = 0;
const pattern = /(\*\*([^*\n]+)\*\*|`([^`\n]+)`|<br\s*\/?>)/gi;
+
+ const pushText = (text: string): void => {
+ if (text.length === 0) return;
+ segments.push({ kind: 'text', text, renderedFrom: rendered, renderedTo: rendered + text.length });
+ rendered += text.length;
+ };
+
for (const match of source.matchAll(pattern)) {
const start = match.index ?? 0;
const end = start + match[0].length;
- if (start > pos) cell.appendChild(document.createTextNode(source.slice(pos, start)));
+ if (start > pos) pushText(source.slice(pos, start));
if (match[0].toLowerCase().startsWith('<br')) {
- cell.appendChild(document.createElement('br'));
+ segments.push({ kind: 'break', renderedFrom: rendered, renderedTo: rendered + 1 });
+ rendered += 1;
pos = end;
continue;
}
if (shouldRevealInlineMarkdown(start, end, revealRanges)) {
- cell.appendChild(document.createTextNode(match[0]));
+ pushText(match[0]);
pos = end;
continue;
}
if (match[2] != null) {
- const strong = document.createElement('strong');
- strong.textContent = match[2];
- cell.appendChild(strong);
+ segments.push({
+ kind: 'strong',
+ text: match[2],
+ renderedFrom: rendered,
+ renderedTo: rendered + match[2].length,
+ });
+ rendered += match[2].length;
} else if (match[3] != null) {
- const code = document.createElement('code');
- code.textContent = match[3];
- cell.appendChild(code);
+ segments.push({
+ kind: 'code',
+ text: match[3],
+ renderedFrom: rendered,
+ renderedTo: rendered + match[3].length,
+ });
+ rendered += match[3].length;
}
pos = end;
}
- if (pos < source.length) cell.appendChild(document.createTextNode(source.slice(pos)));
- if (handle) cell.appendChild(handle);
+ if (pos < source.length) pushText(source.slice(pos));
+ return segments;
+}
+
+/**
+ * 按渲染坐标把片段写进 cell,命中部分包一层 `.cm-doc-search-match`(active
+ * 命中再叠 `.cm-doc-search-active`)。class 与 CodeMirror 正文里的 mark
+ * decoration 完全一致,所以一套 CSS 同时管住正文与表格单元格。
+ */
+function appendRenderedCellSegment(
+ cell: HTMLTableCellElement,
+ segment: RenderedCellSegment,
+ searchRanges: DocSearchRange[],
+): void {
+ if (segment.kind === 'break') {
+ cell.appendChild(document.createElement('br'));
+ return;
+ }
+ const container =
+ segment.kind === 'strong'
+ ? document.createElement('strong')
+ : segment.kind === 'code'
+ ? document.createElement('code')
+ : null;
+
+ let cursor = segment.renderedFrom;
+ for (const range of sortedSearchRanges(searchRanges)) {
+ const from = Math.max(range.from, segment.renderedFrom);
+ const to = Math.min(range.to, segment.renderedTo);
+ if (to <= from) continue;
+ appendPlainText(container ?? cell, segment.text.slice(cursor - segment.renderedFrom, from - segment.renderedFrom));
+ const hit = document.createElement('span');
+ hit.className = range.active ? SEARCH_ACTIVE_HIGHLIGHT_CLASS : SEARCH_HIGHLIGHT_CLASS;
+ hit.textContent = segment.text.slice(from - segment.renderedFrom, to - segment.renderedFrom);
+ (container ?? cell).appendChild(hit);
+ cursor = to;
+ }
+ appendPlainText(
+ container ?? cell,
+ segment.text.slice(cursor - segment.renderedFrom),
+ );
+ if (container) cell.appendChild(container);
+}
+
+function appendPlainText(parent: Node, text: string): void {
+ if (text.length === 0) return;
+ parent.appendChild(document.createTextNode(text));
+}
+
+function sortedSearchRanges(ranges: DocSearchRange[]): DocSearchRange[] {
+ return [...ranges].sort((a, b) => a.from - b.from || a.to - b.to);
+}
+
+function sameSearchRanges(a: DocSearchRange[], b: DocSearchRange[]): boolean {
+ if (a.length !== b.length) return false;
+ return a.every(
+ (range, index) =>
+ range.from === b[index].from && range.to === b[index].to && range.active === b[index].active,
+ );
+}
+
+/**
+ * 落在某个单元格里的命中 → 渲染坐标下的高亮区间。
+ *
+ * `MarkdownTableCell.sourceFrom/sourceTo` 是**表格块内**的相对偏移(见
+ * commitTable 里 `block.from + sourceFrom` 的用法),要先加回 blockFrom 才是
+ * doc 坐标。单元格文本是 trim 过的,这段区间正好对应 trim 后的内容。
+ */
+function computeCellSearchRanges(
+ model: MarkdownTableCell,
+ highlights: DocSearchRange[],
+ blockFrom: number,
+): DocSearchRange[] {
+ if (model.sourceFrom == null || model.sourceTo == null || highlights.length === 0) return [];
+ const cellFrom = blockFrom + model.sourceFrom;
+ const cellTo = blockFrom + model.sourceTo;
+ const out: DocSearchRange[] = [];
+ for (const range of highlights) {
+ const from = Math.max(range.from, cellFrom);
+ const to = Math.min(range.to, cellTo);
+ if (to <= from) continue;
+ out.push({
+ from: sourceOffsetToRenderedOffset(model.text, from - cellFrom, []),
+ to: sourceOffsetToRenderedOffset(model.text, to - cellFrom, []),
+ active: range.active,
+ });
+ }
+ return out;
+}
+
+/** 就地刷新整张表格 widget 的高亮(搜索命中变化时走 MarkdownTableWidget.updateDOM)。 */
+function applyTableSearchHighlights(
+ root: HTMLElement,
+ block: MarkdownTableBlock,
+ highlights: DocSearchRange[],
+): void {
+ for (const cell of root.querySelectorAll<HTMLTableCellElement>('th, td')) {
+ const rowIndex = Number(cell.dataset.row);
+ const columnIndex = Number(cell.dataset.column);
+ if (!Number.isInteger(rowIndex) || !Number.isInteger(columnIndex)) continue;
+ const modelCell =
+ rowIndex === 0
+ ? block.model.header[columnIndex]
+ : block.model.rows[rowIndex - 1]?.[columnIndex];
+ if (!modelCell) continue;
+ // 正在编辑 / 输入法组合中的单元格不重绘:重绘会打断用户输入与光标。
+ // 高亮在 focusout 后由 renderTableCells 补回。
+ if (isComposingTableCell(cell) || document.activeElement === cell) continue;
+ const ranges = computeCellSearchRanges(modelCell, highlights, block.from);
+ cell.dataset.searchHighlights = serializeSearchRanges(ranges);
+ renderInlineMarkdown(cell, cell.dataset.sourceText ?? '', [], ranges);
+ }
+}
+
+/** 高亮区间存 dataset:与 reveal-ranges 同风格,cell 重绘时不必回查 model。 */
+function serializeSearchRanges(ranges: DocSearchRange[]): string {
+ return ranges
+ .map((range) => `${range.from}:${range.to}${range.active ? ':a' : ''}`)
+ .join(',');
+}
+
+function parseSearchRanges(value: string | undefined): DocSearchRange[] {
+ if (!value) return [];
+ return value
+ .split(',')
+ .map((chunk) => {
+ const [from, to, flag] = chunk.split(':');
+ const fromNum = Number(from);
+ const toNum = Number(to);
+ if (!Number.isFinite(fromNum) || !Number.isFinite(toNum)) return null;
+ return { from: fromNum, to: toNum, active: flag === 'a' };
+ })
+ .filter((range): range is DocSearchRange => range != null);
}
function shouldRevealInlineMarkdown(