Skip to content
Open
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
207 changes: 207 additions & 0 deletions e2e/search-shortcut-global.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
import { test, expect, type Locator, type Page } from "@playwright/test";
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import path from "node:path";

/**
* #1987 搜索浮窗前台时 ⌘1~9 / Enter 无需焦点在浮窗内即生效。
*
* 浮窗打开且前台可见时,焦点在编辑器(编辑态 CM6)按真实 ⌘3 / Enter
* 应定位到第 3 条 / 当前条;焦点在浮窗外的普通输入框(设置面板)不劫持;
* 关闭浮窗后 ⌘1~9 恢复全局行为(无残留绑定)。
*
* 先红:现有 ⌘N 用例都先点进浮窗输入框(焦点在浮窗内),本文件补焦点在
* 编辑器 / 浮窗外的用例。
*/

const DOC = [
"# 属性面板",
"",
"这是属性面板的正文。",
"",
"## 第二段",
"",
"属性面板可以配置。",
].join("\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 = DOC): Promise<void> {
await page.evaluate(
(args) => {
(
window as unknown as {
__biaoyue_openFile__: (p: string, c: string, t?: string) => boolean;
}
).__biaoyue_openFile__(args.path, args.content, "search.md");
},
{ path: "/Users/test/search.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);
}

async function openFloat(page: Page): Promise<Locator> {
await page.keyboard.press("Meta+f");
const float = page.locator('[data-testid="search-float"]');
await expect(float).toBeVisible();
return float;
}

async function highlightedRowIndex(float: Locator): Promise<number> {
return float.evaluate((el) => {
const cur = el.querySelector<HTMLElement>(".search-float-hit-cur");
return cur ? Number(cur.dataset.index) : -1;
});
}

async function fillQuery(float: Locator, query: string): Promise<void> {
await float.locator('[data-testid="search-float-input"]').fill(query);
await expect(float.locator('[data-testid="search-float-hit"]')).toHaveCount(
3,
);
}

async function focusEditor(page: Page): Promise<void> {
await page.evaluate(() => {
(document.querySelector(".cm-content") as HTMLElement).focus();
});
await expect
.poll(async () =>
page.evaluate(() => document.activeElement?.className ?? ""),
)
.toContain("cm-content");
}

const ART = path.resolve(process.cwd(), ".artifacts/1987");

async function recordState(page: Page, state: string): Promise<void> {
mkdirSync(ART, { recursive: true });
const file = path.join(ART, `${state}.png`);
await page.screenshot({ path: file });
const manifest = path.join(ART, "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: "1987-search-shortcut-global", states }, null, 2)}\n`,
);
}

test.beforeEach(async ({ page }) => {
await boot(page);
await openDoc(page);
await setMode(page, "edit");
});

test("#1987 浮窗前台 + 编辑器聚焦:⌘3 直达第 3 条并定位,不触发全局卡片直开", async ({
page,
}) => {
const float = await openFloat(page);
await fillQuery(float, "属性");
expect(await highlightedRowIndex(float)).toBe(0);

// 焦点放回编辑器(浮窗保持打开、前台可见)。
await focusEditor(page);

await page.keyboard.press("Meta+3");
expect(await highlightedRowIndex(float)).toBe(2);
await expect(
float.locator('[data-testid="search-float-hit"]').nth(2),
).toHaveClass(/search-float-hit-cur/);
// locate 会把选区派发到编辑器(#1055:Enter 定位选中行 → 编辑器出现选区)。
await expect
.poll(async () => page.locator(".cm-selectionBackground").count())
.toBeGreaterThan(0);
await recordState(page, "01-editor-meta3");
});

test("#1987 浮窗前台 + 编辑器聚焦:Enter 定位当前条", async ({ page }) => {
const float = await openFloat(page);
await fillQuery(float, "属性");
await focusEditor(page);

await page.keyboard.press("ArrowDown");
expect(await highlightedRowIndex(float)).toBe(1);

await page.keyboard.press("Enter");
await expect(
float.locator('[data-testid="search-float-hit"]').nth(1),
).toHaveClass(/search-float-hit-cur/);
await expect
.poll(async () => page.locator(".cm-selectionBackground").count())
.toBeGreaterThan(0);
await recordState(page, "02-editor-enter");
});

test("#1987 焦点在浮窗外的普通输入框:⌘N / Enter 不劫持", async ({ page }) => {
const float = await openFloat(page);
await fillQuery(float, "属性");
expect(await highlightedRowIndex(float)).toBe(0);

// 打开设置面板(fixed z-50 覆盖浮窗,但浮窗所属窗格仍可见 = 前台),
// 聚焦 AI 服务面板的真实 input。
await page.keyboard.press("Meta+,");
await expect(page.locator('[data-testid="settings-scene"]')).toBeVisible();
await page.locator('[data-settings-nav="ai"]').click();
const input = page.locator('[data-testid="ai-endpoint-input"]');
await input.click();
await expect(input).toBeFocused();

// 浮窗仍在前台(所属窗格可见),但焦点在浮窗外的普通 input:
// ⌘2 / Enter 不得被劫持去切搜索结果 / 定位。
await page.keyboard.press("Meta+2");
expect(await highlightedRowIndex(float)).toBe(0);
await page.keyboard.press("Enter");
expect(await highlightedRowIndex(float)).toBe(0);
await expect(input).toBeFocused();
await recordState(page, "03-outside-input-not-switch");
});

test("#1987 关闭浮窗后:⌘N 恢复全局行为,无残留绑定", async ({ page }) => {
const float = await openFloat(page);
await fillQuery(float, "属性");
await focusEditor(page);

await page.keyboard.press("Meta+3");
expect(await highlightedRowIndex(float)).toBe(2);

await page.keyboard.press("Escape");
await expect(float).toBeHidden();

// 关闭后 effect 解绑,⌘N 不再被浮窗拦截:无高亮行可读,浮窗仍关闭。
await focusEditor(page);
await page.keyboard.press("Meta+1");
await expect(float).toBeHidden();
await expect(
page.locator('[data-testid="search-float-hit-cur"]'),
).toHaveCount(0);
await recordState(page, "04-closed-no-residue");
});
44 changes: 44 additions & 0 deletions src/components/Content/SearchReplacePanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -731,6 +731,50 @@ export default function SearchReplacePanel({
return () => document.removeEventListener("keydown", onKey, true);
}, [open, hits.length, stepSelected]);

// 浮窗前台时,焦点在编辑器 / 预览面的 ⌘1~9 直达与 Enter 定位(#1987)。
// 与上方 ↑↓ 同构:仅拦截「浮窗打开 + 所属窗格可见 + 焦点不在浮窗内 +
// 焦点不在浮窗外的普通可编辑元素内」的键;stopPropagation 阻止全局
// 「卡片直开 ⌘1–9」抢占。焦点在浮窗内时根节点 capture 已处理,不重复。
useEffect(() => {
if (!open) return;
const onKey = (event: KeyboardEvent) => {
const isEnter = event.key === "Enter";
const digit = isEnter
? null
: localPickDigit("local-search-row-pick", event);
if (!isEnter && digit === null) return;
const root = rootRef.current;
if (!root) return;
// 焦点在浮窗内(含输入框):根节点 capture 已处理,此处不重复拦截。
if (root.contains(document.activeElement)) return;
// 焦点在浮窗外的普通可编辑元素(属性 / 设置面板输入框等):
// ⌘N / Enter 归该输入框,不劫持。
if (isPlainEditableFocus()) return;
const pane = root.closest("[data-pane-id]") as HTMLElement | null;
// 所属窗格不可见(全屏让位 / 沉浸隐藏)时浮窗不在前台,不拦截。
if (!pane || pane.offsetParent === null) return;
if (hits.length === 0) return;
event.preventDefault();
event.stopPropagation();
if (isEnter) {
const hit = hits[safeSelected];
if (hit) locate(hit, safeSelected);
return;
}
if (digit !== null && digit >= 1 && digit <= hits.length) {
const target = Math.min(
firstVisibleIndexRef.current + digit - 1,
hits.length - 1,
);
setSelected(target);
// 直达复用鼠标点击行的 locate,一步滚动 + 高亮,避免第二套定位逻辑。
locate(hits[target], target);
}
};
document.addEventListener("keydown", onKey, true);
return () => document.removeEventListener("keydown", onKey, true);
}, [open, hits, safeSelected, locate]);

// 浮窗根节点 capture 拦截:⌘1~9 直达、↑↓ 换选、Enter 定位、Esc 关闭,
// stopPropagation 使全局「卡片直开 ⌘1–9」等 window 冒泡监听收不到。
useEffect(() => {
Expand Down
Loading