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): 收紧搜索口径 —— mermaid 与 conceal 标记一律不命中

Zhang Yunjine076e0b3792e
diff --git a/apps/desktop/src/renderer/__tests__/markdownTableSearchHighlight.test.ts b/apps/desktop/src/renderer/__tests__/markdownTableSearchHighlight.test.ts
index 9bef2f1b40..19718e7d4f 100644
--- a/apps/desktop/src/renderer/__tests__/markdownTableSearchHighlight.test.ts
+++ b/apps/desktop/src/renderer/__tests__/markdownTableSearchHighlight.test.ts
@@ -17,7 +17,10 @@ import {
collectMarkdownTableHiddenRanges,
markdownTableDecorationField,
} from '@/components/markdown/markdownTableLivePreview';
-import { searchHighlightField } from '@/components/markdown/PlaintextEditor';
+import {
+ collectDocSearchHiddenRanges,
+ searchHighlightField,
+} from '@/components/markdown/PlaintextEditor';
import {
docSearchRangesField,
filterVisibleDocSearchRanges,
@@ -34,6 +37,27 @@ const DOC = [
'| beta | blocked |',
].join('\n');
+const DOC_WITH_MERMAID = [
+ 'intro alpha',
+ '',
+ '```mermaid',
+ 'graph TD',
+ ' A[alpha] --> B[结束]',
+ '```',
+ '',
+ 'tail alpha',
+].join('\n');
+
+const DOC_WITH_MARKUP = [
+ '# alpha heading',
+ '',
+ '- alpha bullet',
+ '',
+ 'plain **alpha** text with `alpha` code',
+ '',
+ '> alpha quote',
+].join('\n');
+
/** TableWidget 是模块私有的,测试按结构取它暴露的两个成员。 */
interface TableWidgetLike extends WidgetType {
highlights: DocSearchRange[];
@@ -53,11 +77,11 @@ function findMatches(query: string, doc: CodeMirrorText): DocSearchRange[] {
return out;
}
-/** 复刻 PlaintextEditor.findAll 的可见性口径(表格结构字符 + 图片 alt)。 */
+/** 复刻 PlaintextEditor.findAll 的可见性口径(直接调用生产实现)。 */
function visibleMatches(query: string, doc: CodeMirrorText = docOf()): DocSearchRange[] {
return filterVisibleDocSearchRanges(
findMatches(query, doc),
- collectMarkdownTableHiddenRanges(doc),
+ collectDocSearchHiddenRanges(doc, true),
);
}
@@ -133,6 +157,45 @@ describe('markdown table hidden ranges (search visibility)', () => {
});
});
+describe('search only matches text the user can see', () => {
+ it('drops mermaid block matches because the figure cannot be highlighted', () => {
+ const doc = docOf(DOC_WITH_MERMAID);
+ // 源码里有 3 处 alpha(正文 2 + 图内 label 1)
+ expect(findMatches('alpha', doc)).toHaveLength(3);
+ // 去掉 mermaid 块后只剩正文两处,且它们都真的画得出高亮
+ const visible = visibleMatches('alpha', doc);
+ expect(visible).toHaveLength(2);
+ for (const range of visible) {
+ expect(doc.lineAt(range.from).text).toContain('alpha');
+ }
+ // 图内其它 label 文字也不再命中
+ expect(visibleMatches('开始', doc)).toEqual([]);
+ });
+
+ it('drops concealed markdown markers but keeps the text around them', () => {
+ const doc = docOf(DOC_WITH_MARKUP);
+ // `#`、`> `、`**`、反引号都被 live preview 换成 widget / 空白
+ expect(visibleMatches('#', doc)).toEqual([]);
+ expect(visibleMatches('> ', doc)).toEqual([]);
+ expect(visibleMatches('**', doc)).toEqual([]);
+ expect(visibleMatches('`', doc)).toEqual([]);
+ // 正文文字全保留(标题 / 列表 / 强体 / 行内代码 / 引用)
+ expect(visibleMatches('alpha', doc)).toHaveLength(5);
+ });
+
+ it('leaves non-mermaid fenced code alone', () => {
+ const doc = docOf(['```js', 'const alpha = 1;', '```', '', 'alpha tail'].join('\n'));
+ // 围栏内是普通文本(不做 conceal),两处都该命中
+ expect(visibleMatches('alpha', doc)).toHaveLength(2);
+ });
+
+ it('never filters anything for non-markdown documents', () => {
+ const doc = docOf(['# alpha', '- alpha', '```mermaid', 'graph TD', '```'].join('\n'));
+ expect(collectDocSearchHiddenRanges(doc, false)).toEqual([]);
+ expect(visibleMatches('alpha', doc)).toHaveLength(2);
+ });
+});
+
describe('markdown table widget search highlight', () => {
it('highlights matches inside table cells, not just in the body text', () => {
const view = mountView();
diff --git a/apps/desktop/src/renderer/components/markdown/PlaintextEditor.tsx b/apps/desktop/src/renderer/components/markdown/PlaintextEditor.tsx
index 13a4fb6490..0279416cd2 100644
--- a/apps/desktop/src/renderer/components/markdown/PlaintextEditor.tsx
+++ b/apps/desktop/src/renderer/components/markdown/PlaintextEditor.tsx
@@ -72,6 +72,7 @@ import { getCodeMirrorLanguage } from './codemirrorLanguages';
import {
clamp,
findMarkdownTableAtLine,
+ findMarkdownTableAtLineInDoc,
markdownTableDecorationField,
collectMarkdownTableHiddenRanges,
runHistoryCommandPreservingScroll,
@@ -81,6 +82,7 @@ import {
import {
markdownMermaidDecorationField,
mermaidLocaleFacet,
+ findMermaidBlocks,
} from './markdownMermaidLivePreview';
import {
imageBaseDirFacet,
@@ -242,16 +244,20 @@ export const searchHighlightField = StateField.define<DecorationSet>({
/**
* 收集"用户看不见"的 doc 区间,搜索命中落在其中就丢弃,保证搜索条的命中
- * 计数与真正画出来的高亮一一对应。markdown 之外的文件没有任何 replace
- * widget,直接返回空数组。
+ * 计数与真正画出来的高亮**一一对应** —— 用户要的是"搜到的就一定能看见",
+ * 宁可少报一个不可见的命中,也不要报一个点不到的高亮。
+ * markdown 之外的文件没有任何 replace widget / conceal,直接返回空数组。
*
* - 表格:结构字符(分隔行、竖线、padding)由表格模块给出;单元格文字由表格
* widget 负责高亮,所以**不**在这里排除整个表格块。
* - 图片:预览只渲染 <img>,alt 文本不可见,整块排除。
- * - mermaid:图上的 label 是可见的(用户搜的往往就是它),保留命中,只是
- * 暂时无法在 SVG 里定位高亮 —— 详见 markdownMermaidLivePreview 顶部说明。
+ * - mermaid:整块是异步渲染出的 SVG,源码区间到图上文字没有可计算的映射
+ * (详见 markdownMermaidLivePreview 顶部说明),无法在图内定位高亮 → 整块排除。
+ * - conceal 标记(标题 `#`、列表符号、`**`、反引号、引用 `>`、分割线、围栏
+ * 标记行):live preview 把它们替换成 widget / 空白,命中的字符不存在于
+ * 屏幕上 → 按静态口径排除。
*/
-function collectHiddenSearchRanges(
+export function collectDocSearchHiddenRanges(
doc: EditorView['state']['doc'],
isMarkdown: boolean,
): DocSearchHiddenRange[] {
@@ -259,9 +265,56 @@ function collectHiddenSearchRanges(
return [
...collectMarkdownTableHiddenRanges(doc),
...findImageTargets(doc).map((target) => ({ from: target.from, to: target.to })),
+ ...findMermaidBlocks(doc).map((block) => ({ from: block.from, to: block.to })),
+ ...collectMarkdownConcealedRanges(doc),
];
}
+/**
+ * 被 live preview conceal 掉的字符区间(静态口径:编辑器未聚焦、无 reveal)。
+ *
+ * 搜索期间焦点在搜索框输入,`markdownLivePreviewPlugin` 的 reveal 判定
+ * (`getLineRevealRanges`,依赖 `view.hasFocus` + 光标)此时恒为空,所以
+ * "无 reveal 时被 conceal 的字符"就是搜索时真实的隐藏集。直接复用
+ * `addMarkdownConcealDecorations` 的判定逻辑(mini builder 只收区间),
+ * 不另写一套正则 —— 两处判定漂移比多一点计算危险得多。
+ */
+function collectMarkdownConcealedRanges(
+ doc: EditorView['state']['doc'],
+): DocSearchHiddenRange[] {
+ const out: DocSearchHiddenRange[] = [];
+ const fenceLines = computeFenceLineRoles(doc);
+ // 表格块的行是连续的,记住上一次的行号上界,避免每行都重扫表格。
+ let tableLinesThrough = 0;
+ for (let number = 1; number <= doc.lines; number++) {
+ const line = doc.line(number);
+ const role = fenceLines.get(number);
+ // 围栏块内部的行保持原文显示,不做 conceal。
+ if (role === 'body') continue;
+ // 围栏开栏 / 闭栏行整行被空 marker 覆盖。
+ if (role === 'first' || role === 'last') {
+ if (line.text.length > 0) out.push({ from: line.from, to: line.to });
+ continue;
+ }
+ // 表格行的 conceal 由表格 widget 负责(单元格文字是可见的,必须留下命中),
+ // 判定与 markdownLivePreviewPlugin 完全一致。行形状近似的写法会漏判
+ // 真正的表格块,也会误判带竖线的普通行。
+ if (number <= tableLinesThrough) continue;
+ const tableBlock = findMarkdownTableAtLineInDoc(doc, number);
+ if (tableBlock) {
+ tableLinesThrough = doc.lineAt(tableBlock.to).number;
+ continue;
+ }
+ addMarkdownConcealDecorations(collectOnlyBuilder(out), line.from, line.text, []);
+ }
+ return out;
+}
+
+/** 只实现 `add` 的 RangeSetBuilder 替身:把 conceal 区间收进数组。 */
+function collectOnlyBuilder(out: DocSearchHiddenRange[]): RangeSetBuilder<Decoration> {
+ return { add: (from: number, to: number) => void out.push({ from, to }) } as unknown as RangeSetBuilder<Decoration>;
+}
+
class MarkdownMarkerWidget extends WidgetType {
constructor(
private readonly kind: 'empty' | 'bullet' | 'ordered' | 'checked' | 'unchecked',
@@ -1115,11 +1168,11 @@ export const PlaintextEditor = forwardRef<PlaintextEditorHandle, PlaintextEditor
while (!cursor.next().done) {
scanned.push({ from: cursor.value.from, to: cursor.value.to, active: false });
}
- // 丢掉用户看不见的区间(表格结构字符 / 图片 alt):命中计数必须等于
- // 真正画得出来的高亮,否则搜索条会报一个点不到的高亮。
+ // 丢掉用户看不见的区间(表格结构字符 / 图片 alt / mermaid 块 /
+ // conceal 标记):命中计数必须等于真正画得出来的高亮。
const out = filterVisibleDocSearchRanges(
scanned,
- collectHiddenSearchRanges(doc, isMarkdownRef.current),
+ collectDocSearchHiddenRanges(doc, isMarkdownRef.current),
);
matchesRef.current = out;
// Render all matches; no active until setActive() picks one.
diff --git a/apps/desktop/src/renderer/components/markdown/docSearchRanges.ts b/apps/desktop/src/renderer/components/markdown/docSearchRanges.ts
index b7ffe94c34..53ca5d8d8d 100644
--- a/apps/desktop/src/renderer/components/markdown/docSearchRanges.ts
+++ b/apps/desktop/src/renderer/components/markdown/docSearchRanges.ts
@@ -8,8 +8,12 @@
* "1/2",但表格里的那一处永远没有高亮。命中位置因此必须能被 widget 自己
* 读到,由 widget 在自己的 DOM 里补画高亮(见 markdownTableLivePreview)。
*
- * 可见性口径由各 live-preview 模块自己提供区间(`collectMarkdownTableHiddenRanges`
- * 等),本文件只提供命中集合的存取与纯过滤,不反向依赖任何渲染模块,避免循环。
+ * 可见性口径由 PlaintextEditor.collectDocSearchHiddenRanges 集中提供(表格
+ * 结构字符、图片、mermaid、conceal 标记),本文件只提供命中集合的存取与纯
+ * 过滤,不反向依赖任何渲染模块,避免循环。
+ *
+ * 口径的底线:命中的东西用户一定看得见。报一个看不见也点不到的命中,比
+ * 少报一个不可见字符更糟。
*/
import { StateEffect, StateField } from '@codemirror/state';
diff --git a/apps/desktop/src/renderer/components/markdown/markdownMermaidLivePreview.ts b/apps/desktop/src/renderer/components/markdown/markdownMermaidLivePreview.ts
index 0d79660655..68c120f33b 100644
--- a/apps/desktop/src/renderer/components/markdown/markdownMermaidLivePreview.ts
+++ b/apps/desktop/src/renderer/components/markdown/markdownMermaidLivePreview.ts
@@ -2,12 +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。
+ * 搜索命中的口径:mermaid 块**整块不命中**。它是
+ * `Decoration.replace({block: true, widget})` + 异步渲染的 SVG,源码区间到图
+ * 上文字没有可计算的映射(label 由解析 + 布局产出,源码里的 `A[开始]` 只留
+ * 「开始」,方括号是语法;渲染还会 `replaceChildren` 整块替换、SVG 还有主题
+ * 缓存),所以无法在图内定位高亮。既然画不出高亮,就不计入命中 —— 口径统一
+ * 在 PlaintextEditor.collectDocSearchHiddenRanges(与图片 alt、conceal 标记同批)。
+ * 需要看图里的文字请用 hover 工具条的 Edit Source(源码视图)。
*
* Implementation shape mirrors `markdownTableLivePreview`:
* - StateField scans the whole doc on docChange (not on selection/viewport
diff --git a/apps/desktop/src/renderer/components/markdown/markdownTableLivePreview.ts b/apps/desktop/src/renderer/components/markdown/markdownTableLivePreview.ts
index 8604b0e80a..d7330d7044 100644
--- a/apps/desktop/src/renderer/components/markdown/markdownTableLivePreview.ts
+++ b/apps/desktop/src/renderer/components/markdown/markdownTableLivePreview.ts
@@ -119,7 +119,9 @@ export function findMarkdownTableAtLine(
return findMarkdownTableAtLineInDoc(view.state.doc, lineNumber);
}
-function findMarkdownTableAtLineInDoc(
+// 导出给搜索可见性口径用:PlaintextEditor 收集 conceal 区间时要与实际渲染
+// 用完全相同的表格判定(而不是 `isMarkdownTableSourceLine` 那种行形状近似)。
+export function findMarkdownTableAtLineInDoc(
doc: EditorView['state']['doc'],
lineNumber: number,
): MarkdownTableBlock | null {