codeViewerComponent.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. // @vitest-environment jsdom
  2. import { createElement } from "react";
  3. import { renderToStaticMarkup } from "react-dom/server";
  4. import { describe, expect, it, vi } from "vitest";
  5. import { render, waitFor } from "@testing-library/react";
  6. import {
  7. CodeViewer,
  8. codeViewerMarkedLinesCss,
  9. findCodeViewerCommentElement,
  10. findCodeViewerLineElement,
  11. formatCodeCommentSubmitShortcutLabel,
  12. isCodeCommentCancelShortcut,
  13. isCodeCommentSubmitShortcut,
  14. resolveCodeViewerColorScheme,
  15. } from "../src/components/ui/code-viewer.js";
  16. vi.mock("@pierre/diffs/react", () => ({
  17. File: ({
  18. className,
  19. file,
  20. lineAnnotations,
  21. options,
  22. renderAnnotation,
  23. selectedLines,
  24. }: {
  25. className?: string;
  26. file?: { cacheKey?: string };
  27. lineAnnotations?: unknown[];
  28. options?: Record<string, unknown>;
  29. renderAnnotation?: (annotation: unknown) => unknown;
  30. selectedLines?: { start: number; end: number } | null;
  31. }) =>
  32. createElement(
  33. "diffs-container",
  34. {
  35. class: className,
  36. "data-disable-line-numbers": String(Boolean(options?.disableLineNumbers)),
  37. "data-enable-gutter-utility": String(Boolean(options?.enableGutterUtility)),
  38. "data-enable-line-selection": String(Boolean(options?.enableLineSelection)),
  39. "data-file-cache-key": String(file?.cacheKey ?? ""),
  40. "data-has-gutter-utility-click": String(
  41. typeof options?.onGutterUtilityClick === "function",
  42. ),
  43. "data-line-hover-highlight": String(options?.lineHoverHighlight),
  44. "data-selected-lines": selectedLines ? `${selectedLines.start}-${selectedLines.end}` : "",
  45. "data-overflow": String(options?.overflow),
  46. "data-theme": String(options?.theme ?? ""),
  47. "data-unsafe-css": String(options?.unsafeCSS ?? ""),
  48. },
  49. [
  50. selectedLines
  51. ? createElement("span", {
  52. key: "selected-line",
  53. "data-line": String(selectedLines.start),
  54. })
  55. : null,
  56. ...(lineAnnotations?.map((annotation, index) =>
  57. createElement("div", { key: index }, renderAnnotation?.(annotation)),
  58. ) ?? []),
  59. ],
  60. ),
  61. }));
  62. describe("CodeViewer", () => {
  63. it("formats the comment submit shortcut by platform", () => {
  64. expect(formatCodeCommentSubmitShortcutLabel({ platform: "MacIntel" })).toBe("⌘ ↵");
  65. expect(formatCodeCommentSubmitShortcutLabel({ platform: "Win32" })).toBe("Ctrl+↵");
  66. });
  67. it("submits comment drafts with the platform primary modifier and Enter", () => {
  68. expect(
  69. isCodeCommentSubmitShortcut(
  70. {
  71. key: "Enter",
  72. metaKey: true,
  73. ctrlKey: false,
  74. },
  75. { platform: "MacIntel" },
  76. ),
  77. ).toBe(true);
  78. expect(
  79. isCodeCommentSubmitShortcut(
  80. {
  81. key: "Enter",
  82. metaKey: false,
  83. ctrlKey: true,
  84. },
  85. { platform: "MacIntel" },
  86. ),
  87. ).toBe(false);
  88. expect(
  89. isCodeCommentSubmitShortcut(
  90. {
  91. key: "Enter",
  92. metaKey: false,
  93. ctrlKey: true,
  94. },
  95. { platform: "Win32" },
  96. ),
  97. ).toBe(true);
  98. expect(
  99. isCodeCommentSubmitShortcut(
  100. {
  101. key: "Enter",
  102. metaKey: false,
  103. ctrlKey: false,
  104. },
  105. { platform: "Win32" },
  106. ),
  107. ).toBe(false);
  108. expect(
  109. isCodeCommentSubmitShortcut(
  110. {
  111. key: "a",
  112. metaKey: true,
  113. ctrlKey: false,
  114. },
  115. { platform: "MacIntel" },
  116. ),
  117. ).toBe(false);
  118. });
  119. it("cancels comment drafts with Escape", () => {
  120. expect(isCodeCommentCancelShortcut({ key: "Escape" })).toBe(true);
  121. expect(isCodeCommentCancelShortcut({ key: "Enter" })).toBe(false);
  122. });
  123. it("pins dark code preview themes to dark color-scheme", () => {
  124. expect(resolveCodeViewerColorScheme("github-dark")).toBe("dark");
  125. expect(resolveCodeViewerColorScheme("vitesse-dark")).toBe("dark");
  126. expect(resolveCodeViewerColorScheme("min-dark")).toBe("dark");
  127. expect(resolveCodeViewerColorScheme("github-dark-high-contrast")).toBe("dark");
  128. expect(resolveCodeViewerColorScheme("catppuccin-mocha")).toBe("dark");
  129. expect(resolveCodeViewerColorScheme("github-light")).toBe("light");
  130. expect(resolveCodeViewerColorScheme("vitesse-light")).toBe("light");
  131. expect(resolveCodeViewerColorScheme("min-light")).toBe("light");
  132. expect(resolveCodeViewerColorScheme("github-light-high-contrast")).toBe("light");
  133. expect(resolveCodeViewerColorScheme("catppuccin-latte")).toBe("light");
  134. const html = renderToStaticMarkup(
  135. createElement(CodeViewer, {
  136. code: "AI 需要写文件 -> requestPermission",
  137. language: "text",
  138. theme: "github-dark",
  139. }),
  140. );
  141. expect(html).toContain("color-scheme:dark");
  142. });
  143. it("includes the highlight theme in the diff file cache key", () => {
  144. const lightHtml = renderToStaticMarkup(
  145. createElement(CodeViewer, {
  146. code: "const value = 1;",
  147. language: "typescript",
  148. theme: "github-light",
  149. }),
  150. );
  151. const darkHtml = renderToStaticMarkup(
  152. createElement(CodeViewer, {
  153. code: "const value = 1;",
  154. language: "typescript",
  155. theme: "github-dark",
  156. }),
  157. );
  158. expect(lightHtml).toContain('data-theme="github-light"');
  159. expect(lightHtml).toContain('data-file-cache-key="github-light:preview.typescript:typescript:');
  160. expect(darkHtml).toContain('data-theme="github-dark"');
  161. expect(darkHtml).toContain('data-file-cache-key="github-dark:preview.typescript:typescript:');
  162. });
  163. it("passes preview sizing through CSS variables", () => {
  164. const html = renderToStaticMarkup(
  165. createElement(CodeViewer, {
  166. code: "function demo() {\n return true;\n}",
  167. language: "typescript",
  168. showLineNumbers: true,
  169. wrapLongLines: false,
  170. fontSizePx: 13,
  171. }),
  172. );
  173. expect(html).toContain("<diffs-container");
  174. expect(html).toContain("--diffs-font-size:13px");
  175. // @pierre/diffs 在客户端 Shadow DOM 内渲染真实 code 行;SSR 只输出宿主节点。
  176. expect(html).not.toContain(" return true;");
  177. });
  178. it("renders controlled code comments", () => {
  179. const html = renderToStaticMarkup(
  180. createElement(CodeViewer, {
  181. code: "const value = 1;\nconsole.log(value);",
  182. language: "typescript",
  183. comments: [
  184. {
  185. id: "comment-1",
  186. sourceTitle: "app.ts",
  187. startLine: 2,
  188. endLine: 2,
  189. selectedText: "console.log(value);",
  190. comment: "Check this line.",
  191. },
  192. ],
  193. labels: {
  194. deleteComment: "Remove comment",
  195. commentLine: "Line {line}",
  196. },
  197. onDeleteCodeComment: () => undefined,
  198. }),
  199. );
  200. expect(html).toContain("Check this line.");
  201. expect(html).toContain("Line 2");
  202. expect(html).toContain("Remove comment");
  203. });
  204. it("renders a model review with the existing comment annotation but no mutation controls", () => {
  205. const html = renderToStaticMarkup(
  206. createElement(CodeViewer, {
  207. code: "const value = 1;\nconsole.log(value);\nexport {};",
  208. language: "typescript",
  209. comments: [
  210. {
  211. id: "model-review-1",
  212. sourceTitle: "app.ts",
  213. startLine: 2,
  214. endLine: 3,
  215. selectedText: "",
  216. comment: "Model-only review.",
  217. },
  218. ],
  219. focusedRange: { startLine: 2, endLine: 3 },
  220. labels: {
  221. deleteComment: "Remove comment",
  222. commentRange: "Lines {startLine}-{endLine}",
  223. },
  224. }),
  225. );
  226. expect(html).toContain("Model-only review.");
  227. expect(html).toContain("Lines 2-3");
  228. expect(html).toContain('data-selected-lines="2-3"');
  229. expect(html).not.toContain("Remove comment");
  230. expect(html).not.toContain("data-code-viewer-add-comment");
  231. });
  232. it("finds a target line inside nested code viewer Shadow DOM", () => {
  233. const root = document.createElement("div");
  234. const host = document.createElement("diffs-container");
  235. const shadowRoot = host.attachShadow({ mode: "open" });
  236. const nestedHost = document.createElement("div");
  237. const nestedShadowRoot = nestedHost.attachShadow({ mode: "open" });
  238. const line = document.createElement("span");
  239. line.setAttribute("data-line", "42");
  240. nestedShadowRoot.append(line);
  241. shadowRoot.append(nestedHost);
  242. root.append(host);
  243. expect(findCodeViewerLineElement(root, 42)).toBe(line);
  244. expect(findCodeViewerLineElement(root, 43)).toBeNull();
  245. });
  246. it("finds a review comment inside nested code viewer Shadow DOM", () => {
  247. const root = document.createElement("div");
  248. const host = document.createElement("diffs-container");
  249. const shadowRoot = host.attachShadow({ mode: "open" });
  250. const comment = document.createElement("div");
  251. comment.dataset.codeCommentId = "review-42";
  252. shadowRoot.append(comment);
  253. root.append(host);
  254. expect(findCodeViewerCommentElement(root, "review-42")).toBe(comment);
  255. expect(findCodeViewerCommentElement(root, "review-43")).toBeNull();
  256. });
  257. it("positions the review comment below the target without changing horizontal scroll", async () => {
  258. const view = render(
  259. createElement(CodeViewer, {
  260. code: "line 1\nline 2\nline 3",
  261. language: "typescript",
  262. comments: [
  263. {
  264. id: "review-scroll-1",
  265. sourceTitle: "app.ts",
  266. startLine: 2,
  267. endLine: 2,
  268. selectedText: "",
  269. comment: "Review text.",
  270. },
  271. ],
  272. focusedRange: { startLine: 2, endLine: 2 },
  273. focusRequestId: "review-scroll-1",
  274. }),
  275. );
  276. const container = view.container.querySelector<HTMLDivElement>("[data-language]");
  277. if (!container) {
  278. throw new Error("Code viewer scroll container was not rendered");
  279. }
  280. Object.defineProperties(container, {
  281. clientHeight: { configurable: true, value: 600 },
  282. scrollLeft: { configurable: true, writable: true, value: 45 },
  283. scrollTop: { configurable: true, writable: true, value: 100 },
  284. });
  285. const geometrySpy = vi
  286. .spyOn(HTMLElement.prototype, "getBoundingClientRect")
  287. .mockImplementation(function () {
  288. if (this.dataset.codeCommentId === "review-scroll-1") {
  289. return {
  290. bottom: 560,
  291. height: 60,
  292. left: 20,
  293. right: 700,
  294. top: 500,
  295. width: 680,
  296. x: 20,
  297. y: 500,
  298. toJSON: () => ({}),
  299. };
  300. }
  301. return {
  302. bottom: 600,
  303. height: 600,
  304. left: 0,
  305. right: 700,
  306. top: 0,
  307. width: 700,
  308. x: 0,
  309. y: 0,
  310. toJSON: () => ({}),
  311. };
  312. });
  313. await waitFor(() => {
  314. expect(container.scrollTop).toBe(72);
  315. });
  316. expect(container.scrollLeft).toBe(45);
  317. geometrySpy.mockRestore();
  318. view.unmount();
  319. });
  320. it("tints only the gutter numbers of marked lines, through the shadow-root CSS", () => {
  321. const html = renderToStaticMarkup(
  322. createElement(CodeViewer, {
  323. code: "a\nb\nc",
  324. language: "typescript",
  325. markedLines: [3, 1, 3],
  326. }),
  327. );
  328. // 静态标记里属性值的引号被转义。
  329. expect(html).toContain(
  330. "[data-column-number=&quot;3&quot;],[data-column-number=&quot;1&quot;]{color:var(--color-warning);}",
  331. );
  332. const plain = renderToStaticMarkup(
  333. createElement(CodeViewer, { code: "a", language: "typescript" }),
  334. );
  335. expect(plain).not.toContain("data-column-number");
  336. });
  337. it("drops non-positive and non-integer marked lines", () => {
  338. expect(codeViewerMarkedLinesCss([0, -2, 1.5])).toBe("");
  339. expect(codeViewerMarkedLinesCss(undefined)).toBe("");
  340. expect(codeViewerMarkedLinesCss([7])).toBe(
  341. '[data-column-number="7"]{color:var(--color-warning);}',
  342. );
  343. });
  344. it("keeps code blocks read-only when comment controls are disabled", () => {
  345. const html = renderToStaticMarkup(
  346. createElement(CodeViewer, {
  347. code: "const value = 1;",
  348. language: "typescript",
  349. onSubmitCodeComment: () => undefined,
  350. }),
  351. );
  352. expect(html).not.toContain("Add comment");
  353. expect(html).not.toContain("data-code-viewer-add-comment");
  354. });
  355. it("enables @pierre/diffs gutter selection when gutter utility is explicitly enabled", () => {
  356. const html = renderToStaticMarkup(
  357. createElement(CodeViewer, {
  358. code: "const value = 1;",
  359. language: "typescript",
  360. enableLineSelection: true,
  361. enableGutterUtility: true,
  362. onSubmitCodeComment: () => undefined,
  363. }),
  364. );
  365. expect(html).toContain('data-enable-line-selection="true"');
  366. expect(html).toContain('data-enable-gutter-utility="true"');
  367. expect(html).toContain('data-has-gutter-utility-click="true"');
  368. });
  369. it("localizes the gutter comment tooltip label", () => {
  370. const html = renderToStaticMarkup(
  371. createElement(CodeViewer, {
  372. code: "const value = 1;",
  373. language: "typescript",
  374. enableLineSelection: true,
  375. enableGutterUtility: true,
  376. labels: {
  377. addCommentTooltip: "点击或拖拽添加评论",
  378. },
  379. onSubmitCodeComment: () => undefined,
  380. }),
  381. );
  382. expect(html).toContain("--code-comment-add-tooltip:&quot;点击或拖拽添加评论&quot;");
  383. });
  384. it("does not render comment creation UI without a submit handler", () => {
  385. const html = renderToStaticMarkup(
  386. createElement(CodeViewer, {
  387. code: "const value = 1;",
  388. language: "typescript",
  389. enableLineSelection: true,
  390. enableGutterUtility: true,
  391. }),
  392. );
  393. expect(html).toContain('data-enable-line-selection="false"');
  394. expect(html).toContain('data-enable-gutter-utility="false"');
  395. expect(html).toContain('data-has-gutter-utility-click="false"');
  396. });
  397. });