usageStatsHeatmap.test.ts 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. // @vitest-environment jsdom
  2. import { createElement, type ReactNode, type ComponentProps } from "react";
  3. import { renderToStaticMarkup } from "react-dom/server";
  4. import { fireEvent, render, screen } from "@testing-library/react";
  5. import { describe, expect, it, vi } from "vitest";
  6. import type { AppUsageHeatmapCell, AppUsageHeatmapWeek } from "@zcode/shared";
  7. import zhCN from "@/i18n/locales/zh-CN.js";
  8. import { UsageHeatmap } from "@/settings/usage-stats/UsageHeatmap.js";
  9. vi.mock("@/ControlHintTooltip.js", () => ({
  10. ControlHintTooltip: ({
  11. children,
  12. title,
  13. }: {
  14. children: ReactNode;
  15. title: string;
  16. }) => createElement("span", { "data-tooltip-title": title }, children),
  17. }));
  18. const DAY_MS = 86_400_000;
  19. function dateKeyFromUtcDayIndex(dayIndex: number): string {
  20. return new Date(dayIndex * DAY_MS).toISOString().slice(0, 10);
  21. }
  22. function buildThirtyDayWeeks(
  23. endTime = Date.UTC(2026, 5, 4),
  24. ): AppUsageHeatmapWeek[] {
  25. const endDayIndex = Math.floor(endTime / DAY_MS);
  26. const cells: AppUsageHeatmapCell[] = Array.from(
  27. { length: 30 },
  28. (_, index) => ({
  29. date: dateKeyFromUtcDayIndex(endDayIndex - 29 + index),
  30. level: ((index % 4) + 1) as AppUsageHeatmapCell["level"],
  31. totalTokens: index + 1,
  32. turnCount: 1,
  33. toolCallCount: 0,
  34. }),
  35. );
  36. return Array.from({ length: 5 }, (_, weekIndex) => ({
  37. weekIndex,
  38. days: Array.from({ length: 7 }, (_, dayIndex) => {
  39. return cells[weekIndex * 7 + dayIndex] ?? null;
  40. }),
  41. }));
  42. }
  43. describe("UsageHeatmap", () => {
  44. const intl = {
  45. formatMessage(
  46. descriptor: { id: string },
  47. values?: Record<string, string | number>,
  48. ) {
  49. if (descriptor.id === "settings.usage.heatmapCell") {
  50. return `${values?.date}\n${values?.tokens} tokens · ${values?.turns} messages`;
  51. }
  52. if (descriptor.id === "settings.usage.heatmapWeeklyCell") {
  53. return `${values?.date} week\n${values?.tokens} tokens · ${values?.turns} messages`;
  54. }
  55. if (descriptor.id === "settings.usage.heatmapCumulativeCell") {
  56. return `Through ${values?.date}\n${values?.tokens} tokens · ${values?.turns} messages`;
  57. }
  58. if (descriptor.id === "settings.usage.heatmapToolCell") {
  59. return `${values?.date}\n${values?.tokens} tokens · ${values?.tools} tools`;
  60. }
  61. if (descriptor.id === "settings.usage.heatmapWeeklyToolCell") {
  62. return `${values?.date} week\n${values?.tokens} tokens · ${values?.tools} tools`;
  63. }
  64. if (descriptor.id === "settings.usage.heatmapCumulativeToolCell") {
  65. return `Through ${values?.date}\n${values?.tokens} tokens · ${values?.tools} tools`;
  66. }
  67. const messages: Record<string, string> = {
  68. "settings.usage.heatmapTitle": "Token Activity",
  69. "settings.usage.heatmap.less": "Less",
  70. "settings.usage.heatmap.more": "More",
  71. "settings.usage.heatmap.range.daily": "Daily",
  72. "settings.usage.heatmap.range.weekly": "Weekly",
  73. "settings.usage.heatmap.range.cumulative": "Cumulative",
  74. };
  75. return messages[descriptor.id] ?? descriptor.id;
  76. },
  77. } as ComponentProps<typeof UsageHeatmap>["intl"];
  78. it("uses Token activity as the Chinese heatmap title", () => {
  79. expect(zhCN["settings.usage.heatmapTitle"]).toBe("Token 活动");
  80. expect(zhCN["settings.usage.heatmapCell"]).toBe(
  81. "{date}\n{tokens} tokens · {turns} 轮消息",
  82. );
  83. expect(zhCN["settings.usage.heatmapWeeklyCell"]).toBe(
  84. "{date} 当周\n{tokens} tokens · {turns} 轮消息",
  85. );
  86. expect(zhCN["settings.usage.heatmapCumulativeCell"]).toBe(
  87. "截至 {date} 当周累计\n{tokens} tokens · {turns} 轮消息",
  88. );
  89. });
  90. it("shows real tool calls instead of missing message turns for Coding Plan", () => {
  91. const html = renderToStaticMarkup(
  92. createElement(UsageHeatmap, {
  93. locale: "en-US",
  94. intl,
  95. weeks: buildThirtyDayWeeks(),
  96. countMetric: "tools",
  97. }),
  98. );
  99. expect(html).toContain("tokens");
  100. expect(html).not.toContain("messages");
  101. expect(html).toContain("0 tools");
  102. });
  103. it("renders missing days as zero-usage hoverable cells", () => {
  104. const html = renderToStaticMarkup(
  105. createElement(UsageHeatmap, {
  106. locale: "en-US",
  107. intl,
  108. weeks: buildThirtyDayWeeks(),
  109. }),
  110. );
  111. expect(html).toContain("rounded-xl");
  112. expect(html).toContain("data-usage-heatmap-month-label");
  113. expect(html).toContain("Daily");
  114. expect(html).toContain("Weekly");
  115. expect(html).toContain("Cumulative");
  116. expect(
  117. html.match(/data-tooltip-title="([^"]+)\n0 tokens · 0 messages/)?.[1],
  118. ).toBe("June 8, 2025");
  119. expect((html.match(/data-tooltip-title=/g) ?? []).length).toBe(364);
  120. expect((html.match(/0 tokens · 0 messages/g) ?? []).length).toBe(334);
  121. expect(html).toContain("background-color:var(--color-usage-heatmap-0)");
  122. expect(html).toContain("background-color:var(--color-usage-heatmap-4)");
  123. expect(html).not.toContain("var(--color-brand)");
  124. });
  125. it("shows only the latest 12 month labels while preserving leading grid spans", () => {
  126. const { container, unmount } = render(
  127. createElement(UsageHeatmap, {
  128. locale: "en-US",
  129. intl,
  130. weeks: buildThirtyDayWeeks(Date.UTC(2026, 7, 17)),
  131. }),
  132. );
  133. const labels = [
  134. ...container.querySelectorAll("[data-usage-heatmap-month-label]"),
  135. ];
  136. expect(labels.map((label) => label.textContent)).toEqual([
  137. "",
  138. "Sep",
  139. "Oct",
  140. "Nov",
  141. "Dec",
  142. "Jan",
  143. "Feb",
  144. "Mar",
  145. "Apr",
  146. "May",
  147. "Jun",
  148. "Jul",
  149. "Aug",
  150. ]);
  151. // 2025-09-01 是周一,所以 Sep 应锚定到包含 1 日的 2025-08-31 周列;
  152. // 开头仅剩 2025-08-24 一列空月份占位。
  153. expect(labels[0]?.getAttribute("style")).toContain("grid-column: span 1");
  154. unmount();
  155. });
  156. it("switches Token activity between daily, weekly, and cumulative views", () => {
  157. render(
  158. createElement(UsageHeatmap, {
  159. locale: "en-US",
  160. intl,
  161. weeks: buildThirtyDayWeeks(),
  162. }),
  163. );
  164. expect(screen.getByText("Daily")).toBeTruthy();
  165. expect(document.body.innerHTML).not.toContain(
  166. "group-hover/usage-heatmap-column:border-border-hover",
  167. );
  168. fireEvent.click(screen.getByText("Weekly"));
  169. expect(document.body.innerHTML).toContain("week\n");
  170. expect(document.body.innerHTML).toContain("tokens ·");
  171. expect(document.body.innerHTML).toContain(
  172. "group-hover/usage-heatmap-column:border-border-hover",
  173. );
  174. expect((document.body.innerHTML.match(/week\n/g) ?? []).length).toBe(52);
  175. fireEvent.click(screen.getByText("Cumulative"));
  176. expect(document.body.innerHTML).toContain("Through");
  177. expect(document.body.innerHTML).toContain("tokens ·");
  178. expect(document.body.innerHTML).toContain(
  179. "group-hover/usage-heatmap-column:border-border-hover",
  180. );
  181. expect((document.body.innerHTML.match(/Through/g) ?? []).length).toBe(52);
  182. });
  183. it("fits all 52 week columns in the container without horizontal scrolling", () => {
  184. const html = renderToStaticMarkup(
  185. createElement(UsageHeatmap, {
  186. locale: "en-US",
  187. intl,
  188. weeks: buildThirtyDayWeeks(),
  189. }),
  190. );
  191. expect(html).toContain("grid-template-columns:repeat(52, minmax(0, 1fr))");
  192. expect(html).toContain("grid w-full gap-x-0.5");
  193. expect(html).not.toContain("min-w-max");
  194. expect(html).not.toContain("overflow-x-auto");
  195. });
  196. it("matches the hook scope tabs pill styling", () => {
  197. const html = renderToStaticMarkup(
  198. createElement(UsageHeatmap, {
  199. locale: "en-US",
  200. intl,
  201. weeks: buildThirtyDayWeeks(),
  202. }),
  203. );
  204. expect(html).toContain("rounded-full bg-surface");
  205. expect(html).toContain("p-0.5");
  206. expect(html).toContain("group-data-horizontal/tabs:h-7");
  207. expect(html).toContain("data-active:bg-background");
  208. expect(html).toContain("data-active:shadow-none");
  209. expect(html).toContain("h-6 flex-none justify-center rounded-full");
  210. expect(html).toContain("px-2.5 py-0 text-ui-sm font-medium");
  211. expect(html).not.toContain("w-16");
  212. expect(html).not.toContain("h-7 flex-none rounded-full");
  213. expect(html).not.toContain("px-0 py-0 text-ui-sm");
  214. expect(html).not.toContain(
  215. "px-2.5 text-ui-base font-medium text-foreground-subtle",
  216. );
  217. expect(html).not.toContain("rounded-lg bg-background p-1");
  218. });
  219. });