taskFindDialogNavigation.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. import { act, createElement, type ReactNode } from "react";
  2. import { createRoot, type Root } from "react-dom/client";
  3. import { afterEach, describe, expect, it, vi } from "vitest";
  4. type CapturedButtonProps = {
  5. "aria-label"?: string;
  6. onClick?: () => void;
  7. };
  8. type CapturedInputProps = {
  9. onChange?: (event: { target: { value: string } }) => void;
  10. onKeyDown?: (event: {
  11. key: string;
  12. preventDefault: () => void;
  13. shiftKey: boolean;
  14. }) => void;
  15. };
  16. const { capturedButtonProps, capturedInputProps } = vi.hoisted(() => ({
  17. capturedButtonProps: [] as CapturedButtonProps[],
  18. capturedInputProps: [] as CapturedInputProps[],
  19. }));
  20. type TestEvent = {
  21. bubbles?: boolean;
  22. button?: number;
  23. currentTarget?: TestElement;
  24. defaultPrevented?: boolean;
  25. key?: string;
  26. preventDefault?: () => void;
  27. shiftKey?: boolean;
  28. stopPropagation?: () => void;
  29. target?: TestElement;
  30. type: string;
  31. };
  32. type TestEventHandler = (event: TestEvent) => void;
  33. type TestNode = TestElement | {
  34. nodeType: 3;
  35. nodeValue: string;
  36. ownerDocument: Document;
  37. parentNode: TestElement | null;
  38. };
  39. type TestElement = Element & {
  40. __attrs: Map<string, string>;
  41. __listeners: Map<string, TestEventHandler[]>;
  42. childNodes: TestNode[];
  43. dispatchEvent: (event: TestEvent) => boolean;
  44. focus: () => void;
  45. parentNode: TestElement | null;
  46. value: string;
  47. };
  48. vi.mock("lucide-react", () => {
  49. const createIcon = (name: string) => (props: Record<string, unknown>) =>
  50. createElement("svg", { "data-icon": name, ...props });
  51. return {
  52. ArrowDownIcon: createIcon("arrow-down"),
  53. ArrowUpIcon: createIcon("arrow-up"),
  54. FileDiffIcon: createIcon("file-diff"),
  55. MessageCircleIcon: createIcon("message-circle"),
  56. SearchIcon: createIcon("search"),
  57. XIcon: createIcon("x"),
  58. };
  59. });
  60. vi.mock("react/jsx-runtime", async () => {
  61. const actual = await vi.importActual<typeof import("react/jsx-runtime")>(
  62. "react/jsx-runtime",
  63. );
  64. const capture =
  65. (factory: typeof actual.jsx) =>
  66. (type: Parameters<typeof actual.jsx>[0], props: Record<string, unknown>, key?: string) => {
  67. if (type === "input") {
  68. capturedInputProps.push(props as CapturedInputProps);
  69. }
  70. return factory(type, props, key);
  71. };
  72. return {
  73. ...actual,
  74. jsx: capture(actual.jsx),
  75. jsxs: capture(actual.jsxs),
  76. };
  77. });
  78. vi.mock("react/jsx-dev-runtime", async () => {
  79. const actual = await vi.importActual<typeof import("react/jsx-dev-runtime")>(
  80. "react/jsx-dev-runtime",
  81. );
  82. return {
  83. ...actual,
  84. jsxDEV: (
  85. type: Parameters<typeof actual.jsxDEV>[0],
  86. props: Record<string, unknown>,
  87. ...rest: unknown[]
  88. ) => {
  89. if (type === "input") {
  90. capturedInputProps.push(props as CapturedInputProps);
  91. }
  92. return actual.jsxDEV(type, props, ...rest);
  93. },
  94. };
  95. });
  96. vi.mock("@/components/ui/button.js", () => ({
  97. Button: ({ children, ...props }: { children?: ReactNode } & CapturedButtonProps) => {
  98. capturedButtonProps.push(props);
  99. return createElement("button", props, children);
  100. },
  101. }));
  102. vi.mock("@/ControlHintTooltip.js", () => ({
  103. ControlHintTooltip: ({ children }: { children?: ReactNode }) => children,
  104. }));
  105. vi.mock("@/i18n/IntlProvider.js", () => ({
  106. useZCodeIntl: () => ({
  107. intl: {
  108. formatMessage: ({ id }: { id: string }) => id,
  109. },
  110. }),
  111. }));
  112. function createMinimalElement(ownerDocument: Document, tagName = "div") {
  113. const element = {
  114. __attrs: new Map<string, string>(),
  115. __listeners: new Map<string, TestEventHandler[]>(),
  116. addEventListener: (type: string, handler: TestEventHandler) => {
  117. const handlers = element.__listeners.get(type) ?? [];
  118. handlers.push(handler);
  119. element.__listeners.set(type, handlers);
  120. },
  121. appendChild: (child: TestNode) => {
  122. child.parentNode = element as unknown as TestElement;
  123. element.childNodes.push(child);
  124. return child;
  125. },
  126. childNodes: [] as TestNode[],
  127. dispatchEvent: (event: TestEvent) => {
  128. event.target ??= element as unknown as TestElement;
  129. event.preventDefault ??= () => {
  130. event.defaultPrevented = true;
  131. };
  132. event.stopPropagation ??= () => {};
  133. let current: TestElement | null = element as unknown as TestElement;
  134. while (current) {
  135. event.currentTarget = current;
  136. for (const handler of current.__listeners.get(event.type) ?? []) {
  137. handler(event);
  138. }
  139. if (!event.bubbles) {
  140. break;
  141. }
  142. current = current.parentNode;
  143. }
  144. return !event.defaultPrevented;
  145. },
  146. focus: () => {},
  147. getAttribute: (name: string) => element.__attrs.get(name) ?? null,
  148. insertBefore: (child: TestNode, beforeChild?: TestNode | null) => {
  149. child.parentNode = element as unknown as TestElement;
  150. const beforeIndex = beforeChild
  151. ? element.childNodes.indexOf(beforeChild)
  152. : -1;
  153. if (beforeIndex >= 0) {
  154. element.childNodes.splice(beforeIndex, 0, child);
  155. } else {
  156. element.childNodes.push(child);
  157. }
  158. return child;
  159. },
  160. nodeName: tagName.toUpperCase(),
  161. nodeType: 1,
  162. ownerDocument,
  163. parentNode: null as TestElement | null,
  164. removeAttribute: (name: string) => {
  165. element.__attrs.delete(name);
  166. },
  167. removeChild: (child: TestNode) => {
  168. element.childNodes = element.childNodes.filter((item) => item !== child);
  169. child.parentNode = null;
  170. return child;
  171. },
  172. removeEventListener: (type: string, handler: TestEventHandler) => {
  173. element.__listeners.set(
  174. type,
  175. (element.__listeners.get(type) ?? []).filter((item) => item !== handler),
  176. );
  177. },
  178. setAttribute: (name: string, value: string) => {
  179. element.__attrs.set(name, String(value));
  180. },
  181. style: {},
  182. tagName: tagName.toUpperCase(),
  183. value: "",
  184. };
  185. return element as unknown as TestElement;
  186. }
  187. function installMinimalDom() {
  188. const windowListeners = new Map<string, TestEventHandler[]>();
  189. const documentMock = {
  190. addEventListener: () => {},
  191. createElement: (tagName: string) =>
  192. createMinimalElement(documentMock as unknown as Document, tagName),
  193. createElementNS: (_namespace: string, tagName: string) =>
  194. createMinimalElement(documentMock as unknown as Document, tagName),
  195. createTextNode: (nodeValue: string) => ({
  196. nodeType: 3 as const,
  197. nodeValue,
  198. ownerDocument: documentMock as unknown as Document,
  199. parentNode: null,
  200. }),
  201. nodeType: 9,
  202. removeEventListener: () => {},
  203. } as unknown as Document;
  204. const windowMock = {
  205. addEventListener: (type: string, handler: TestEventHandler) => {
  206. const handlers = windowListeners.get(type) ?? [];
  207. handlers.push(handler);
  208. windowListeners.set(type, handlers);
  209. },
  210. cancelAnimationFrame: () => {},
  211. document: documentMock,
  212. HTMLIFrameElement: function HTMLIFrameElement() {},
  213. HTMLElement: function HTMLElement() {},
  214. Node: function Node() {},
  215. removeEventListener: (type: string, handler: TestEventHandler) => {
  216. windowListeners.set(
  217. type,
  218. (windowListeners.get(type) ?? []).filter((item) => item !== handler),
  219. );
  220. },
  221. requestAnimationFrame: (callback: FrameRequestCallback) => {
  222. callback(0);
  223. return 1;
  224. },
  225. };
  226. Object.defineProperty(globalThis, "document", {
  227. configurable: true,
  228. value: documentMock,
  229. });
  230. Object.defineProperty(globalThis, "window", {
  231. configurable: true,
  232. value: windowMock,
  233. });
  234. Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", {
  235. configurable: true,
  236. value: true,
  237. });
  238. return {
  239. container: createMinimalElement(documentMock),
  240. dispatchWindowEvent: (event: TestEvent) => {
  241. event.preventDefault ??= () => {
  242. event.defaultPrevented = true;
  243. };
  244. for (const handler of windowListeners.get(event.type) ?? []) {
  245. handler(event);
  246. }
  247. return !event.defaultPrevented;
  248. },
  249. };
  250. }
  251. function getLatestInputProps() {
  252. const props = capturedInputProps.at(-1);
  253. expect(props).toBeDefined();
  254. return props!;
  255. }
  256. function getLatestButtonProps(label: string) {
  257. for (let index = capturedButtonProps.length - 1; index >= 0; index -= 1) {
  258. if (capturedButtonProps[index]?.["aria-label"] === label) {
  259. return capturedButtonProps[index]!;
  260. }
  261. }
  262. throw new Error(`没有找到按钮: ${label}`);
  263. }
  264. async function renderDialog({
  265. conversationMatchCount = 1,
  266. fileChangeMatchCount = 1,
  267. }: {
  268. conversationMatchCount?: number;
  269. fileChangeMatchCount?: number;
  270. } = {}) {
  271. const { TaskFindDialog } = await import("@/quickpick/TaskFindDialog.js");
  272. const { container, dispatchWindowEvent } = installMinimalDom();
  273. const root: Root = createRoot(container);
  274. const callbacks = {
  275. onConversationFindChange: vi.fn(),
  276. onConversationFindNavigate: vi.fn(),
  277. onFileChangeFindChange: vi.fn(),
  278. onFileChangeFindNavigate: vi.fn(),
  279. onOpenChange: vi.fn(),
  280. onOpenFileChanges: vi.fn(),
  281. };
  282. act(() => {
  283. root.render(
  284. createElement(TaskFindDialog, {
  285. open: true,
  286. placement: "chat",
  287. focusRequestId: 0,
  288. conversationMatchCount,
  289. conversationMatchIndex: 0,
  290. fileChangeMatchCount,
  291. fileChangeMatchIndex: 0,
  292. ...callbacks,
  293. }),
  294. );
  295. });
  296. act(() => {
  297. getLatestInputProps().onChange?.({ target: { value: "needle" } });
  298. });
  299. return { callbacks, dispatchWindowEvent, root };
  300. }
  301. function clearFindCallbacks(callbacks: Awaited<ReturnType<typeof renderDialog>>["callbacks"]) {
  302. callbacks.onConversationFindChange.mockClear();
  303. callbacks.onConversationFindNavigate.mockClear();
  304. callbacks.onFileChangeFindChange.mockClear();
  305. callbacks.onFileChangeFindNavigate.mockClear();
  306. }
  307. function triggerSixNavigationEntries() {
  308. act(() => {
  309. getLatestButtonProps("quickPick.find.previous").onClick?.();
  310. getLatestButtonProps("quickPick.find.next").onClick?.();
  311. getLatestInputProps().onKeyDown?.({
  312. key: "ArrowUp",
  313. preventDefault: vi.fn(),
  314. shiftKey: false,
  315. });
  316. getLatestInputProps().onKeyDown?.({
  317. key: "ArrowDown",
  318. preventDefault: vi.fn(),
  319. shiftKey: false,
  320. });
  321. getLatestInputProps().onKeyDown?.({
  322. key: "Enter",
  323. preventDefault: vi.fn(),
  324. shiftKey: false,
  325. });
  326. getLatestInputProps().onKeyDown?.({
  327. key: "Enter",
  328. preventDefault: vi.fn(),
  329. shiftKey: true,
  330. });
  331. });
  332. }
  333. describe("TaskFindDialog navigation", () => {
  334. afterEach(() => {
  335. capturedButtonProps.length = 0;
  336. capturedInputProps.length = 0;
  337. delete (globalThis as { document?: unknown }).document;
  338. delete (globalThis as { window?: unknown }).window;
  339. delete (globalThis as { IS_REACT_ACT_ENVIRONMENT?: unknown })
  340. .IS_REACT_ACT_ENVIRONMENT;
  341. });
  342. it("routes both buttons and Enter shortcuts through conversation navigate", async () => {
  343. const { callbacks, root } = await renderDialog();
  344. clearFindCallbacks(callbacks);
  345. triggerSixNavigationEntries();
  346. expect(callbacks.onConversationFindNavigate.mock.calls).toEqual([
  347. ["needle", 0],
  348. ["needle", 0],
  349. ["needle", 0],
  350. ["needle", 0],
  351. ["needle", 0],
  352. ["needle", 0],
  353. ]);
  354. expect(callbacks.onConversationFindChange).not.toHaveBeenCalled();
  355. expect(callbacks.onFileChangeFindChange).not.toHaveBeenCalled();
  356. expect(callbacks.onFileChangeFindNavigate).not.toHaveBeenCalled();
  357. act(() => root.unmount());
  358. });
  359. it("keeps file-change navigation isolated from conversation callbacks", async () => {
  360. const { callbacks, root } = await renderDialog();
  361. act(() => {
  362. getLatestButtonProps("quickPick.find.scope.changes").onClick?.();
  363. });
  364. clearFindCallbacks(callbacks);
  365. triggerSixNavigationEntries();
  366. expect(callbacks.onFileChangeFindNavigate.mock.calls).toEqual([
  367. ["needle", 0],
  368. ["needle", 0],
  369. ["needle", 0],
  370. ["needle", 0],
  371. ["needle", 0],
  372. ["needle", 0],
  373. ]);
  374. expect(callbacks.onFileChangeFindChange).not.toHaveBeenCalled();
  375. expect(callbacks.onConversationFindChange).not.toHaveBeenCalled();
  376. expect(callbacks.onConversationFindNavigate).not.toHaveBeenCalled();
  377. act(() => root.unmount());
  378. });
  379. it("ignores every navigation entry when there are no matches", async () => {
  380. const { callbacks, root } = await renderDialog({
  381. conversationMatchCount: 0,
  382. fileChangeMatchCount: 0,
  383. });
  384. clearFindCallbacks(callbacks);
  385. triggerSixNavigationEntries();
  386. expect(callbacks.onConversationFindChange).not.toHaveBeenCalled();
  387. expect(callbacks.onConversationFindNavigate).not.toHaveBeenCalled();
  388. expect(callbacks.onFileChangeFindChange).not.toHaveBeenCalled();
  389. expect(callbacks.onFileChangeFindNavigate).not.toHaveBeenCalled();
  390. act(() => root.unmount());
  391. });
  392. it("keeps find open when another active layer already handled Escape", async () => {
  393. const { callbacks, dispatchWindowEvent, root } = await renderDialog();
  394. callbacks.onOpenChange.mockClear();
  395. act(() => {
  396. dispatchWindowEvent({
  397. defaultPrevented: true,
  398. key: "Escape",
  399. type: "keydown",
  400. });
  401. });
  402. expect(callbacks.onOpenChange).not.toHaveBeenCalled();
  403. act(() => root.unmount());
  404. });
  405. it("closes find and consumes an unhandled Escape", async () => {
  406. const { callbacks, dispatchWindowEvent, root } = await renderDialog();
  407. callbacks.onOpenChange.mockClear();
  408. const event: TestEvent = {
  409. defaultPrevented: false,
  410. key: "Escape",
  411. type: "keydown",
  412. };
  413. act(() => {
  414. dispatchWindowEvent(event);
  415. });
  416. expect(event.defaultPrevented).toBe(true);
  417. expect(callbacks.onOpenChange).toHaveBeenCalledWith(false);
  418. act(() => root.unmount());
  419. });
  420. });