From e3e5acffd04bdd899a23060776ea6ef884c2b455 Mon Sep 17 00:00:00 2001 From: lqtdys Date: Wed, 2 Dec 2026 19:43:55 +0800 Subject: [PATCH] =?UTF-8?q?fix(search):=20=E6=90=9C=E7=B4=A2=E5=90=8E?= =?UTF-8?q?=E6=AD=A3=E6=96=87=E5=91=BD=E4=B8=AD=E6=8C=81=E4=B9=85=E9=AB=98?= =?UTF-8?q?=E4=BA=AE=EF=BC=88CM6=20=E7=BC=96=E8=BE=91/=E6=BA=90=E7=A0=81?= =?UTF-8?q?=E6=80=81=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fixes #1841 --- .artifacts/1841/state-coverage.json | 33 +++++ e2e/search-body-highlight.spec.ts | 139 ++++++++++++++++++ .../Content/SearchReplacePanel.test.tsx | 41 ++++-- src/components/Content/SearchReplacePanel.tsx | 19 +++ src/editors/searchHighlight.ts | 66 +++++++++ src/editors/setup.ts | 4 + src/styles/search-float.css | 6 + 7 files changed, 294 insertions(+), 14 deletions(-) create mode 100644 .artifacts/1841/state-coverage.json create mode 100644 e2e/search-body-highlight.spec.ts create mode 100644 src/editors/searchHighlight.ts diff --git a/.artifacts/1841/state-coverage.json b/.artifacts/1841/state-coverage.json new file mode 100644 index 00000000..7988b7b6 --- /dev/null +++ b/.artifacts/1841/state-coverage.json @@ -0,0 +1,33 @@ +{ + "task": "1841-search-body-highlight", + "states": [ + { + "state": "01-edit-all-hits", + "screenshot": ".artifacts/1841/01-edit-all-hits.png", + "assertion": "passed", + "recorded_at": "2026-12-02T11:38:51.500Z", + "runner": "unknown@unknown" + }, + { + "state": "03-clear-query", + "screenshot": ".artifacts/1841/03-clear-query.png", + "assertion": "passed", + "recorded_at": "2026-12-02T11:38:51.580Z", + "runner": "unknown@unknown" + }, + { + "state": "04-close-cleared", + "screenshot": ".artifacts/1841/04-close-cleared.png", + "assertion": "passed", + "recorded_at": "2026-12-02T11:38:51.623Z", + "runner": "unknown@unknown" + }, + { + "state": "02-source-all-hits", + "screenshot": ".artifacts/1841/02-source-all-hits.png", + "assertion": "passed", + "recorded_at": "2026-12-02T11:38:52.688Z", + "runner": "unknown@unknown" + } + ] +} diff --git a/e2e/search-body-highlight.spec.ts b/e2e/search-body-highlight.spec.ts new file mode 100644 index 00000000..f092f3a6 --- /dev/null +++ b/e2e/search-body-highlight.spec.ts @@ -0,0 +1,139 @@ +import { test, expect, type Page } from "@playwright/test"; +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import path from "node:path"; + +/** + * 正文搜索命中持久高亮(#1841 / D6)真实浏览器用例。 + * + * 走 e2e/mocks/tauri-mock.js:`__biaoyue_openFile__` 注入文档, + * `__biaoyue_store__` 切模式。断言落到 CM6 正文的 `.cm-search-hit` 装饰 + * 节点数与计算样式,不停留在「元素存在」。 + * + * 范围:只覆盖 CM6 正文(编辑态 / 源码态)。阅读 / 预览态由 PreviewView + * (HTML)渲染,不在本票范围。 + */ + +/** 含 3 处重复词的文档:正文里「命中」出现 3 次。 */ +const DOC = ["# 标题", "", "正文命中一", "", "正文命中二", "", "结尾命中"].join( + "\n", +); + +const ART_1841 = path.resolve(process.cwd(), ".artifacts/1841"); + +async function recordState1841(page: Page, state: string): Promise { + mkdirSync(ART_1841, { recursive: true }); + const file = path.join(ART_1841, `${state}.png`); + await page.screenshot({ path: file }); + const manifest = path.join(ART_1841, "state-coverage.json"); + let states: Array> = []; + try { + states = JSON.parse(readFileSync(manifest, "utf8")).states ?? []; + } catch { + states = []; + } + states = states.filter((s) => s.state !== state); + states.push({ + state, + screenshot: path.relative(process.cwd(), file), + assertion: "passed", + recorded_at: new Date().toISOString(), + runner: `${process.env.USER ?? "unknown"}@${process.env.HOSTNAME ?? "unknown"}`, + }); + writeFileSync( + manifest, + `${JSON.stringify({ task: "1841-search-body-highlight", states }, null, 2)}\n`, + ); +} + +async function boot(page: Page): Promise { + await page.addInitScript({ path: "./e2e/mocks/tauri-mock.js" }); + await page.goto("/", { waitUntil: "networkidle" }); + await page.waitForSelector('[data-testid="pane-header"]', { timeout: 15000 }); +} + +async function openDoc(page: Page, content: string): Promise { + await page.evaluate((c) => { + ( + window as unknown as { + __biaoyue_openFile__: (p: string, c: string, t?: string) => boolean; + } + ).__biaoyue_openFile__("/Users/test/highlight.md", c, "highlight.md"); + }, content); +} + +async function setMode(page: Page, mode: "preview" | "edit" | "source") { + await page.evaluate((m) => { + ( + window as unknown as { + __biaoyue_store__: { + getState: () => { setEditorMode: (m: string) => void }; + }; + } + ).__biaoyue_store__ + .getState() + .setEditorMode(m as "preview" | "edit" | "source"); + }, mode); +} + +/** 正文 `.cm-search-hit` 节点数。 */ +async function hitCount(page: Page): Promise { + return page.evaluate( + () => document.querySelectorAll(".cm-search-hit").length, + ); +} + +/** 正文 `.cm-search-hit` 的计算背景色(无节点时为 null)。 */ +async function hitBackground(page: Page): Promise { + return page.evaluate(() => { + const el = document.querySelector(".cm-search-hit"); + return el ? getComputedStyle(el).backgroundColor : null; + }); +} + +test.beforeEach(async ({ page }) => { + await boot(page); + await openDoc(page, DOC); + await setMode(page, "edit"); +}); + +test("#1841 编辑态:⌘F 输入重复词后正文全部命中持久高亮,清空 / 关闭即清除", async ({ + page, +}) => { + await page.keyboard.press("Meta+f"); + const input = page.locator('[data-testid="search-float-input"]'); + await expect(input).toBeFocused(); + + await input.fill("命中"); + await expect(page.locator('[data-testid="search-float-count"]')).toHaveText( + "3 处", + ); + + // 正文 3 处命中全部高亮,且背景非透明(真实可见)。 + await expect.poll(async () => hitCount(page)).toBe(3); + expect(await hitBackground(page)).not.toBe("rgba(0, 0, 0, 0)"); + await recordState1841(page, "01-edit-all-hits"); + + // 清空查询 → 正文高亮清除。 + await page.locator('[data-testid="search-float-clear"]').click(); + await expect.poll(async () => hitCount(page)).toBe(0); + await recordState1841(page, "03-clear-query"); + + // 再输入后关闭浮窗(Esc)→ 正文高亮清除。 + await input.fill("命中"); + await expect.poll(async () => hitCount(page)).toBe(3); + await page.keyboard.press("Escape"); + await expect(page.locator('[data-testid="search-float"]')).toBeHidden(); + await expect.poll(async () => hitCount(page)).toBe(0); + await recordState1841(page, "04-close-cleared"); +}); + +test("#1841 源码态:同一浮窗在源码态也高亮正文全部命中", async ({ page }) => { + await page.keyboard.press("Meta+f"); + await page.locator('[data-testid="search-float-input"]').fill("命中"); + await expect.poll(async () => hitCount(page)).toBe(3); + + await setMode(page, "source"); + await expect.poll(async () => hitCount(page)).toBe(3); + expect(await hitBackground(page)).not.toBe("rgba(0, 0, 0, 0)"); + await recordState1841(page, "02-source-all-hits"); +}); diff --git a/src/__tests__/components/Content/SearchReplacePanel.test.tsx b/src/__tests__/components/Content/SearchReplacePanel.test.tsx index df272014..3bf01785 100644 --- a/src/__tests__/components/Content/SearchReplacePanel.test.tsx +++ b/src/__tests__/components/Content/SearchReplacePanel.test.tsx @@ -194,12 +194,16 @@ describe("SearchReplacePanel 点击定位到浮窗所属窗格", () => { }); fireEvent.click(getAllByTestId("search-float-hit")[1]); - expect(own.dispatch).toHaveBeenCalledTimes(1); expect(own.focus).toHaveBeenCalledTimes(1); expect(active.dispatch).not.toHaveBeenCalled(); expect(active.focus).not.toHaveBeenCalled(); - const arg = (own.dispatch as ReturnType).mock.calls[0][0] as { + // #1841 的正文高亮 effect 也走 dispatch,但定位选区事务必须恰好一次。 + const selectionCalls = ( + own.dispatch as ReturnType + ).mock.calls.filter((c) => c[0]?.selection !== undefined); + expect(selectionCalls).toHaveLength(1); + const arg = selectionCalls[0][0] as { selection: { anchor: number; head: number }; }; expect(arg.selection.head).toBeGreaterThan(arg.selection.anchor); @@ -212,6 +216,7 @@ describe("SearchReplacePanel 点击定位到浮窗所属窗格", () => { const { getByTestId } = renderPanel("panel-b"); keyDown(getByTestId("search-float-input"), { key: "Enter" }); + // 初始 appliedKey 为 "null",空查询不派发高亮,故无任何 dispatch。 expect(own.dispatch).not.toHaveBeenCalled(); }); @@ -226,7 +231,10 @@ describe("SearchReplacePanel 点击定位到浮窗所属窗格", () => { keyDown(input, { key: "ArrowDown" }); keyDown(input, { key: "Enter" }); - expect(own.dispatch).toHaveBeenCalledTimes(1); + const selectionCalls = ( + own.dispatch as ReturnType + ).mock.calls.filter((c) => c[0]?.selection !== undefined); + expect(selectionCalls).toHaveLength(1); expect(own.focus).toHaveBeenCalledTimes(1); }); @@ -240,7 +248,10 @@ describe("SearchReplacePanel 点击定位到浮窗所属窗格", () => { keyDown(input, { key: "ArrowDown" }); keyDown(input, { key: "Enter" }); - expect(own.dispatch).toHaveBeenCalledTimes(1); + const selectionCalls = ( + own.dispatch as ReturnType + ).mock.calls.filter((c) => c[0]?.selection !== undefined); + expect(selectionCalls).toHaveLength(1); expect(document.activeElement).toBe(input); keyDown(input, { key: "ArrowUp" }); @@ -319,14 +330,15 @@ describe("SearchReplacePanel 替换与关闭还焦落到所属窗格", () => { }); fireEvent.click(getByTestId("search-float-replace-one")); - expect(own.dispatch).toHaveBeenCalledTimes(1); expect(active.dispatch).not.toHaveBeenCalled(); expect(active.focus).not.toHaveBeenCalled(); - const arg = (own.dispatch as ReturnType).mock.calls[0][0] as { - changes: unknown[]; - }; - expect(arg.changes).toHaveLength(1); + // #1841 的高亮 effect 也走 dispatch,但替换事务必须恰好一次。 + const changeCalls = ( + own.dispatch as ReturnType + ).mock.calls.filter((c) => c[0]?.changes !== undefined); + expect(changeCalls).toHaveLength(1); + expect(changeCalls[0][0].changes).toHaveLength(1); }); it("点击「全部替换」只对 panelId 视图 dispatch,不碰全局最近聚焦视图", () => { @@ -345,14 +357,15 @@ describe("SearchReplacePanel 替换与关闭还焦落到所属窗格", () => { }); fireEvent.click(getByTestId("search-float-replace-all")); - expect(own.dispatch).toHaveBeenCalledTimes(1); expect(active.dispatch).not.toHaveBeenCalled(); expect(active.focus).not.toHaveBeenCalled(); - const arg = (own.dispatch as ReturnType).mock.calls[0][0] as { - changes: unknown[]; - }; - expect(arg.changes).toHaveLength(3); + // #1841 的高亮 effect 也走 dispatch,但替换事务必须恰好一次。 + const changeCalls = ( + own.dispatch as ReturnType + ).mock.calls.filter((c) => c[0]?.changes !== undefined); + expect(changeCalls).toHaveLength(1); + expect(changeCalls[0][0].changes).toHaveLength(3); }); it("Esc 关闭后还焦到所属窗格视图,不还焦全局最近聚焦视图", () => { diff --git a/src/components/Content/SearchReplacePanel.tsx b/src/components/Content/SearchReplacePanel.tsx index 6d47044b..034ac68d 100644 --- a/src/components/Content/SearchReplacePanel.tsx +++ b/src/components/Content/SearchReplacePanel.tsx @@ -41,6 +41,7 @@ import Icon from "../Icon"; import { useSearchFloatStore } from "../../stores/searchFloat"; import { useEditorStore } from "../../stores/editorStore"; import { getEditorView } from "../../editors/editorRef"; +import { setSearchHighlight } from "../../editors/searchHighlight"; import type { EditorMode, SearchPanelDefaultPos } from "../../types"; const BLOCK_TYPE_LABELS: Record = { @@ -292,6 +293,24 @@ export default function SearchReplacePanel({ }, [panelId]); const hits = useMemo(() => searchScan(content, query), [content, query]); + + // 正文搜索命中持久高亮(#1841):把命中区间派发给 CM6 正文装饰字段。 + // 预览态 / 空查询 / 浮窗关闭时清除,避免编辑态残留。既有 locate / 替换逻辑不变。 + const appliedKeyRef = useRef("null"); + useEffect(() => { + const view = getEditorView(panelId); + if (!view) return; + const active = open && mode !== "preview" && query.trim() !== ""; + const ranges = active + ? hits.map((hit) => ({ from: hit.from, to: hit.to })) + : null; + const key = ranges + ? ranges.map((range) => `${range.from}:${range.to}`).join(",") + : "null"; + if (key === appliedKeyRef.current) return; + appliedKeyRef.current = key; + view.dispatch({ effects: setSearchHighlight.of(ranges) }); + }, [hits, open, mode, panelId, query]); const blocks = useMemo(() => splitSearchBlocks(content), [content]); const snippetHits = useMemo( () => diff --git a/src/editors/searchHighlight.ts b/src/editors/searchHighlight.ts new file mode 100644 index 00000000..93395ad8 --- /dev/null +++ b/src/editors/searchHighlight.ts @@ -0,0 +1,66 @@ +/* 正文搜索命中持久高亮(#1841 / D6)。 + * + * 自研搜索浮窗(#981)只向编辑器派发 `selection + scrollIntoView`,从不派发 + * 搜索装饰;CM6 内置 `searchKeymap` / 搜索装饰早于 #981 被移除,于是正文里 + * 多次出现的词不会持久高亮。这里补一个独立 StateField:浮窗把命中区间 + * (文档偏移,与 CM6 `doc` 同源)作为 effect 派发,字段据此生成 + * `Decoration.mark({ class: "cm-search-hit" })`。 + * + * 与 `editors/decorations/` 的块装饰并存:两者都是 `DecorationSet` 字段, + * 各自 `EditorView.decorations.from(field)` 提供,互不覆盖。 + */ +import { + StateEffect, + StateField, + type Extension, + type Transaction, +} from "@codemirror/state"; +import { Decoration, EditorView, type DecorationSet } from "@codemirror/view"; + +/** 命中区间(文档偏移);`null` 表示清除全部正文高亮。 */ +export const setSearchHighlight = StateEffect.define< + { from: number; to: number }[] | null +>(); + +/** + * 正文搜索高亮字段。 + * + * 文档变更时先按 `tr.changes` 映射既有装饰,再应用本次事务里的 + * `setSearchHighlight` effect(后到的 effect 覆盖先到的)。区间做 `from < to` + * 与文档边界防护,避免越界或倒置区间让 `Decoration.set` 抛错。 + */ +const searchHighlightField = StateField.define({ + create() { + return Decoration.none; + }, + update(deco, tr: Transaction) { + let next = deco.map(tr.changes); + for (const effect of tr.effects) { + if (!effect.is(setSearchHighlight)) continue; + if (effect.value === null) { + next = Decoration.none; + continue; + } + const docLength = tr.state.doc.length; + const ranges = effect.value + .filter( + (range) => + range.from < range.to && range.from >= 0 && range.to <= docLength, + ) + .map((range) => + Decoration.mark({ class: "cm-search-hit" }).range( + range.from, + range.to, + ), + ); + next = Decoration.set(ranges, true); + } + return next; + }, + provide: (field) => EditorView.decorations.from(field), +}); + +/** 装配进编辑器的扩展:编辑态与源码态都生效(不放进 decorCompartment)。 */ +export function searchHighlightExtension(): Extension { + return searchHighlightField; +} diff --git a/src/editors/setup.ts b/src/editors/setup.ts index 8112a08d..c8ea2721 100644 --- a/src/editors/setup.ts +++ b/src/editors/setup.ts @@ -24,6 +24,7 @@ import { yaml } from "@codemirror/lang-yaml"; import type { FileKind } from "../types"; import { editorDecorations } from "./decorations"; import type { EditorDecorationsOptions } from "./decorations"; +import { searchHighlightExtension } from "./searchHighlight"; import { smartInput } from "./smart-input"; import { slashKeymap } from "./slash"; import { floatingToolbar } from "./orchestration/floating-toolbar"; @@ -78,6 +79,9 @@ export function baseEditorExtensions(): Extension[] { EditorView.lineWrapping, drawSelection(), EditorState.allowMultipleSelections.of(true), + // 正文搜索命中持久高亮(#1841):编辑态与源码态都生效,故不进 + // decorCompartment(那会随模式切换被摘掉)。浮窗派发命中区间。 + searchHighlightExtension(), // 撤销历史不在这里:它由 `historyCompartment` 提供,ContentArea 才能在 // 切页签时清空(#321)。`createExtensions` 与 ContentArea 都要显式装回。 indentOnInput(), diff --git a/src/styles/search-float.css b/src/styles/search-float.css index 750aa30e..5b9873a1 100644 --- a/src/styles/search-float.css +++ b/src/styles/search-float.css @@ -1,5 +1,11 @@ /* 搜索浮窗(#981 / S-1):系统浮层范式,绝对定位在当前窗格内。 */ +/* 正文搜索命中持久高亮(#1841 / D6):CM6 装饰类,编辑态与源码态都生效。 */ +.cm-search-hit { + background: var(--app-accent-soft); + border-radius: var(--radius-4); +} + .search-float { z-index: 40; width: min(300px, calc(100% - 48px));