cloudContentDialog.test.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. // @vitest-environment jsdom
  2. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  3. import { cleanup, fireEvent, render as renderUi, screen, waitFor } from "@testing-library/react";
  4. import { createElement, type ReactNode } from "react";
  5. import { afterEach, describe, expect, it, vi } from "vitest";
  6. import { CloudContentDialog } from "@/components/cloud-content-dialog/CloudContentDialog.js";
  7. import type { CloudContentDialogPayload } from "@/components/cloud-content-dialog/cloudContentDialogTypes.js";
  8. afterEach(cleanup);
  9. const render = (ui: ReactNode) =>
  10. renderUi(ui, {
  11. wrapper: ({ children }) =>
  12. createElement(ZCodeIntlProvider, { initialLocale: "en-US" }, children),
  13. });
  14. const payload: CloudContentDialogPayload = {
  15. schemaVersion: 1,
  16. id: "new-feature",
  17. revision: 1,
  18. locale: "en-US",
  19. kind: "feature",
  20. dialog: {
  21. hero: { type: "image", src: "https://example.com/hero.png", alt: "Feature preview" },
  22. title: "New feature",
  23. description: { format: "html", text: "<p>A <b>new</b> feature</p>" },
  24. buttons: [
  25. { id: "copy", label: "Copy", variant: "primary", actionId: "copy" },
  26. { id: "claim", label: "Claim", variant: "secondary", actionId: "claim" },
  27. { id: "close", label: "Later", variant: "link", actionId: "close" },
  28. ],
  29. },
  30. actions: {
  31. copy: { type: "copy_text", text: "share" },
  32. claim: { type: "claim_plan", planId: "test" },
  33. close: { type: "close" },
  34. },
  35. };
  36. describe("CloudContentDialog", () => {
  37. it("keeps initial focus in the parent dialog so a bundle cannot swallow Escape", async () => {
  38. const onClose = vi.fn();
  39. render(
  40. createElement(CloudContentDialog, {
  41. payload: {
  42. ...payload,
  43. dialog: {
  44. ...payload.dialog,
  45. hero: {
  46. type: "interactive_bundle",
  47. runtime: "zcode-hero-sandbox-v1",
  48. resolvedUrl: "https://example.com/hero.html",
  49. data: {},
  50. },
  51. },
  52. },
  53. open: true,
  54. onClose,
  55. handlers: {},
  56. labels: { actionFailed: "Failed" },
  57. }),
  58. );
  59. await waitFor(() =>
  60. expect(document.activeElement).toBe(document.querySelector('[data-slot="dialog-close"]')),
  61. );
  62. fireEvent.keyDown(document.activeElement!, { key: "Escape" });
  63. expect(onClose).toHaveBeenCalledTimes(1);
  64. });
  65. it("renders rich title and button without nested actions or losing the close event", () => {
  66. const onClose = vi.fn();
  67. render(
  68. createElement(CloudContentDialog, {
  69. payload: {
  70. ...payload,
  71. dialog: {
  72. ...payload.dialog,
  73. formattedTitle: { format: "markdown", text: "**New** feature" },
  74. buttons: [
  75. {
  76. id: "close",
  77. actionId: "close",
  78. label: "Later",
  79. variant: "primary",
  80. formattedLabel: {
  81. format: "html",
  82. text: '<p><a href="https://example.com"><b style="font-style:italic" class="underline">Later</b></a><script>bad()</script></p>',
  83. },
  84. },
  85. ],
  86. },
  87. },
  88. open: true,
  89. onClose,
  90. handlers: {},
  91. labels: { actionFailed: "Failed" },
  92. }),
  93. );
  94. expect(screen.getByRole("heading").querySelector("strong")?.textContent).toBe("New");
  95. const button = screen.getByRole("button", { name: "Later" });
  96. expect(button.querySelector("p,a,script,svg")).toBeNull();
  97. expect(button.querySelector("b")?.style.fontStyle).toBe("italic");
  98. expect(button.querySelector("b")?.classList.contains("underline")).toBe(true);
  99. expect(button.querySelector("b")?.classList.contains("text-foreground")).toBe(false);
  100. fireEvent.click(button.querySelector("b")!);
  101. expect(onClose).toHaveBeenCalledTimes(1);
  102. });
  103. it("applies button theme without changing close actions", () => {
  104. const onClose = vi.fn();
  105. render(
  106. createElement(CloudContentDialog, {
  107. payload: {
  108. ...payload,
  109. dialog: {
  110. ...payload.dialog,
  111. buttons: [
  112. {
  113. id: "close",
  114. label: "Themed close",
  115. actionId: "close",
  116. variant: "primary",
  117. theme: {
  118. variant: "ghost",
  119. class: "rounded-lg text-foreground",
  120. style: "color: red;position:fixed;background-image:url(https://example.com/x)",
  121. },
  122. },
  123. ],
  124. },
  125. },
  126. open: true,
  127. onClose,
  128. handlers: {},
  129. labels: { actionFailed: "Failed" },
  130. }),
  131. );
  132. const button = screen.getByRole("button", { name: "Themed close" });
  133. expect(button.dataset.variant).toBe("ghost");
  134. expect(button.className).toContain("rounded-lg");
  135. expect(button.className).not.toContain("rounded-full");
  136. expect(button.style.color).toBe("red");
  137. expect(button.style.position).toBe("");
  138. expect(button.style.backgroundImage).toBe("");
  139. fireEvent.click(button);
  140. expect(onClose).toHaveBeenCalledOnce();
  141. });
  142. it("supports an explicit focus target when async loading disabled the opener", async () => {
  143. const target = document.createElement("button");
  144. document.body.append(target);
  145. const props = {
  146. payload,
  147. open: true,
  148. onClose: vi.fn(),
  149. handlers: {},
  150. labels: { actionFailed: "Failed" },
  151. returnFocusRef: { current: target },
  152. };
  153. const { rerender } = render(createElement(CloudContentDialog, props));
  154. rerender(createElement(CloudContentDialog, { ...props, open: false }));
  155. try {
  156. await waitFor(() => expect(document.activeElement).toBe(target));
  157. } finally {
  158. target.remove();
  159. }
  160. });
  161. it("restores focus to the connected opener after closing a controlled dialog", async () => {
  162. const opener = document.createElement("button");
  163. document.body.append(opener);
  164. opener.focus();
  165. const props = {
  166. payload,
  167. open: true,
  168. onClose: vi.fn(),
  169. handlers: {},
  170. labels: { actionFailed: "Failed" },
  171. };
  172. const { rerender } = render(createElement(CloudContentDialog, props));
  173. expect(document.activeElement).not.toBe(opener);
  174. rerender(createElement(CloudContentDialog, { ...props, open: false }));
  175. try {
  176. await waitFor(() => expect(document.activeElement).toBe(opener));
  177. } finally {
  178. opener.remove();
  179. }
  180. });
  181. it("shows a host-localized copy acknowledgement without changing the payload or closing", async () => {
  182. const onClose = vi.fn();
  183. render(
  184. createElement(CloudContentDialog, {
  185. payload,
  186. open: true,
  187. onClose,
  188. handlers: { copy_text: vi.fn() },
  189. labels: { actionFailed: "Failed", copySucceeded: "Copied" },
  190. }),
  191. );
  192. fireEvent.click(screen.getByText("Copy"));
  193. expect(await screen.findByText("Copied")).toBeTruthy();
  194. expect(payload.dialog.buttons[0]?.label).toBe("Copy");
  195. expect(onClose).not.toHaveBeenCalled();
  196. });
  197. it("does not let a closed instance's pending dismissal close a reopened dialog", async () => {
  198. let resolve: () => void = () => {};
  199. const onClose = vi.fn();
  200. const dismiss = vi.fn(
  201. () =>
  202. new Promise<void>((done) => {
  203. resolve = done;
  204. }),
  205. );
  206. const content = {
  207. ...payload,
  208. actions: { ...payload.actions, copy: { type: "dismiss_content" as const } },
  209. };
  210. const props = {
  211. payload: content,
  212. open: true,
  213. onClose,
  214. handlers: { dismiss_content: dismiss },
  215. labels: { actionFailed: "Failed" },
  216. };
  217. const { rerender } = render(createElement(CloudContentDialog, props));
  218. fireEvent.click(screen.getByText("Copy"));
  219. rerender(createElement(CloudContentDialog, { ...props, open: false }));
  220. rerender(createElement(CloudContentDialog, props));
  221. resolve();
  222. await waitFor(() =>
  223. expect((screen.getByRole("button", { name: "Copy" }) as HTMLButtonElement).disabled).toBe(
  224. false,
  225. ),
  226. );
  227. expect(onClose).not.toHaveBeenCalled();
  228. });
  229. it("renders payload fields and ordered buttons, only dispatching available host actions", async () => {
  230. const copy = vi.fn();
  231. const onClose = vi.fn();
  232. render(
  233. createElement(CloudContentDialog, {
  234. payload,
  235. open: true,
  236. onClose,
  237. handlers: { copy_text: copy },
  238. labels: { actionFailed: "Action failed" },
  239. }),
  240. );
  241. expect(screen.getByRole("heading").textContent).toBe("New feature");
  242. expect(screen.getByText("new").tagName).toBe("B");
  243. const buttons = screen.getAllByTestId("cloud-dialog-action");
  244. expect(buttons.map((button) => button.textContent)).toEqual(["Copy", "Claim", "Later"]);
  245. expect((buttons[1] as HTMLButtonElement).disabled).toBe(true);
  246. fireEvent.click(buttons[0]!);
  247. await waitFor(() => expect(copy).toHaveBeenCalledWith({ type: "copy_text", text: "share" }));
  248. fireEvent.click(screen.getByText("Later"));
  249. expect(onClose).toHaveBeenCalledTimes(1);
  250. });
  251. it("blocks duplicate actions, surfaces failures, permits retry and never blocks closing", async () => {
  252. let reject: (error: Error) => void = () => {};
  253. const copy = vi.fn(
  254. () =>
  255. new Promise<void>((_resolve, fail) => {
  256. reject = fail;
  257. }),
  258. );
  259. const onClose = vi.fn();
  260. render(
  261. createElement(CloudContentDialog, {
  262. payload,
  263. open: true,
  264. onClose,
  265. handlers: { copy_text: copy },
  266. labels: { actionFailed: "Action failed" },
  267. }),
  268. );
  269. fireEvent.click(screen.getByText("Copy"));
  270. fireEvent.click(screen.getByText("Copy"));
  271. expect(copy).toHaveBeenCalledTimes(1);
  272. reject(new Error("failure"));
  273. await waitFor(() => expect(screen.getByRole("alert").textContent).toBe("Action failed"));
  274. fireEvent.click(screen.getByText("Copy"));
  275. expect(copy).toHaveBeenCalledTimes(2);
  276. fireEvent.click(screen.getByText("Later"));
  277. expect(onClose).toHaveBeenCalledTimes(1);
  278. });
  279. });