返回 CodeWhale
docs-search.test.tsx
根目录 / web / components / docs-search.test.tsx
1 import { renderToStaticMarkup } from "react-dom/server";
2 import { describe, expect, it } from "vitest";
3 import { DocsSearch, isDocsSearchShortcut } from "./docs-search";
4 import type { ShortcutKeyEvent } from "@/lib/slash-shortcut";
5
6 function keyEvent(
7 overrides: Partial<ShortcutKeyEvent & { shiftKey?: boolean }> = {},
8 ): ShortcutKeyEvent & { shiftKey?: boolean } {
9 return {
10 key: "/",
11 ctrlKey: false,
12 metaKey: false,
13 altKey: false,
14 shiftKey: false,
15 isComposing: false,
16 target: { tagName: "BODY", isContentEditable: false },
17 ...overrides,
18 };
19 }
20
21 describe("DocsSearch keyboard shortcuts and hint badge", () => {
22 it("accepts Ctrl+K, Cmd+K, and unmodified / outside editable fields", () => {
23 expect(isDocsSearchShortcut(keyEvent({ key: "/" }))).toBe(true);
24 expect(isDocsSearchShortcut(keyEvent({ key: "k", ctrlKey: true }))).toBe(true);
25 expect(isDocsSearchShortcut(keyEvent({ key: "K", metaKey: true }))).toBe(true);
26 expect(
27 isDocsSearchShortcut(keyEvent({ key: "k", ctrlKey: true, target: { tagName: "INPUT" } })),
28 ).toBe(true);
29 });
30
31 it("ignores / inside editable controls and ignores modified K combinations", () => {
32 expect(isDocsSearchShortcut(keyEvent({ key: "/", target: { tagName: "INPUT" } }))).toBe(false);
33 expect(isDocsSearchShortcut(keyEvent({ key: "/", target: { tagName: "TEXTAREA" } }))).toBe(false);
34 expect(isDocsSearchShortcut(keyEvent({ key: "/", target: { tagName: "SELECT" } }))).toBe(false);
35 expect(
36 isDocsSearchShortcut(keyEvent({ key: "/", target: { tagName: "DIV", isContentEditable: true } })),
37 ).toBe(false);
38 expect(isDocsSearchShortcut(keyEvent({ key: "k", ctrlKey: true, shiftKey: true }))).toBe(false);
39 expect(isDocsSearchShortcut(keyEvent({ key: "k", ctrlKey: true, altKey: true }))).toBe(false);
40 expect(isDocsSearchShortcut(keyEvent({ key: "k", ctrlKey: true, isComposing: true }))).toBe(false);
41 });
42
43 it("renders visible Ctrl+K and / hint badges with aria-keyshortcuts", () => {
44 const html = renderToStaticMarkup(<DocsSearch locale="en" />);
45 expect(html).toContain('aria-keyshortcuts="/ Control+k Meta+k"');
46 expect(html).toContain("docs-search-shortcut");
47 expect(html).toContain("<kbd>Ctrl+K</kbd>");
48 expect(html).toContain("<kbd>/</kbd>");
49 });
50 });
51
51 lines Plain Text