| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465 |
- import { act, createElement, type ReactNode } from "react";
- import { createRoot, type Root } from "react-dom/client";
- import { afterEach, describe, expect, it, vi } from "vitest";
- type CapturedButtonProps = {
- "aria-label"?: string;
- onClick?: () => void;
- };
- type CapturedInputProps = {
- onChange?: (event: { target: { value: string } }) => void;
- onKeyDown?: (event: {
- key: string;
- preventDefault: () => void;
- shiftKey: boolean;
- }) => void;
- };
- const { capturedButtonProps, capturedInputProps } = vi.hoisted(() => ({
- capturedButtonProps: [] as CapturedButtonProps[],
- capturedInputProps: [] as CapturedInputProps[],
- }));
- type TestEvent = {
- bubbles?: boolean;
- button?: number;
- currentTarget?: TestElement;
- defaultPrevented?: boolean;
- key?: string;
- preventDefault?: () => void;
- shiftKey?: boolean;
- stopPropagation?: () => void;
- target?: TestElement;
- type: string;
- };
- type TestEventHandler = (event: TestEvent) => void;
- type TestNode = TestElement | {
- nodeType: 3;
- nodeValue: string;
- ownerDocument: Document;
- parentNode: TestElement | null;
- };
- type TestElement = Element & {
- __attrs: Map<string, string>;
- __listeners: Map<string, TestEventHandler[]>;
- childNodes: TestNode[];
- dispatchEvent: (event: TestEvent) => boolean;
- focus: () => void;
- parentNode: TestElement | null;
- value: string;
- };
- vi.mock("lucide-react", () => {
- const createIcon = (name: string) => (props: Record<string, unknown>) =>
- createElement("svg", { "data-icon": name, ...props });
- return {
- ArrowDownIcon: createIcon("arrow-down"),
- ArrowUpIcon: createIcon("arrow-up"),
- FileDiffIcon: createIcon("file-diff"),
- MessageCircleIcon: createIcon("message-circle"),
- SearchIcon: createIcon("search"),
- XIcon: createIcon("x"),
- };
- });
- vi.mock("react/jsx-runtime", async () => {
- const actual = await vi.importActual<typeof import("react/jsx-runtime")>(
- "react/jsx-runtime",
- );
- const capture =
- (factory: typeof actual.jsx) =>
- (type: Parameters<typeof actual.jsx>[0], props: Record<string, unknown>, key?: string) => {
- if (type === "input") {
- capturedInputProps.push(props as CapturedInputProps);
- }
- return factory(type, props, key);
- };
- return {
- ...actual,
- jsx: capture(actual.jsx),
- jsxs: capture(actual.jsxs),
- };
- });
- vi.mock("react/jsx-dev-runtime", async () => {
- const actual = await vi.importActual<typeof import("react/jsx-dev-runtime")>(
- "react/jsx-dev-runtime",
- );
- return {
- ...actual,
- jsxDEV: (
- type: Parameters<typeof actual.jsxDEV>[0],
- props: Record<string, unknown>,
- ...rest: unknown[]
- ) => {
- if (type === "input") {
- capturedInputProps.push(props as CapturedInputProps);
- }
- return actual.jsxDEV(type, props, ...rest);
- },
- };
- });
- vi.mock("@/components/ui/button.js", () => ({
- Button: ({ children, ...props }: { children?: ReactNode } & CapturedButtonProps) => {
- capturedButtonProps.push(props);
- return createElement("button", props, children);
- },
- }));
- vi.mock("@/ControlHintTooltip.js", () => ({
- ControlHintTooltip: ({ children }: { children?: ReactNode }) => children,
- }));
- vi.mock("@/i18n/IntlProvider.js", () => ({
- useZCodeIntl: () => ({
- intl: {
- formatMessage: ({ id }: { id: string }) => id,
- },
- }),
- }));
- function createMinimalElement(ownerDocument: Document, tagName = "div") {
- const element = {
- __attrs: new Map<string, string>(),
- __listeners: new Map<string, TestEventHandler[]>(),
- addEventListener: (type: string, handler: TestEventHandler) => {
- const handlers = element.__listeners.get(type) ?? [];
- handlers.push(handler);
- element.__listeners.set(type, handlers);
- },
- appendChild: (child: TestNode) => {
- child.parentNode = element as unknown as TestElement;
- element.childNodes.push(child);
- return child;
- },
- childNodes: [] as TestNode[],
- dispatchEvent: (event: TestEvent) => {
- event.target ??= element as unknown as TestElement;
- event.preventDefault ??= () => {
- event.defaultPrevented = true;
- };
- event.stopPropagation ??= () => {};
- let current: TestElement | null = element as unknown as TestElement;
- while (current) {
- event.currentTarget = current;
- for (const handler of current.__listeners.get(event.type) ?? []) {
- handler(event);
- }
- if (!event.bubbles) {
- break;
- }
- current = current.parentNode;
- }
- return !event.defaultPrevented;
- },
- focus: () => {},
- getAttribute: (name: string) => element.__attrs.get(name) ?? null,
- insertBefore: (child: TestNode, beforeChild?: TestNode | null) => {
- child.parentNode = element as unknown as TestElement;
- const beforeIndex = beforeChild
- ? element.childNodes.indexOf(beforeChild)
- : -1;
- if (beforeIndex >= 0) {
- element.childNodes.splice(beforeIndex, 0, child);
- } else {
- element.childNodes.push(child);
- }
- return child;
- },
- nodeName: tagName.toUpperCase(),
- nodeType: 1,
- ownerDocument,
- parentNode: null as TestElement | null,
- removeAttribute: (name: string) => {
- element.__attrs.delete(name);
- },
- removeChild: (child: TestNode) => {
- element.childNodes = element.childNodes.filter((item) => item !== child);
- child.parentNode = null;
- return child;
- },
- removeEventListener: (type: string, handler: TestEventHandler) => {
- element.__listeners.set(
- type,
- (element.__listeners.get(type) ?? []).filter((item) => item !== handler),
- );
- },
- setAttribute: (name: string, value: string) => {
- element.__attrs.set(name, String(value));
- },
- style: {},
- tagName: tagName.toUpperCase(),
- value: "",
- };
- return element as unknown as TestElement;
- }
- function installMinimalDom() {
- const windowListeners = new Map<string, TestEventHandler[]>();
- const documentMock = {
- addEventListener: () => {},
- createElement: (tagName: string) =>
- createMinimalElement(documentMock as unknown as Document, tagName),
- createElementNS: (_namespace: string, tagName: string) =>
- createMinimalElement(documentMock as unknown as Document, tagName),
- createTextNode: (nodeValue: string) => ({
- nodeType: 3 as const,
- nodeValue,
- ownerDocument: documentMock as unknown as Document,
- parentNode: null,
- }),
- nodeType: 9,
- removeEventListener: () => {},
- } as unknown as Document;
- const windowMock = {
- addEventListener: (type: string, handler: TestEventHandler) => {
- const handlers = windowListeners.get(type) ?? [];
- handlers.push(handler);
- windowListeners.set(type, handlers);
- },
- cancelAnimationFrame: () => {},
- document: documentMock,
- HTMLIFrameElement: function HTMLIFrameElement() {},
- HTMLElement: function HTMLElement() {},
- Node: function Node() {},
- removeEventListener: (type: string, handler: TestEventHandler) => {
- windowListeners.set(
- type,
- (windowListeners.get(type) ?? []).filter((item) => item !== handler),
- );
- },
- requestAnimationFrame: (callback: FrameRequestCallback) => {
- callback(0);
- return 1;
- },
- };
- Object.defineProperty(globalThis, "document", {
- configurable: true,
- value: documentMock,
- });
- Object.defineProperty(globalThis, "window", {
- configurable: true,
- value: windowMock,
- });
- Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", {
- configurable: true,
- value: true,
- });
- return {
- container: createMinimalElement(documentMock),
- dispatchWindowEvent: (event: TestEvent) => {
- event.preventDefault ??= () => {
- event.defaultPrevented = true;
- };
- for (const handler of windowListeners.get(event.type) ?? []) {
- handler(event);
- }
- return !event.defaultPrevented;
- },
- };
- }
- function getLatestInputProps() {
- const props = capturedInputProps.at(-1);
- expect(props).toBeDefined();
- return props!;
- }
- function getLatestButtonProps(label: string) {
- for (let index = capturedButtonProps.length - 1; index >= 0; index -= 1) {
- if (capturedButtonProps[index]?.["aria-label"] === label) {
- return capturedButtonProps[index]!;
- }
- }
- throw new Error(`没有找到按钮: ${label}`);
- }
- async function renderDialog({
- conversationMatchCount = 1,
- fileChangeMatchCount = 1,
- }: {
- conversationMatchCount?: number;
- fileChangeMatchCount?: number;
- } = {}) {
- const { TaskFindDialog } = await import("@/quickpick/TaskFindDialog.js");
- const { container, dispatchWindowEvent } = installMinimalDom();
- const root: Root = createRoot(container);
- const callbacks = {
- onConversationFindChange: vi.fn(),
- onConversationFindNavigate: vi.fn(),
- onFileChangeFindChange: vi.fn(),
- onFileChangeFindNavigate: vi.fn(),
- onOpenChange: vi.fn(),
- onOpenFileChanges: vi.fn(),
- };
- act(() => {
- root.render(
- createElement(TaskFindDialog, {
- open: true,
- placement: "chat",
- focusRequestId: 0,
- conversationMatchCount,
- conversationMatchIndex: 0,
- fileChangeMatchCount,
- fileChangeMatchIndex: 0,
- ...callbacks,
- }),
- );
- });
- act(() => {
- getLatestInputProps().onChange?.({ target: { value: "needle" } });
- });
- return { callbacks, dispatchWindowEvent, root };
- }
- function clearFindCallbacks(callbacks: Awaited<ReturnType<typeof renderDialog>>["callbacks"]) {
- callbacks.onConversationFindChange.mockClear();
- callbacks.onConversationFindNavigate.mockClear();
- callbacks.onFileChangeFindChange.mockClear();
- callbacks.onFileChangeFindNavigate.mockClear();
- }
- function triggerSixNavigationEntries() {
- act(() => {
- getLatestButtonProps("quickPick.find.previous").onClick?.();
- getLatestButtonProps("quickPick.find.next").onClick?.();
- getLatestInputProps().onKeyDown?.({
- key: "ArrowUp",
- preventDefault: vi.fn(),
- shiftKey: false,
- });
- getLatestInputProps().onKeyDown?.({
- key: "ArrowDown",
- preventDefault: vi.fn(),
- shiftKey: false,
- });
- getLatestInputProps().onKeyDown?.({
- key: "Enter",
- preventDefault: vi.fn(),
- shiftKey: false,
- });
- getLatestInputProps().onKeyDown?.({
- key: "Enter",
- preventDefault: vi.fn(),
- shiftKey: true,
- });
- });
- }
- describe("TaskFindDialog navigation", () => {
- afterEach(() => {
- capturedButtonProps.length = 0;
- capturedInputProps.length = 0;
- delete (globalThis as { document?: unknown }).document;
- delete (globalThis as { window?: unknown }).window;
- delete (globalThis as { IS_REACT_ACT_ENVIRONMENT?: unknown })
- .IS_REACT_ACT_ENVIRONMENT;
- });
- it("routes both buttons and Enter shortcuts through conversation navigate", async () => {
- const { callbacks, root } = await renderDialog();
- clearFindCallbacks(callbacks);
- triggerSixNavigationEntries();
- expect(callbacks.onConversationFindNavigate.mock.calls).toEqual([
- ["needle", 0],
- ["needle", 0],
- ["needle", 0],
- ["needle", 0],
- ["needle", 0],
- ["needle", 0],
- ]);
- expect(callbacks.onConversationFindChange).not.toHaveBeenCalled();
- expect(callbacks.onFileChangeFindChange).not.toHaveBeenCalled();
- expect(callbacks.onFileChangeFindNavigate).not.toHaveBeenCalled();
- act(() => root.unmount());
- });
- it("keeps file-change navigation isolated from conversation callbacks", async () => {
- const { callbacks, root } = await renderDialog();
- act(() => {
- getLatestButtonProps("quickPick.find.scope.changes").onClick?.();
- });
- clearFindCallbacks(callbacks);
- triggerSixNavigationEntries();
- expect(callbacks.onFileChangeFindNavigate.mock.calls).toEqual([
- ["needle", 0],
- ["needle", 0],
- ["needle", 0],
- ["needle", 0],
- ["needle", 0],
- ["needle", 0],
- ]);
- expect(callbacks.onFileChangeFindChange).not.toHaveBeenCalled();
- expect(callbacks.onConversationFindChange).not.toHaveBeenCalled();
- expect(callbacks.onConversationFindNavigate).not.toHaveBeenCalled();
- act(() => root.unmount());
- });
- it("ignores every navigation entry when there are no matches", async () => {
- const { callbacks, root } = await renderDialog({
- conversationMatchCount: 0,
- fileChangeMatchCount: 0,
- });
- clearFindCallbacks(callbacks);
- triggerSixNavigationEntries();
- expect(callbacks.onConversationFindChange).not.toHaveBeenCalled();
- expect(callbacks.onConversationFindNavigate).not.toHaveBeenCalled();
- expect(callbacks.onFileChangeFindChange).not.toHaveBeenCalled();
- expect(callbacks.onFileChangeFindNavigate).not.toHaveBeenCalled();
- act(() => root.unmount());
- });
- it("keeps find open when another active layer already handled Escape", async () => {
- const { callbacks, dispatchWindowEvent, root } = await renderDialog();
- callbacks.onOpenChange.mockClear();
- act(() => {
- dispatchWindowEvent({
- defaultPrevented: true,
- key: "Escape",
- type: "keydown",
- });
- });
- expect(callbacks.onOpenChange).not.toHaveBeenCalled();
- act(() => root.unmount());
- });
- it("closes find and consumes an unhandled Escape", async () => {
- const { callbacks, dispatchWindowEvent, root } = await renderDialog();
- callbacks.onOpenChange.mockClear();
- const event: TestEvent = {
- defaultPrevented: false,
- key: "Escape",
- type: "keydown",
- };
- act(() => {
- dispatchWindowEvent(event);
- });
- expect(event.defaultPrevented).toBe(true);
- expect(callbacks.onOpenChange).toHaveBeenCalledWith(false);
- act(() => root.unmount());
- });
- });
|