markdownPreviewSelection.test.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. import {
  2. buildSelectionSideChatKey,
  3. registerSelectionSideChatOpener,
  4. } from "@/lib/selectionSideChatRuntime.js";
  5. // @vitest-environment jsdom
  6. import { createElement } from "react";
  7. import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
  8. import { afterEach, describe, expect, it, vi } from "vitest";
  9. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  10. import { MarkdownPreviewContent } from "@/previewPaneMarkdownContent.js";
  11. import {
  12. appendConversationSelectionReference,
  13. buildPromptWithConversationSelections,
  14. getConversationSelectionReferenceScope,
  15. setConversationSelectionReferenceScope,
  16. type ConversationSelectionReference,
  17. } from "@/lib/conversationSelectionReference.js";
  18. vi.mock("@/components/ai-elements/message.js", () => ({
  19. MessageResponse: ({ children }: { children: string }) => createElement("p", null, children),
  20. }));
  21. const target = { sessionId: null, workspaceKey: "ssh:first:/workspace" };
  22. const reference: ConversationSelectionReference = {
  23. id: "md-1",
  24. contentType: "markdown",
  25. sourceKey: "/workspace/a.md",
  26. sourceTitle: "a.md",
  27. path: "/workspace/a.md",
  28. text: "Selected paragraph",
  29. };
  30. function preview(content = "Selected paragraph", sessionId: string | null = null) {
  31. return createElement(
  32. ZCodeIntlProvider,
  33. { initialLocale: "en-US" },
  34. createElement(MarkdownPreviewContent, {
  35. content,
  36. sourceKey: "/workspace/a.md",
  37. sourceTitle: "a.md",
  38. sourcePath: "/workspace/a.md",
  39. selectionTarget: { ...target, sessionId },
  40. }),
  41. );
  42. }
  43. async function selectText(event = "mouseup") {
  44. const text = screen.getByText("Selected paragraph").firstChild!;
  45. const range = document.createRange();
  46. range.selectNodeContents(text);
  47. range.getBoundingClientRect = () =>
  48. ({ left: 100, top: 120, bottom: 140, width: 100, height: 20 }) as DOMRect;
  49. const selection = window.getSelection()!;
  50. selection.removeAllRanges();
  51. selection.addRange(range);
  52. await act(async () => {
  53. if (event === "selectionchange") document.dispatchEvent(new Event(event));
  54. else text.parentElement!.dispatchEvent(new MouseEvent(event, { bubbles: true }));
  55. });
  56. return screen.findByRole("button", { name: "Add to chat" });
  57. }
  58. afterEach(() => {
  59. cleanup();
  60. vi.restoreAllMocks();
  61. vi.unstubAllGlobals();
  62. window.getSelection()?.removeAllRanges();
  63. setConversationSelectionReferenceScope(null, target.workspaceKey, []);
  64. });
  65. describe("Markdown preview selections", () => {
  66. it("区分 Markdown 来源,去重并发送路径与选中文字", () => {
  67. expect(
  68. appendConversationSelectionReference([reference], { ...reference, id: "md-2" }),
  69. ).toMatchObject({ duplicate: true });
  70. expect(
  71. appendConversationSelectionReference([reference], {
  72. ...reference,
  73. sourceKey: "/workspace/b.md",
  74. }),
  75. ).toMatchObject({ duplicate: false });
  76. expect(buildPromptWithConversationSelections("Explain", [reference])).toContain(
  77. JSON.stringify([{ path: "/workspace/a.md", text: reference.text }]),
  78. );
  79. expect(buildPromptWithConversationSelections("Explain", [reference])).not.toContain(
  80. "sourceKey",
  81. );
  82. expect(
  83. appendConversationSelectionReference([reference], { ...reference, text: "x".repeat(8001) }),
  84. ).toEqual({ ok: false, reason: "single" });
  85. });
  86. it("触控选区添加到明确的远程草稿 scope,不串同路径 workspace", async () => {
  87. render(preview());
  88. fireEvent.click(await selectText("selectionchange"));
  89. expect(getConversationSelectionReferenceScope(null, target.workspaceKey)).toMatchObject([
  90. { text: reference.text, contentType: "markdown", path: "/workspace/a.md" },
  91. ]);
  92. expect(getConversationSelectionReferenceScope(null, "ssh:second:/workspace")).toEqual([]);
  93. expect(getConversationSelectionReferenceScope("other-task", target.workspaceKey)).toEqual([]);
  94. });
  95. it("Escape、滚动、内容与目标切换清除旧浮层", async () => {
  96. const view = render(preview());
  97. await selectText();
  98. fireEvent.keyUp(document, { key: "Escape" });
  99. expect(screen.queryByRole("button", { name: "Add to chat" })).toBeNull();
  100. await selectText();
  101. fireEvent.scroll(view.container.querySelector("[data-markdown-preview]")!);
  102. expect(screen.queryByRole("button", { name: "Add to chat" })).toBeNull();
  103. await selectText();
  104. view.rerender(preview("Changed"));
  105. await waitFor(() => expect(screen.queryByRole("button", { name: "Add to chat" })).toBeNull());
  106. view.rerender(preview());
  107. await selectText();
  108. view.rerender(preview("Selected paragraph", "task-b"));
  109. await waitFor(() => expect(screen.queryByRole("button", { name: "Add to chat" })).toBeNull());
  110. });
  111. it("窄屏浮层留在视口内,空白和跨预览选区不提供入口", async () => {
  112. vi.stubGlobal("innerWidth", 180);
  113. const view = render(preview());
  114. await selectText();
  115. const popup = document.querySelector<HTMLElement>("[data-conversation-selection-tooltip]")!;
  116. expect(Number.parseFloat(popup.style.left)).toBeGreaterThanOrEqual(12);
  117. expect(Number.parseFloat(popup.style.maxWidth)).toBe(156);
  118. expect(popup.style.width).toBe("max-content");
  119. const outside = document.createElement("p");
  120. outside.textContent = "Outside";
  121. document.body.append(outside);
  122. const range = document.createRange();
  123. range.setStart(screen.getByText("Selected paragraph").firstChild!, 0);
  124. range.setEnd(outside.firstChild!, 3);
  125. const selection = window.getSelection()!;
  126. selection.removeAllRanges();
  127. selection.addRange(range);
  128. fireEvent.mouseUp(view.container.querySelector("[data-markdown-preview]")!);
  129. await waitFor(() => expect(screen.queryByRole("button", { name: "Add to chat" })).toBeNull());
  130. outside.remove();
  131. view.rerender(preview(" "));
  132. const blank = view.container.querySelector("p")!.firstChild!;
  133. range.selectNodeContents(blank);
  134. selection.removeAllRanges();
  135. selection.addRange(range);
  136. fireEvent.mouseUp(blank.parentElement!);
  137. await act(async () => {
  138. await new Promise((resolve) => requestAnimationFrame(resolve));
  139. });
  140. expect(screen.queryByRole("button", { name: "Add to chat" })).toBeNull();
  141. });
  142. it("辅助动作传递 Markdown 引用,主草稿引用不变;未就绪时禁用", async () => {
  143. const view = render(preview());
  144. await selectText();
  145. expect(
  146. (screen.getByRole("button", { name: "Add in side chat" }) as HTMLButtonElement).disabled,
  147. ).toBe(true);
  148. const open = vi.fn(async () => {});
  149. const unregister = registerSelectionSideChatOpener(
  150. buildSelectionSideChatKey(target.workspaceKey, "parent"),
  151. open,
  152. true,
  153. );
  154. try {
  155. view.rerender(preview("Selected paragraph", "parent"));
  156. await selectText();
  157. fireEvent.click(screen.getByRole("button", { name: "Add in side chat" }));
  158. expect(open).toHaveBeenCalledWith(
  159. expect.objectContaining({ contentType: "markdown", text: reference.text }),
  160. );
  161. expect(getConversationSelectionReferenceScope("parent", target.workspaceKey)).toEqual([]);
  162. } finally {
  163. unregister();
  164. }
  165. });
  166. });