workflowArtifactPresetsRender.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. // @vitest-environment jsdom
  2. import { cleanup, render, screen, waitFor } from "@testing-library/react";
  3. import { createElement } from "react";
  4. import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
  5. import {
  6. applyArtifactItems,
  7. type ArtifactItem,
  8. } from "@/app-shell/workflow-artifacts/presets/apply.js";
  9. import { chartPlotPropsEqual } from "@/app-shell/workflow-artifacts/presets/ArtifactChartView.js";
  10. import {
  11. ArtifactBoard,
  12. ArtifactChart,
  13. ArtifactMetrics,
  14. ArtifactTable,
  15. parseArtifactPresetSpec,
  16. type BoardSpec,
  17. type ChartSpec,
  18. type MetricsSpec,
  19. type PresetLabels,
  20. type TableSpec,
  21. } from "@/app-shell/workflow-artifacts/presets/index.js";
  22. /**
  23. * 四个预置渲染器的冒烟:compact(run 侧板卡片里的小尺寸)与全尺寸两种形态各渲染一次
  24. * (docs/dynamic-workflow/authoring.md「Declaring a dashboard」)。
  25. *
  26. * 这里不断样式细节,只钉住形态契约:小卡露什么、全尺寸露什么、零条目时给空态,
  27. * 以及图表**不是**静态 import 进来的(recharts 必须可懒加载,见 Electron Linux 启动雷)。
  28. */
  29. const labels: PresetLabels = {
  30. otherColumn: "其他",
  31. empty: "暂无数据",
  32. itemsCount: (count) => `${count} 条`,
  33. };
  34. function items(...raw: unknown[]): ArtifactItem[] {
  35. return raw.map((item, index) => ({
  36. sequence: index + 1,
  37. siteId: "report#1",
  38. ordinal: index + 1,
  39. item,
  40. }));
  41. }
  42. let restoreRect: (() => void) | undefined;
  43. beforeAll(() => {
  44. // recharts 的 ResponsiveContainer 需要 ResizeObserver,且会在 effect 里读一次
  45. // `getBoundingClientRect()`——jsdom 无布局,两者都得补,否则它测出 0×0 就整块不渲染
  46. // (initialDimension 会被这次测量覆盖掉)。
  47. (globalThis as { ResizeObserver?: unknown }).ResizeObserver ??= class {
  48. observe() {}
  49. unobserve() {}
  50. disconnect() {}
  51. };
  52. const original = Element.prototype.getBoundingClientRect;
  53. Element.prototype.getBoundingClientRect = function stubbedRect(this: Element): DOMRect {
  54. return {
  55. bottom: 200,
  56. height: 200,
  57. left: 0,
  58. right: 320,
  59. toJSON: () => ({}),
  60. top: 0,
  61. width: 320,
  62. x: 0,
  63. y: 0,
  64. } as DOMRect;
  65. };
  66. restoreRect = () => {
  67. Element.prototype.getBoundingClientRect = original;
  68. };
  69. });
  70. afterAll(() => {
  71. restoreRect?.();
  72. });
  73. afterEach(() => {
  74. cleanup();
  75. });
  76. describe("ArtifactMetrics", () => {
  77. const spec = parseArtifactPresetSpec("metrics", {
  78. title: "性能",
  79. metrics: [{ field: "p99", label: "P99", unit: "ms" }, { field: "errors" }],
  80. }) as MetricsSpec;
  81. it("renders a tile row in the compact form", () => {
  82. render(
  83. createElement(ArtifactMetrics, {
  84. compact: true,
  85. items: items({ p99: 12, errors: 0 }, { p99: 9 }),
  86. labels,
  87. spec,
  88. }),
  89. );
  90. const values = screen.getAllByTestId("artifact-metric-value").map((node) => node.textContent);
  91. expect(values).toEqual(["9", "0"]);
  92. // 小卡不重复标题——卡片本身已经有标题了。
  93. expect(screen.queryByText("性能")).toBeNull();
  94. });
  95. it("renders the title and tiles in the full form", () => {
  96. render(createElement(ArtifactMetrics, { items: items({ p99: 9 }), labels, spec }));
  97. expect(screen.getByText("性能")).toBeTruthy();
  98. expect(screen.getAllByTestId("artifact-metric-tile")).toHaveLength(2);
  99. // 从没出现过的字段显示破折号,而不是 0。
  100. expect(screen.getAllByTestId("artifact-metric-value")[1]!.textContent).toBe("—");
  101. });
  102. it("shows the empty state before any item arrives", () => {
  103. render(createElement(ArtifactMetrics, { items: [], labels, spec }));
  104. expect(screen.getByTestId("artifact-preset-empty").textContent).toBe("暂无数据");
  105. });
  106. });
  107. describe("ArtifactTable", () => {
  108. const spec = parseArtifactPresetSpec("table", {
  109. title: "回合",
  110. columns: [{ field: "name" }, { field: "ms", label: "耗时", unit: "ms" }],
  111. key: "name",
  112. }) as TableSpec;
  113. it("shows the row count and only the first three rows in the compact form", () => {
  114. render(
  115. createElement(ArtifactTable, {
  116. compact: true,
  117. items: items(
  118. { name: "a", ms: 1 },
  119. { name: "b", ms: 2 },
  120. { name: "c", ms: 3 },
  121. { name: "d", ms: 4 },
  122. ),
  123. labels,
  124. spec,
  125. }),
  126. );
  127. expect(screen.getByTestId("artifact-table-count").textContent).toBe("4 条");
  128. expect(screen.getAllByTestId("artifact-table-row")).toHaveLength(3);
  129. });
  130. it("renders every row with unit-bearing headers in the full form", () => {
  131. render(
  132. createElement(ArtifactTable, {
  133. items: items({ name: "a", ms: 1 }, { name: "b", ms: 2 }, { name: "c", ms: 3 }),
  134. labels,
  135. spec,
  136. }),
  137. );
  138. expect(screen.getByText("回合")).toBeTruthy();
  139. expect(screen.getByText("耗时 (ms)")).toBeTruthy();
  140. expect(screen.getAllByTestId("artifact-table-row")).toHaveLength(3);
  141. });
  142. it("shows the empty state before any item arrives", () => {
  143. render(createElement(ArtifactTable, { items: [], labels, spec }));
  144. expect(screen.getByTestId("artifact-preset-empty")).toBeTruthy();
  145. });
  146. });
  147. describe("ArtifactBoard", () => {
  148. const spec = parseArtifactPresetSpec("board", {
  149. title: "驱动",
  150. key: "id",
  151. status: "state",
  152. columns: ["todo", "done"],
  153. cardTitle: "name",
  154. detail: [{ field: "owner", label: "负责人" }],
  155. }) as BoardSpec;
  156. const stream = items(
  157. { id: "1", state: "todo", name: "uart", owner: "a" },
  158. { id: "2", state: "done", name: "spi" },
  159. { id: "3", state: "blocked", name: "i2c" },
  160. );
  161. it("renders per-column counts in the compact form", () => {
  162. render(createElement(ArtifactBoard, { compact: true, items: stream, labels, spec }));
  163. const counts = screen
  164. .getAllByTestId("artifact-board-column-count")
  165. .map((node) => node.textContent);
  166. expect(counts).toEqual(["todo1", "done1", "其他1"]);
  167. expect(screen.queryByTestId("artifact-board-card")).toBeNull();
  168. });
  169. it("renders columns and cards in the full form", () => {
  170. render(createElement(ArtifactBoard, { items: stream, labels, spec }));
  171. expect(screen.getAllByTestId("artifact-board-column")).toHaveLength(3);
  172. expect(screen.getAllByTestId("artifact-board-card")).toHaveLength(3);
  173. expect(screen.getByText("uart")).toBeTruthy();
  174. // 未列出的 status 落到「其他」,标题由 labels 提供(组件不查 i18n)。
  175. expect(screen.getByText("其他")).toBeTruthy();
  176. // 三张卡都带 detail 行(值可以为空,标签始终在场)。
  177. expect(screen.getAllByText("负责人")).toHaveLength(3);
  178. });
  179. it("shows the empty state before any item arrives", () => {
  180. render(createElement(ArtifactBoard, { items: [], labels, spec }));
  181. expect(screen.getByTestId("artifact-preset-empty")).toBeTruthy();
  182. });
  183. });
  184. describe("ArtifactChart", () => {
  185. const spec = parseArtifactPresetSpec("chart", {
  186. title: "查询耗时",
  187. x: { field: "round", label: "轮次" },
  188. y: [
  189. { field: "queryMs", label: "查询", unit: "ms" },
  190. { field: "writeMs", label: "写入", unit: "ms" },
  191. ],
  192. baseline: { field: "budgetMs", label: "预算" },
  193. }) as ChartSpec;
  194. const stream = items(
  195. { round: 1, queryMs: 10, writeMs: 4, budgetMs: 6 },
  196. { round: 2, queryMs: 8, writeMs: 5 },
  197. { round: 3, queryMs: 6, writeMs: 5 },
  198. );
  199. it("lazily renders a sparkline plus the latest value in the compact form", async () => {
  200. render(createElement(ArtifactChart, { compact: true, items: stream, labels, spec }));
  201. // 懒加载:第一帧是骨架,recharts 落地后才有 SVG。
  202. expect(screen.getByTestId("artifact-chart-skeleton")).toBeTruthy();
  203. await waitFor(() => expect(screen.getByTestId("artifact-chart-compact")).toBeTruthy());
  204. expect(screen.getByTestId("artifact-chart-latest").textContent).toBe("6ms");
  205. expect(document.querySelector("svg.recharts-surface")).toBeTruthy();
  206. // 无轴 sparkline:没有刻度文本。
  207. expect(document.querySelector(".recharts-cartesian-axis-tick")).toBeNull();
  208. });
  209. it("renders axes, a legend and the x-axis caption in the full form", async () => {
  210. render(createElement(ArtifactChart, { items: stream, labels, spec }));
  211. await waitFor(() => expect(screen.getByTestId("artifact-chart")).toBeTruthy());
  212. expect(screen.getByText("查询耗时")).toBeTruthy();
  213. // 图例永远在场,且每条带最新值——身份不只靠颜色(见 palette.ts 的次级编码那段)。
  214. const legend = screen.getAllByTestId("artifact-chart-legend-item").map((n) => n.textContent);
  215. expect(legend).toEqual(["查询6 ms", "写入5 ms"]);
  216. expect(screen.getByText("轮次")).toBeTruthy();
  217. await waitFor(() =>
  218. expect(document.querySelector(".recharts-cartesian-axis-tick")).toBeTruthy(),
  219. );
  220. // 参考线取自第一条带 budgetMs 的条目。
  221. expect(document.querySelector(".recharts-reference-line")).toBeTruthy();
  222. });
  223. it("shows the empty state before any item arrives", async () => {
  224. render(createElement(ArtifactChart, { items: [], labels, spec }));
  225. await waitFor(() => expect(screen.getByTestId("artifact-preset-empty")).toBeTruthy());
  226. });
  227. it("keeps recharts out of the barrel's static import graph", async () => {
  228. // 图表必须可懒加载(Electron Linux 启动雷):barrel 自己 import 时不得拉起 recharts。
  229. const { readFile } = await import("node:fs/promises");
  230. const [entry, view, barrel] = await Promise.all(
  231. [
  232. "packages/ui/src/app-shell/workflow-artifacts/presets/ArtifactChart.tsx",
  233. "packages/ui/src/app-shell/workflow-artifacts/presets/ArtifactChartView.tsx",
  234. "packages/ui/src/app-shell/workflow-artifacts/presets/index.ts",
  235. ].map((path) => readFile(path, "utf8")),
  236. );
  237. // recharts 只出现在 View 里,且只经 lazy 的动态 import 抵达。
  238. expect(view).toContain('from "recharts"');
  239. expect(entry).not.toContain('from "recharts"');
  240. expect(entry).toContain("lazy(");
  241. expect(entry).toContain(
  242. 'import("@/app-shell/workflow-artifacts/presets/ArtifactChartView.js")',
  243. );
  244. expect(barrel).not.toContain("ArtifactChartView");
  245. });
  246. });
  247. describe("chartPlotPropsEqual — 绘图体的重渲染契约", () => {
  248. const spec = parseArtifactPresetSpec("chart", {
  249. x: "round",
  250. y: "ms",
  251. baseline: "budget",
  252. }) as ChartSpec;
  253. function plot(count: number, options: { baseline?: number; offset?: number } = {}) {
  254. const stream = Array.from({ length: count }, (_, index) => ({
  255. sequence: index + 1 + (options.offset ?? 0),
  256. siteId: "report#1",
  257. ordinal: index + 1,
  258. item: {
  259. round: index + 1,
  260. ms: (index + 1) * 2,
  261. ...(options.baseline === undefined ? {} : { budget: options.baseline }),
  262. },
  263. }));
  264. return { compact: false, model: applyArtifactItems("chart", spec, stream) };
  265. }
  266. it("skips the re-render when a fresh model carries the same points", () => {
  267. // 父组件重渲染会造出一份新的 model 引用;点数、定义域、首尾 sequence 都没变 ⇒ 不重画。
  268. expect(chartPlotPropsEqual(plot(3), plot(3))).toBe(true);
  269. });
  270. it("re-renders when a point arrives", () => {
  271. expect(chartPlotPropsEqual(plot(3), plot(4))).toBe(false);
  272. });
  273. it("re-renders when the same-sized batch was actually replaced", () => {
  274. // 冷恢复重取:点数一样但 sequence 整体后移,靠首尾 sequence 认出来。
  275. expect(chartPlotPropsEqual(plot(3), plot(3, { offset: 100 }))).toBe(false);
  276. });
  277. it("re-renders when the baseline or the form changes", () => {
  278. expect(chartPlotPropsEqual(plot(3), plot(3, { baseline: 5 }))).toBe(false);
  279. expect(chartPlotPropsEqual(plot(3), { ...plot(3), compact: true })).toBe(false);
  280. });
  281. });