codeViewerComponent.test.ts 16 KB

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