Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions .artifacts/1841/state-coverage.json
Original file line number Diff line number Diff line change
@@ -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"
}
]
}
139 changes: 139 additions & 0 deletions e2e/search-body-highlight.spec.ts
Original file line number Diff line number Diff line change
@@ -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<void> {
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<Record<string, string>> = [];
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<void> {
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<void> {
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<number> {
return page.evaluate(
() => document.querySelectorAll(".cm-search-hit").length,
);
}

/** 正文 `.cm-search-hit` 的计算背景色(无节点时为 null)。 */
async function hitBackground(page: Page): Promise<string | null> {
return page.evaluate(() => {
const el = document.querySelector<HTMLElement>(".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");
});
41 changes: 27 additions & 14 deletions src/__tests__/components/Content/SearchReplacePanel.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof vi.fn>).mock.calls[0][0] as {
// #1841 的正文高亮 effect 也走 dispatch,但定位选区事务必须恰好一次。
const selectionCalls = (
own.dispatch as ReturnType<typeof vi.fn>
).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);
Expand All @@ -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();
});

Expand All @@ -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<typeof vi.fn>
).mock.calls.filter((c) => c[0]?.selection !== undefined);
expect(selectionCalls).toHaveLength(1);
expect(own.focus).toHaveBeenCalledTimes(1);
});

Expand All @@ -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<typeof vi.fn>
).mock.calls.filter((c) => c[0]?.selection !== undefined);
expect(selectionCalls).toHaveLength(1);
expect(document.activeElement).toBe(input);

keyDown(input, { key: "ArrowUp" });
Expand Down Expand Up @@ -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<typeof vi.fn>).mock.calls[0][0] as {
changes: unknown[];
};
expect(arg.changes).toHaveLength(1);
// #1841 的高亮 effect 也走 dispatch,但替换事务必须恰好一次。
const changeCalls = (
own.dispatch as ReturnType<typeof vi.fn>
).mock.calls.filter((c) => c[0]?.changes !== undefined);
expect(changeCalls).toHaveLength(1);
expect(changeCalls[0][0].changes).toHaveLength(1);
});

it("点击「全部替换」只对 panelId 视图 dispatch,不碰全局最近聚焦视图", () => {
Expand All @@ -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<typeof vi.fn>).mock.calls[0][0] as {
changes: unknown[];
};
expect(arg.changes).toHaveLength(3);
// #1841 的高亮 effect 也走 dispatch,但替换事务必须恰好一次。
const changeCalls = (
own.dispatch as ReturnType<typeof vi.fn>
).mock.calls.filter((c) => c[0]?.changes !== undefined);
expect(changeCalls).toHaveLength(1);
expect(changeCalls[0][0].changes).toHaveLength(3);
});

it("Esc 关闭后还焦到所属窗格视图,不还焦全局最近聚焦视图", () => {
Expand Down
19 changes: 19 additions & 0 deletions src/components/Content/SearchReplacePanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string> = {
Expand Down Expand Up @@ -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(
() =>
Expand Down
66 changes: 66 additions & 0 deletions src/editors/searchHighlight.ts
Original file line number Diff line number Diff line change
@@ -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<DecorationSet>({
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;
}
4 changes: 4 additions & 0 deletions src/editors/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -78,6 +79,9 @@ export function baseEditorExtensions(): Extension[] {
EditorView.lineWrapping,
drawSelection(),
EditorState.allowMultipleSelections.of(true),
// 正文搜索命中持久高亮(#1841):编辑态与源码态都生效,故不进
// decorCompartment(那会随模式切换被摘掉)。浮窗派发命中区间。
searchHighlightExtension(),
// 撤销历史不在这里:它由 `historyCompartment` 提供,ContentArea 才能在
// 切页签时清空(#321)。`createExtensions` 与 ContentArea 都要显式装回。
indentOnInput(),
Expand Down
6 changes: 6 additions & 0 deletions src/styles/search-float.css
Original file line number Diff line number Diff line change
@@ -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));
Expand Down
Loading