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): 处置 PR #5241 的 4 条 review(2×P1、2×P2)

Zhang Yunjine408c0a82899
diff --git a/apps/desktop/src/renderer/__tests__/markdownTableSearchHighlight.test.ts b/apps/desktop/src/renderer/__tests__/markdownTableSearchHighlight.test.ts
index be255d2d60..f268877b15 100644
--- a/apps/desktop/src/renderer/__tests__/markdownTableSearchHighlight.test.ts
+++ b/apps/desktop/src/renderer/__tests__/markdownTableSearchHighlight.test.ts
@@ -14,6 +14,7 @@ import { EditorView, type DecorationSet, type WidgetType } from '@codemirror/vie
import { SearchCursor } from '@codemirror/search';
import {
+ collectMarkdownTableBlocks,
collectMarkdownTableHiddenRanges,
markdownTableDecorationField,
} from '@/components/markdown/markdownTableLivePreview';
@@ -214,6 +215,25 @@ describe('search only matches text the user can see', () => {
expect(visibleMatches('alpha', doc)).toHaveLength(2);
});
+ it('drops cells beyond the rendered column count', () => {
+ // 表头 2 列 → 渲染模型截掉数据行的第 3 列,那一列没有单元格可高亮
+ const doc = docOf(['| h1 | h2 |', '| --- | --- |', '| a | b | c |', '| d | e | f |'].join('\n'));
+ expect(visibleMatches('c', doc)).toEqual([]);
+ expect(visibleMatches('f', doc)).toEqual([]);
+ // 前两列照常命中
+ expect(visibleMatches('a', doc)).toHaveLength(1);
+ expect(visibleMatches('b', doc)).toHaveLength(1);
+ });
+
+ it('stays linear on documents full of pipes that are not tables', () => {
+ // 含竖线但没有分隔行 → 不是表格;两路判定都不得把它当表格反复扫描
+ const lines: string[] = [];
+ for (let index = 0; index < 200; index++) lines.push(`| pipe line ${index} | tail`);
+ const doc = docOf(lines.join('\n'));
+ expect(collectMarkdownTableBlocks(doc)).toEqual([]);
+ expect(visibleMatches('pipe', doc)).toHaveLength(200);
+ });
+
it('never filters anything for non-markdown documents', () => {
const doc = docOf(['# alpha', '- alpha', '```mermaid', 'graph TD', '```'].join('\n'));
expect(collectDocSearchHiddenRanges(doc, false)).toEqual([]);
@@ -299,9 +319,14 @@ describe('markdown table widget search highlight', () => {
cell.tabIndex = -1;
cell.focus();
cell.textContent = 'alpha edited';
- dispatchRanges(view, visibleMatches('ready'));
+ // 新查询仍命中这个 cell,但起点不同 → dataset 要跟着变
+ dispatchRanges(view, visibleMatches('lpha'));
+ view.requestMeasure();
expect(cell.textContent).toBe('alpha edited');
+ // dataset 必须已经存了新查询的高亮:失焦重画才不会回到旧查询
+ // (project-search 跳转不聚焦搜索框,新命中会在 cell 仍聚焦时到达)
+ expect(cell.dataset.searchHighlights).toBe('1:5');
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 0279416cd2..a55d788f3e 100644
--- a/apps/desktop/src/renderer/components/markdown/PlaintextEditor.tsx
+++ b/apps/desktop/src/renderer/components/markdown/PlaintextEditor.tsx
@@ -72,11 +72,12 @@ import { getCodeMirrorLanguage } from './codemirrorLanguages';
import {
clamp,
findMarkdownTableAtLine,
- findMarkdownTableAtLineInDoc,
markdownTableDecorationField,
+ collectMarkdownTableBlocks,
collectMarkdownTableHiddenRanges,
runHistoryCommandPreservingScroll,
tableMenuLabelsFacet,
+ type MarkdownTableBlock,
type TableMenuLabels,
} from './markdownTableLivePreview';
import {
@@ -262,11 +263,13 @@ export function collectDocSearchHiddenRanges(
isMarkdown: boolean,
): DocSearchHiddenRange[] {
if (!isMarkdown) return [];
+ // 表格块只扫一次:表格结构字符与 conceal 行判定共用同一份结果。
+ const blocks = collectMarkdownTableBlocks(doc);
return [
- ...collectMarkdownTableHiddenRanges(doc),
+ ...collectMarkdownTableHiddenRanges(doc, blocks),
...findImageTargets(doc).map((target) => ({ from: target.from, to: target.to })),
...findMermaidBlocks(doc).map((block) => ({ from: block.from, to: block.to })),
- ...collectMarkdownConcealedRanges(doc),
+ ...collectMarkdownConcealedRanges(doc, blocks),
];
}
@@ -281,11 +284,17 @@ export function collectDocSearchHiddenRanges(
*/
function collectMarkdownConcealedRanges(
doc: EditorView['state']['doc'],
+ tableBlocks: MarkdownTableBlock[],
): DocSearchHiddenRange[] {
const out: DocSearchHiddenRange[] = [];
const fenceLines = computeFenceLineRoles(doc);
- // 表格块的行是连续的,记住上一次的行号上界,避免每行都重扫表格。
- let tableLinesThrough = 0;
+ // 表格块的行号区间是有序的,用游标线性推进 —— 不逐行重扫表格探测
+ // (那会让含竖线但不是表格的段落变成平方级,每次输入都跑一遍)。
+ const tableRanges = tableBlocks.map((block) => ({
+ fromLine: doc.lineAt(block.from).number,
+ toLine: doc.lineAt(block.to).number,
+ }));
+ let tableIndex = 0;
for (let number = 1; number <= doc.lines; number++) {
const line = doc.line(number);
const role = fenceLines.get(number);
@@ -297,12 +306,15 @@ function collectMarkdownConcealedRanges(
continue;
}
// 表格行的 conceal 由表格 widget 负责(单元格文字是可见的,必须留下命中),
- // 判定与 markdownLivePreviewPlugin 完全一致。行形状近似的写法会漏判
- // 真正的表格块,也会误判带竖线的普通行。
- if (number <= tableLinesThrough) continue;
- const tableBlock = findMarkdownTableAtLineInDoc(doc, number);
- if (tableBlock) {
- tableLinesThrough = doc.lineAt(tableBlock.to).number;
+ // 判定与 markdownLivePreviewPlugin 一致:用同一份表格块结果。
+ while (tableIndex < tableRanges.length && tableRanges[tableIndex].toLine < number) {
+ tableIndex++;
+ }
+ if (
+ tableIndex < tableRanges.length &&
+ number >= tableRanges[tableIndex].fromLine &&
+ number <= tableRanges[tableIndex].toLine
+ ) {
continue;
}
addMarkdownConcealDecorations(collectOnlyBuilder(out), line.from, line.text, []);
diff --git a/apps/desktop/src/renderer/components/markdown/docSearchRanges.ts b/apps/desktop/src/renderer/components/markdown/docSearchRanges.ts
index 53ca5d8d8d..c953d00115 100644
--- a/apps/desktop/src/renderer/components/markdown/docSearchRanges.ts
+++ b/apps/desktop/src/renderer/components/markdown/docSearchRanges.ts
@@ -56,15 +56,43 @@ export interface DocSearchHiddenRange {
to: number;
}
-/** 丢掉任何与不可见区间相交的命中,使"命中计数"与"可见高亮"始终一致。 */
+/**
+ * 丢掉任何与不可见区间相交的命中,使"命中计数"与"可见高亮"始终一致。
+ *
+ * `ranges` 按位置递增(SearchCursor 从 0 扫到 doc.length),所以先把 hidden
+ * 排序合并再用双指针扫一遍即可 —— 早先的 `hidden.some(...)` 是 O(n×m),长文档
+ * 里隐藏标记多 + 命中多时每次输入都要重扫,会让搜索框发涩。
+ */
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),
- );
+ if (hidden.length === 0 || ranges.length === 0) return ranges;
+ const merged = mergeHiddenRanges(hidden);
+ const out: DocSearchRange[] = [];
+ let cursor = 0;
+ for (const range of ranges) {
+ while (cursor < merged.length && merged[cursor].to <= range.from) cursor++;
+ const next = merged[cursor];
+ // 与下一个隐藏区间相交 → 不可见;不相交时保留并不推进游标(后面的命中可能才相交)。
+ if (next && next.from < range.to) continue;
+ out.push(range);
+ }
+ return out;
+}
+
+function mergeHiddenRanges(ranges: DocSearchHiddenRange[]): DocSearchHiddenRange[] {
+ const sorted = [...ranges].sort((a, b) => a.from - b.from || a.to - b.to);
+ const out: DocSearchHiddenRange[] = [];
+ for (const span of sorted) {
+ const last = out[out.length - 1];
+ if (last && span.from <= last.to) {
+ last.to = Math.max(last.to, span.to);
+ continue;
+ }
+ out.push({ ...span });
+ }
+ return out;
}
/** 取出落在 [from, to) 内的命中(表格 widget 用它在自己 DOM 里补画高亮)。 */
diff --git a/apps/desktop/src/renderer/components/markdown/markdownTableLivePreview.ts b/apps/desktop/src/renderer/components/markdown/markdownTableLivePreview.ts
index 45657c9d4d..0f2a55da2e 100644
--- a/apps/desktop/src/renderer/components/markdown/markdownTableLivePreview.ts
+++ b/apps/desktop/src/renderer/components/markdown/markdownTableLivePreview.ts
@@ -182,13 +182,31 @@ function isMarkdownTableSeparator(text: unknown): boolean {
*/
export function collectMarkdownTableHiddenRanges(
doc: EditorView['state']['doc'],
+ blocks: MarkdownTableBlock[] = collectMarkdownTableBlocks(doc),
): Array<{ from: number; to: number }> {
const out: Array<{ from: number; to: number }> = [];
+ for (const block of blocks) {
+ out.push(...complementOfCellTextRanges(doc, block));
+ }
+ return out;
+}
+
+/**
+ * 一次性线性扫描出全文的表格块。搜索可见性口径有多个消费者(表格结构字符、
+ * conceal 行判定),共用这一份结果 —— 逐行各自调 `findMarkdownTableAtLineInDoc`
+ * 会让每行都重扫整段,大文档上变成平方级(每次输入都跑一遍)。
+ *
+ * 块内行整段跳过,所以每个候选行只被探测一次。
+ */
+export function collectMarkdownTableBlocks(
+ doc: EditorView['state']['doc'],
+): MarkdownTableBlock[] {
+ const blocks: MarkdownTableBlock[] = [];
let line = doc.line(1);
while (line.number <= doc.lines) {
const block = findMarkdownTableAtLineInDoc(doc, line.number);
if (block) {
- out.push(...complementOfCellTextRanges(doc, block));
+ blocks.push(block);
const blockEndLine = doc.lineAt(block.to).number;
if (blockEndLine >= doc.lines) break;
line = doc.line(blockEndLine + 1);
@@ -197,7 +215,7 @@ export function collectMarkdownTableHiddenRanges(
if (line.to >= doc.length) break;
line = doc.line(line.number + 1);
}
- return out;
+ return blocks;
}
function complementOfCellTextRanges(
@@ -206,13 +224,24 @@ function complementOfCellTextRanges(
): Array<{ from: number; to: number }> {
const visible: Array<{ from: number; to: number }> = [];
const hidden: Array<{ from: number; to: number }> = [];
+ // 渲染模型会把超出列数的 cell 截掉(normalizeCells),那些文字没有对应单元格
+ // 可高亮 —— 宽度超出的行必须整段算隐藏,否则搜索条会报点不到的高亮。
+ const renderedColumns = getColumnCount(block.model);
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)) {
+ const cells = splitMarkdownTableRowWithRanges(line.text, line.from);
+ for (let index = 0; index < cells.length; index++) {
+ const cell = cells[index];
+ if (index >= renderedColumns) {
+ if (cell.contentTo > cell.contentFrom) {
+ hidden.push({ from: cell.contentFrom, to: cell.contentTo });
+ }
+ continue;
+ }
if (cell.contentTo <= cell.contentFrom) continue;
visible.push({ from: cell.contentFrom, to: cell.contentTo });
hidden.push(...collectCellInlineMarkerRanges(cell));
@@ -1475,11 +1504,14 @@ function applyTableSearchHighlights(
? block.model.header[columnIndex]
: block.model.rows[rowIndex - 1]?.[columnIndex];
if (!modelCell) continue;
+ const ranges = computeCellSearchRanges(modelCell, highlights, block.from);
+ // dataset 一定要先写:编辑中的 cell 只暂缓重绘,不能暂缓"新高亮是多少"。
+ // 否则失焦后 renderTableCells 会拿旧区间重画,搜索条是新查询、单元格却回到
+ // 上一轮的高亮(project-search 跳转不聚焦搜索框,这条路径是真实存在的)。
+ cell.dataset.searchHighlights = serializeSearchRanges(ranges);
// 正在编辑 / 输入法组合中的单元格不重绘:重绘会打断用户输入与光标。
// 高亮在 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);
}
}