gentle-pi 4.7.0 → 4.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (365) hide show
  1. package/README.md +55 -44
  2. package/assets/agents/gentle-ai-explore.md +3 -3
  3. package/assets/agents/gentle-ai-verify.md +20 -6
  4. package/assets/agents/gentle-ai-worker.md +6 -6
  5. package/assets/agents/jd-judge-a.md +1 -3
  6. package/assets/agents/jd-judge-b.md +1 -3
  7. package/assets/agents/review-readability.md +1 -5
  8. package/assets/agents/review-reliability.md +1 -5
  9. package/assets/agents/review-resilience.md +1 -5
  10. package/assets/agents/review-risk.md +1 -5
  11. package/assets/design-canvas/canvas-api.js +45 -0
  12. package/assets/design-canvas/canvas-boards.js +456 -0
  13. package/assets/design-canvas/canvas-boot.js +217 -0
  14. package/assets/design-canvas/canvas-checks.js +491 -0
  15. package/assets/design-canvas/canvas-comments.js +315 -0
  16. package/assets/design-canvas/canvas-compare.js +159 -0
  17. package/assets/design-canvas/canvas-events.js +75 -0
  18. package/assets/design-canvas/canvas-export.js +393 -0
  19. package/assets/design-canvas/canvas-focus.js +203 -0
  20. package/assets/design-canvas/canvas-handoffs.js +150 -0
  21. package/assets/design-canvas/canvas-i18n-es.js +392 -0
  22. package/assets/design-canvas/canvas-i18n.js +108 -0
  23. package/assets/design-canvas/canvas-layout.js +526 -0
  24. package/assets/design-canvas/canvas-menu.js +213 -0
  25. package/assets/design-canvas/canvas-messages.js +86 -0
  26. package/assets/design-canvas/canvas-minimap.js +163 -0
  27. package/assets/design-canvas/canvas-parts.js +401 -0
  28. package/assets/design-canvas/canvas-popover.js +234 -0
  29. package/assets/design-canvas/canvas-rail.js +348 -0
  30. package/assets/design-canvas/canvas-sizes.js +524 -0
  31. package/assets/design-canvas/canvas-store.js +164 -0
  32. package/assets/design-canvas/canvas-tokens.js +674 -0
  33. package/assets/design-canvas/canvas-ui.js +24 -0
  34. package/assets/design-canvas/canvas-view.js +184 -0
  35. package/assets/design-canvas/canvas.css +746 -15
  36. package/assets/design-canvas/canvas.js +2 -1506
  37. package/assets/design-canvas/index.html +117 -36
  38. package/assets/design-canvas/inspector.js +546 -16
  39. package/assets/install-wizard/wizard.js +5 -1
  40. package/assets/migrations/agent-body-history.json +24 -0
  41. package/assets/orchestrator-delegation-reference.md +8 -14
  42. package/assets/orchestrator-delegation.md +4 -4
  43. package/assets/orchestrator-full-delegation-card.md +4 -5
  44. package/assets/orchestrator-full-delegation.md +8 -8
  45. package/assets/orchestrator-memory.md +2 -2
  46. package/assets/orchestrator-prompts.md +1 -1
  47. package/assets/orchestrator-quota-recovery.md +5 -0
  48. package/assets/orchestrator-skills.md +13 -12
  49. package/assets/orchestrator-tracking.md +10 -14
  50. package/assets/orchestrator-verification.md +10 -8
  51. package/assets/orchestrator-writer.md +4 -4
  52. package/assets/orchestrator.md +18 -22
  53. package/bin/gentle-shell.mjs +128 -9
  54. package/contracts/review-provider-contract-mirror/provider-contract.lock.json +8 -9
  55. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/manifest.json +3 -3
  56. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/orchestration/pi.md +1 -0
  57. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/routing/pi.md +6 -6
  58. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/generated/provider-capabilities.baseline.json +3 -3
  59. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/generated/provider-roles.baseline.json +1 -1
  60. package/docs/assets/brand/sponsor-banner.svg +60 -0
  61. package/docs/bundled-install.md +14 -6
  62. package/docs/delegated-verification.md +18 -2
  63. package/docs/desktop-rpc.md +1253 -0
  64. package/docs/gentle-agents-activity.md +26 -0
  65. package/docs/gentle-shell.md +39 -16
  66. package/docs/install-wizard.md +30 -21
  67. package/docs/odd-preparation-continuity.md +24 -0
  68. package/docs/permission-modes.md +9 -1
  69. package/docs/prompt-budget.md +12 -0
  70. package/docs/rdd-odd-friction-triage-2026-11-07.md +57 -0
  71. package/docs/readme-reference.md +76 -24
  72. package/docs/review-coordinator.md +29 -9
  73. package/docs/review-delivery-preflight.md +22 -0
  74. package/docs/work-continuity.md +11 -1
  75. package/extensions/ask-user-question.ts +2 -2
  76. package/extensions/child-context.ts +21 -7
  77. package/extensions/gentle-agents.ts +234 -33
  78. package/extensions/gentle-ai.ts +576 -135
  79. package/extensions/gentle-design.ts +69 -3
  80. package/extensions/gentle-desktop-rpc.ts +143 -0
  81. package/extensions/gentle-guide.ts +3 -0
  82. package/extensions/gentle-shell.ts +105 -52
  83. package/extensions/gentle-todo.ts +48 -25
  84. package/extensions/skill-registry.ts +248 -223
  85. package/lib/agent-assets.ts +30 -6
  86. package/lib/agent-tool-overlay.ts +117 -0
  87. package/lib/agents-config.ts +47 -6
  88. package/lib/agents-message-delivery.ts +17 -0
  89. package/lib/agents-messaging.ts +8 -2
  90. package/lib/agents-protocol.ts +15 -0
  91. package/lib/agents-report-cap.ts +115 -0
  92. package/lib/agents-runner.ts +91 -6
  93. package/lib/agents-session-transport.ts +17 -1
  94. package/lib/background-jobs-tools.ts +9 -4
  95. package/lib/bounded-writer-admission.ts +184 -31
  96. package/lib/child-context-files.ts +21 -6
  97. package/lib/codemode-renderer.ts +1 -0
  98. package/lib/delivery-conflict-markers.ts +349 -0
  99. package/lib/design-canvas-assets.ts +36 -0
  100. package/lib/design-canvas-server.ts +241 -23
  101. package/lib/design-comments.ts +94 -4
  102. package/lib/design-handoffs.ts +2 -1
  103. package/lib/design-layout.ts +125 -0
  104. package/lib/design-parts.ts +281 -0
  105. package/lib/design-system-tokens.ts +111 -0
  106. package/lib/desktop-agents-service.ts +294 -0
  107. package/lib/desktop-design-service.ts +233 -0
  108. package/lib/desktop-jobs-service.ts +263 -0
  109. package/lib/desktop-rpc-agents.ts +294 -0
  110. package/lib/desktop-rpc-config.ts +731 -0
  111. package/lib/desktop-rpc-design.ts +138 -0
  112. package/lib/desktop-rpc-jobs.ts +181 -0
  113. package/lib/desktop-rpc-permissions.ts +177 -0
  114. package/lib/desktop-rpc-profiles.ts +196 -0
  115. package/lib/desktop-rpc-usage.ts +229 -0
  116. package/lib/desktop-rpc.ts +225 -0
  117. package/lib/desktop-usage-service.ts +310 -0
  118. package/lib/destructive-command-guard.ts +188 -13
  119. package/lib/gentle-ai-renderer.ts +13 -1
  120. package/lib/gentle-design.ts +201 -14
  121. package/lib/gentle-shell-bundled.ts +100 -9
  122. package/lib/hidden-tools.ts +35 -0
  123. package/lib/inprocess-reviewer.ts +96 -12
  124. package/lib/model-fallback-policy.ts +9 -0
  125. package/lib/model-routing-authority.ts +9 -0
  126. package/lib/nan-provider.ts +42 -28
  127. package/lib/native-review-cli.ts +79 -4
  128. package/lib/orchestrator-discovery.ts +39 -2
  129. package/lib/reply-language-anchor.ts +27 -2
  130. package/lib/request-context-placement.ts +53 -0
  131. package/lib/review-candidate-view.ts +11 -1
  132. package/lib/review-continuation-registry.ts +17 -0
  133. package/lib/review-coordinator.ts +252 -8
  134. package/lib/review-delivery-preflight.ts +85 -0
  135. package/lib/review-host-relay.ts +5 -1
  136. package/lib/review-integration-v2.ts +56 -3
  137. package/lib/reviewer-stream.ts +87 -0
  138. package/lib/shell-prompt.ts +16 -3
  139. package/lib/shell-usage.ts +10 -0
  140. package/lib/vim-editor-adapter.ts +9 -2
  141. package/lib/writer-batch-admission.ts +55 -0
  142. package/lib/yolo-session-policy.ts +6 -1
  143. package/package.json +2 -2
  144. package/prompts/skill-creation.md +1 -10
  145. package/runtime/design-canvas-assets.mjs +37 -0
  146. package/runtime/gentle-shell-bundled.mjs +100 -9
  147. package/runtime/native-review-cli.mjs +79 -4
  148. package/runtime/review-integration-v2.mjs +56 -3
  149. package/scripts/bootstrap.cmd +2 -2
  150. package/scripts/bootstrap.sh +41 -4
  151. package/scripts/build-full-delegation-card.mjs +4 -0
  152. package/scripts/build-runtime-modules.mjs +1 -0
  153. package/scripts/gentle-ai-installer.mjs +10 -10
  154. package/scripts/gentle-ai-proxy.mjs +1 -1
  155. package/scripts/installer-downloads.mjs +34 -8
  156. package/scripts/installer-preflight.mjs +28 -17
  157. package/scripts/installer-probes.mjs +25 -5
  158. package/scripts/installer-server.mjs +38 -9
  159. package/scripts/installer-windows.mjs +2 -2
  160. package/scripts/pi-update.mjs +166 -27
  161. package/scripts/prepare-verifier.mjs +107 -0
  162. package/scripts/update-agent-body-history.mjs +55 -8
  163. package/scripts/verify-package-files.mjs +40 -19
  164. package/skills/branch-pr/SKILL.md +16 -16
  165. package/skills/comment-writer/SKILL.md +1 -1
  166. package/skills/design/SKILL.md +6 -6
  167. package/skills/gentle-ai/SKILL.md +5 -5
  168. package/skills/judgment-day/SKILL.md +2 -2
  169. package/skills/judgment-day/references/prompts-and-formats.md +1 -1
  170. package/skills/rdd-defect-workflow/SKILL.md +6 -6
  171. package/skills/skill-improver/SKILL.md +2 -2
  172. package/skills/skill-registry/SKILL.md +11 -13
  173. package/skills/tui-design/SKILL.md +1 -1
  174. package/skills/work-unit-commits/SKILL.md +5 -5
  175. package/tests/agent-prompt-diet-contract.test.ts +101 -0
  176. package/tests/agent-tool-overlay-acceptance.test.ts +158 -0
  177. package/tests/agent-tool-overlay.test.ts +89 -0
  178. package/tests/agents-config.test.ts +10 -1
  179. package/tests/agents-message-delivery.test.ts +36 -0
  180. package/tests/agents-queries.test.ts +144 -4
  181. package/tests/agents-report-cap.test.ts +126 -0
  182. package/tests/agents-runner.test.ts +37 -1
  183. package/tests/agents-session-transport.test.ts +34 -0
  184. package/tests/always-on-prompt-verdicts-contract.test.ts +188 -0
  185. package/tests/append-system-prompt-route.test.ts +10 -2
  186. package/tests/approved-text-leftovers-contract.test.ts +136 -0
  187. package/tests/artifact-language.test.ts +1 -1
  188. package/tests/ask-user-question.test.ts +2 -1
  189. package/tests/audit-leftovers-contract.test.ts +51 -0
  190. package/tests/bounded-stop-contract.test.ts +9 -1
  191. package/tests/branch-pr-skill.test.ts +10 -1
  192. package/tests/bundled-install.test.ts +1 -1
  193. package/tests/child-context-files.test.ts +64 -8
  194. package/tests/child-skills-catalog.test.ts +56 -0
  195. package/tests/codemode-rendering.test.ts +4 -1
  196. package/tests/delegate-for-reason-contract.test.ts +30 -8
  197. package/tests/delivery-conflict-markers.test.ts +348 -0
  198. package/tests/design-canvas-all-sizes.test.ts +631 -0
  199. package/tests/design-canvas-allowlist.test.ts +32 -0
  200. package/tests/design-canvas-assets.test.ts +11 -878
  201. package/tests/design-canvas-boards.test.ts +77 -0
  202. package/tests/design-canvas-checks.test.ts +655 -0
  203. package/tests/design-canvas-compare.test.ts +79 -0
  204. package/tests/design-canvas-events.test.ts +59 -0
  205. package/tests/design-canvas-export.test.ts +1168 -0
  206. package/tests/design-canvas-focus.test.ts +113 -0
  207. package/tests/design-canvas-handoffs.test.ts +59 -0
  208. package/tests/design-canvas-i18n-review.test.ts +513 -0
  209. package/tests/design-canvas-i18n-views.test.ts +259 -0
  210. package/tests/design-canvas-i18n.test.ts +526 -0
  211. package/tests/design-canvas-inspector.test.ts +937 -0
  212. package/tests/design-canvas-layout.test.ts +1222 -0
  213. package/tests/design-canvas-minimap.test.ts +413 -0
  214. package/tests/design-canvas-modules.test.ts +90 -0
  215. package/tests/design-canvas-parts.test.ts +721 -0
  216. package/tests/design-canvas-rail.test.ts +799 -0
  217. package/tests/design-canvas-server.test.ts +855 -17
  218. package/tests/design-canvas-sizes.test.ts +548 -0
  219. package/tests/design-canvas-store.test.ts +180 -0
  220. package/tests/design-canvas-tokens.test.ts +965 -0
  221. package/tests/design-canvas-view.test.ts +299 -0
  222. package/tests/design-comments.test.ts +201 -1
  223. package/tests/design-handoffs.test.ts +20 -0
  224. package/tests/design-layout.test.ts +100 -0
  225. package/tests/design-parts.test.ts +260 -0
  226. package/tests/design-system-tokens.test.ts +215 -0
  227. package/tests/desktop-rpc-agents.test.ts +893 -0
  228. package/tests/desktop-rpc-config.test.ts +1452 -0
  229. package/tests/desktop-rpc-design.test.ts +662 -0
  230. package/tests/desktop-rpc-jobs.test.ts +796 -0
  231. package/tests/desktop-rpc-permissions.test.ts +311 -0
  232. package/tests/desktop-rpc-profiles.test.ts +140 -0
  233. package/tests/desktop-rpc-safety.test.ts +119 -0
  234. package/tests/desktop-rpc-usage.test.ts +697 -0
  235. package/tests/desktop-rpc.test.ts +252 -0
  236. package/tests/devbinary/pi-host-relay.devtest.ts +149 -80
  237. package/tests/devbinary/review-session-consent.devtest.ts +84 -0
  238. package/tests/engram-safety.test.ts +111 -0
  239. package/tests/fixtures/devbinary/status-v9-escalated-non-blocking.captured.json +92 -0
  240. package/tests/fixtures/devbinary/status-v9-escalated-non-blocking.provenance.md +3 -0
  241. package/tests/fixtures/primary-session-prompt/gentleman.golden.md +20 -29
  242. package/tests/fixtures/refusal-identity.probe.mjs +139 -0
  243. package/tests/full-delegation-closure.test.ts +29 -0
  244. package/tests/gentle-agents.test.ts +329 -4
  245. package/tests/gentle-ai-binary.test.ts +1 -1
  246. package/tests/gentle-ai-child-guards.test.ts +1 -0
  247. package/tests/gentle-ai-installer.test.ts +52 -51
  248. package/tests/gentle-ai-renderer.test.ts +36 -2
  249. package/tests/gentle-ai.test.ts +121 -6
  250. package/tests/gentle-design.test.ts +365 -1
  251. package/tests/gentle-shell-bundled.test.ts +91 -5
  252. package/tests/gentle-shell-launcher.test.ts +1 -1
  253. package/tests/gentle-shell.test.ts +118 -87
  254. package/tests/gentle-todo.test.ts +32 -9
  255. package/tests/hidden-tools.test.ts +188 -0
  256. package/tests/independent-recovery-delivery.test.ts +19 -5
  257. package/tests/inprocess-reviewer.test.ts +73 -0
  258. package/tests/install-wizard.test.ts +27 -1
  259. package/tests/installer-downloads.test.ts +30 -1
  260. package/tests/installer-posix-bootstrap.test.ts +114 -13
  261. package/tests/installer-preflight.test.ts +49 -1
  262. package/tests/installer-probes.test.ts +146 -0
  263. package/tests/installer-server.test.ts +203 -4
  264. package/tests/installer-windows-bootstrap.test.ts +19 -1
  265. package/tests/judgment-day-severity-admission.test.ts +46 -0
  266. package/tests/lazy-module-contradictions-contract.test.ts +158 -0
  267. package/tests/maintainer/desktop-rpc.maintest.ts +632 -0
  268. package/tests/maintainer/pi-update-source.maintest.ts +48 -18
  269. package/tests/model-fallback-policy.test.ts +26 -7
  270. package/tests/nan-provider-runtime.test.ts +17 -3
  271. package/tests/nan-provider.test.ts +111 -56
  272. package/tests/native-review-capability-contract.test.ts +11 -1
  273. package/tests/native-review-cli-nonblocking-findings.test.ts +165 -0
  274. package/tests/native-review-parity.test.ts +24 -5
  275. package/tests/native-review-refusal-identity.test.ts +25 -0
  276. package/tests/no-self-pause-contract.test.ts +11 -3
  277. package/tests/odd-integration.test.ts +11 -3
  278. package/tests/odd-routing-contract.test.ts +80 -28
  279. package/tests/orchestrator-budget.test.ts +30 -5
  280. package/tests/orchestrator-consultation-sdk.test.ts +32 -6
  281. package/tests/orchestrator-delegation-mode.test.ts +2 -1
  282. package/tests/orchestrator-discovery.test.ts +28 -0
  283. package/tests/orchestrator-prompt-budget.test.ts +11 -2
  284. package/tests/orchestrator-prompt-diet-contract.test.ts +221 -0
  285. package/tests/orchestrator-rdd-ownership.test.ts +2 -1
  286. package/tests/orchestrator-work-search.test.ts +4 -2
  287. package/tests/package-files.test.ts +25 -1
  288. package/tests/package-manifest.test.ts +11 -10
  289. package/tests/parallel-reason-contract.test.ts +6 -3
  290. package/tests/permission-allowlist.test.ts +200 -30
  291. package/tests/persona-neutral-voseo.test.ts +4 -4
  292. package/tests/persona-reply-language.test.ts +1 -1
  293. package/tests/persona-single-channel.test.ts +13 -5
  294. package/tests/pi-update-launcher.test.ts +17 -7
  295. package/tests/pi-update-source.test.ts +113 -6
  296. package/tests/pi-update.test.ts +294 -19
  297. package/tests/pnpm-workspace-policy.test.ts +47 -0
  298. package/tests/primary-context-files.test.ts +233 -0
  299. package/tests/primary-context-three-files.test.ts +174 -0
  300. package/tests/provider-defect-handoff.test.ts +9 -2
  301. package/tests/rdd-aware-verification-contract.test.ts +1 -1
  302. package/tests/rdd-status-line.test.ts +94 -1
  303. package/tests/reply-language-anchor-placement.test.ts +184 -0
  304. package/tests/reply-language-anchor.test.ts +17 -1
  305. package/tests/request-context-append-only.test.ts +218 -0
  306. package/tests/request-context-placement.test.ts +148 -0
  307. package/tests/review-agent-end-preflight.test.ts +79 -1
  308. package/tests/review-candidate-view.test.ts +65 -0
  309. package/tests/review-continuation-registry.test.ts +31 -0
  310. package/tests/review-contract-prompt.test.ts +1 -1
  311. package/tests/review-controller.test.ts +2 -1
  312. package/tests/review-coordinator-correction-gate.test.ts +105 -0
  313. package/tests/review-coordinator-findings.test.ts +206 -0
  314. package/tests/review-coordinator-nonblocking-scope.test.ts +169 -0
  315. package/tests/review-coordinator.test.ts +271 -4
  316. package/tests/review-delivery-preflight.test.ts +462 -0
  317. package/tests/review-due-compaction.test.ts +31 -0
  318. package/tests/review-due-public-boundary.test.ts +26 -0
  319. package/tests/review-integration-nonblocking-findings.test.ts +108 -0
  320. package/tests/review-json-arguments.test.ts +41 -2
  321. package/tests/review-ledger-contract.test.ts +19 -40
  322. package/tests/review-loadout-rdd-off-sdk.test.ts +30 -1
  323. package/tests/review-one-call-findings.test.ts +131 -0
  324. package/tests/review-one-call-followups.test.ts +308 -0
  325. package/tests/review-one-call-reviewer-requests.test.ts +207 -0
  326. package/tests/review-one-call.test.ts +452 -0
  327. package/tests/review-relay-transport-agent.test.ts +28 -1
  328. package/tests/review-reviewer-evidence.test.ts +41 -1
  329. package/tests/review-risk-assessment.test.ts +52 -5
  330. package/tests/review-run-statement-guidance-independent.test.ts +54 -0
  331. package/tests/review-session-standing-permission-controller.test.ts +32 -2
  332. package/tests/review-tool-prose-budget.test.ts +1 -0
  333. package/tests/reviewer-stream.test.ts +149 -0
  334. package/tests/session-profile-extension.test.ts +2 -2
  335. package/tests/shell-prompt.test.ts +17 -0
  336. package/tests/shell-usage.test.ts +59 -10
  337. package/tests/skill-contradictions-contract.test.ts +122 -0
  338. package/tests/skill-registry-watcher.test.ts +216 -2
  339. package/tests/skill-registry.test.ts +929 -306
  340. package/tests/support/design-canvas-dom.ts +369 -0
  341. package/tests/support/review-coordinator-runtime.ts +212 -17
  342. package/tests/task-size-routing-contract.test.ts +42 -11
  343. package/tests/test-strength-contract.test.ts +2 -1
  344. package/tests/todo-request-append-only.test.ts +214 -0
  345. package/tests/tool-batching-contract.test.ts +3 -1
  346. package/tests/update-agent-body-history.test.ts +138 -0
  347. package/tests/verification-tiers-contract.test.ts +229 -0
  348. package/tests/verifier-preparation.test.ts +229 -0
  349. package/tests/verify-agent-contract.test.ts +20 -2
  350. package/tests/verify-first-launch-contract.test.ts +87 -11
  351. package/tests/vim-editor-adapter.test.ts +2 -2
  352. package/tests/work-continuity-contract.test.ts +54 -11
  353. package/tests/writer-admission-messages.test.ts +232 -0
  354. package/tests/writer-batch-admission.test.ts +66 -0
  355. package/tests/writer-edit-surface-scope.test.ts +52 -20
  356. package/tests/writer-feature-document-admission.test.ts +184 -0
  357. package/tests/yolo-mode.test.ts +39 -0
  358. package/skills/_shared/review-ledger-contract.md +0 -106
  359. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/README.md +0 -0
  360. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/lens.schema.json +0 -0
  361. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/refuter.schema.json +0 -0
  362. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/targeted-validator.schema.json +0 -0
  363. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/lens.json +0 -0
  364. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/refuter.json +0 -0
  365. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/targeted-validator.json +0 -0
@@ -0,0 +1,1168 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFileSync } from "node:fs";
3
+ import test from "node:test";
4
+ import { fileURLToPath } from "node:url";
5
+ import { DESIGN_CANVAS_ASSETS } from "../lib/design-canvas-assets.ts";
6
+ import { injectInspector } from "../lib/design-canvas-server.ts";
7
+ import { boardsOf, click, findAll, flush, handoffDoc, inspectorPick, loadCanvas, read, texts, withClass, type FakeElement } from "./support/design-canvas-dom.ts";
8
+
9
+ // Export (canvas-export.js): a ⋯ button in each design artboard's header opens the shared
10
+ // menu (canvas-menu.js) with the export items only: Export as PNG (the browser's tab
11
+ // capture, cropped to the artboard), at 2×, Export as PDF (the print dialog) and Download
12
+ // HTML (the file without the injected inspector). Nothing is uploaded: PDF and HTML only
13
+ // read the artboard file from the canvas server. Every
14
+ // assertion compares strings, numbers or booleans, never fake elements, which node:assert
15
+ // would walk whole on a failure.
16
+
17
+ const SYSTEM_REPLY = { "/t/api/system": { exists: true, file: "system.html", width: 800, height: 600 } };
18
+ const EXPORT_ITEMS = ["Export as PNG", "Export as PNG at 2×", "Export as PDF", "Download HTML"];
19
+ const ARTBOARD_URL = "/t/files/alpha/01-a.html";
20
+
21
+ async function loadExport(replies: Record<string, unknown> = {}, extraWindow: Record<string, unknown> = {}, config: Record<string, unknown> = {}) {
22
+ const canvas = await loadCanvas(300, replies, config, extraWindow);
23
+ // The fake DOM starts every element visible; index.html starts these hidden.
24
+ for (const id of ["gd-popover", "gd-menu", "gd-device-menu"]) canvas.document.getElementById(id).hidden = true;
25
+ return canvas;
26
+ }
27
+ type Canvas = Awaited<ReturnType<typeof loadExport>>;
28
+
29
+ const $ = (canvas: Canvas, id: string) => canvas.document.getElementById(id);
30
+ const keyOn = (target: FakeElement, key: string) => target.dispatch("keydown", { key, shiftKey: false });
31
+ const isActive = (canvas: Canvas, element: FakeElement | undefined) => canvas.document.activeElement === element;
32
+ const menuEl = (canvas: Canvas) => $(canvas, "gd-menu");
33
+ const menuItems = (canvas: Canvas) => findAll(menuEl(canvas), (element) => element.getAttribute("role") === "menuitem");
34
+ const itemLabels = (canvas: Canvas) => menuItems(canvas).map((item) => texts(item, "gd-menu-label")[0]);
35
+ const itemNamed = (canvas: Canvas, label: string) => menuItems(canvas).find((item) => texts(item, "gd-menu-label")[0] === label)!;
36
+ const menuButtonOf = (wrapper: FakeElement) => withClass(wrapper, "gd-menu-button")[0];
37
+ /** Opens the ⋯ menu of the design artboard `index` and returns its button. */
38
+ const openMenu = (canvas: Canvas, index = 0) => {
39
+ const button = menuButtonOf(canvas.boards[index].wrapper);
40
+ button.dispatch("click");
41
+ return button;
42
+ };
43
+ const choose = (canvas: Canvas, label: string, index = 0) => {
44
+ openMenu(canvas, index);
45
+ itemNamed(canvas, label).dispatch("click");
46
+ };
47
+ const settle = async (times = 8) => { for (let i = 0; i < times; i++) await flush(); };
48
+ const statusText = (canvas: Canvas) => $(canvas, "gd-status").textContent;
49
+ const statusIsError = (canvas: Canvas) => $(canvas, "gd-status").classes.has("gd-error");
50
+ const toastText = (canvas: Canvas) => $(canvas, "gd-toast").textContent;
51
+ /** A key press delivered to the document's keydown listeners, as the browser would from `target`. */
52
+ function press(canvas: Canvas, key: string, target: FakeElement) {
53
+ const event: any = { key, shiftKey: false, ctrlKey: false, metaKey: false, altKey: false, target, defaultPrevented: false, preventDefault() { event.defaultPrevented = true; } };
54
+ for (const listener of canvas.document.listeners.get("keydown") ?? []) listener(event);
55
+ return event;
56
+ }
57
+
58
+ // ---- the ⋯ menu (S7: the export items only)
59
+
60
+ test("each design artboard has a ⋯ menu button named after it beside Implement this, collapsed; the system board has none", async () => {
61
+ const canvas = await loadExport(SYSTEM_REPLY);
62
+ const [system, first, second] = boardsOf(canvas);
63
+ assert.equal(withClass(system, "gd-menu-button").length, 0, "the system board has no menu");
64
+ for (const [wrapper, title] of [[first, "First"], [second, "Second"]] as const) {
65
+ const buttons = withClass(wrapper, "gd-menu-button");
66
+ assert.equal(buttons.length, 1);
67
+ const button = buttons[0];
68
+ assert.equal(button.localName, "button");
69
+ assert.equal((button as unknown as { type?: string }).type, "button");
70
+ assert.equal(button.getAttribute("aria-label"), `More actions for ${title}`);
71
+ assert.equal(button.getAttribute("aria-haspopup"), "menu");
72
+ assert.equal(button.getAttribute("aria-expanded"), "false");
73
+ assert.equal(button.getAttribute("aria-controls"), "gd-menu");
74
+ assert.equal(button.textContent, "", "an icon, not text");
75
+ assert.equal(withClass(button, "gd-i")[0].children[0].getAttribute("href"), "#i-more");
76
+ assert.ok(withClass(wrapper, "gd-board-actions")[0].contains(button), "in the header's actions, beside Implement this");
77
+ }
78
+ assert.equal(menuEl(canvas).hidden, true);
79
+ });
80
+
81
+ test("S7: the menu lists only the export items, marks the button expanded, focuses the first item and toggles from the button", async () => {
82
+ const canvas = await loadExport();
83
+ const button = openMenu(canvas, 1);
84
+ assert.equal(menuEl(canvas).hidden, false);
85
+ assert.equal(button.getAttribute("aria-expanded"), "true");
86
+ assert.equal(menuEl(canvas).getAttribute("aria-label"), "Second actions");
87
+ assert.deepEqual(itemLabels(canvas), EXPORT_ITEMS);
88
+ assert.deepEqual(menuItems(canvas).map((item) => withClass(item, "gd-i")[0].children[0].getAttribute("href")), ["#i-image", "#i-image", "#i-file", "#i-download"]);
89
+ assert.equal(withClass(menuEl(canvas), "gd-menu-separator").length, 0);
90
+ assert.ok(menuItems(canvas).every((item) => item.localName === "button" && item.getAttribute("tabindex") === "-1"));
91
+ assert.ok(isActive(canvas, menuItems(canvas)[0]));
92
+ button.dispatch("click");
93
+ assert.equal(menuEl(canvas).hidden, true);
94
+ assert.equal(button.getAttribute("aria-expanded"), "false");
95
+ assert.ok(isActive(canvas, button), "closing with the button keeps focus on it");
96
+ });
97
+
98
+ test("S7: an implemented artboard with a running app still gets only the export items: no Compare, Implement or another direction", async () => {
99
+ const canvas = await loadExport({ "/t/api/designs/alpha/handoffs": handoffDoc("01-a.html", { "01-a.html": { status: "implemented", previewUrl: "http://localhost:3000/" } }) });
100
+ openMenu(canvas, 0);
101
+ assert.deepEqual(itemLabels(canvas), EXPORT_ITEMS);
102
+ assert.equal(withClass(canvas.boards[0].wrapper, "gd-compare-start").length, 1, "Compare stays where it was, in the handoff row");
103
+ });
104
+
105
+ test("the keyboard opens the menu with the arrows, and moves with arrows, Home and End", async () => {
106
+ const canvas = await loadExport();
107
+ const button = menuButtonOf(canvas.boards[0].wrapper);
108
+ const down = keyOn(button, "ArrowDown");
109
+ assert.equal(down.defaultPrevented, true);
110
+ assert.equal(menuEl(canvas).hidden, false);
111
+ assert.ok(isActive(canvas, menuItems(canvas)[0]));
112
+ keyOn(button, "Escape");
113
+ assert.equal(menuEl(canvas).hidden, true);
114
+ keyOn(button, "ArrowUp");
115
+ const items = menuItems(canvas);
116
+ assert.ok(isActive(canvas, items[items.length - 1]), "ArrowUp opens on the last item");
117
+ const at = () => items.findIndex((item) => item === canvas.document.activeElement);
118
+ keyOn(items[at()], "ArrowDown");
119
+ assert.equal(at(), 0, "ArrowDown wraps to the first");
120
+ keyOn(items[at()], "ArrowUp");
121
+ assert.equal(at(), items.length - 1, "ArrowUp wraps to the last");
122
+ keyOn(items[at()], "Home");
123
+ assert.equal(at(), 0);
124
+ keyOn(items[at()], "End");
125
+ assert.equal(at(), items.length - 1);
126
+ assert.equal(menuEl(canvas).hidden, false, "moving never closes it");
127
+ });
128
+
129
+ test("Enter and Space on an item choose it; Escape returns focus to the button; Tab closes", async () => {
130
+ let printed = 0;
131
+ const canvas = await loadExport({}, { print: () => printed++ });
132
+ const button = openMenu(canvas, 0);
133
+ const escape = keyOn(menuItems(canvas)[1], "Escape");
134
+ assert.equal(escape.defaultPrevented, true);
135
+ assert.equal(menuEl(canvas).hidden, true);
136
+ assert.equal(button.getAttribute("aria-expanded"), "false");
137
+ assert.ok(isActive(canvas, button), "Esc returns focus to the button");
138
+
139
+ for (const key of ["Enter", " "]) {
140
+ openMenu(canvas, 0);
141
+ const chosen = keyOn(itemNamed(canvas, "Export as PDF"), key);
142
+ assert.equal(chosen.defaultPrevented, true, key);
143
+ assert.equal(menuEl(canvas).hidden, true, key);
144
+ assert.equal(withClass(canvas.document.body, "gd-print").length, 1, `${key} chose Export as PDF`);
145
+ }
146
+
147
+ openMenu(canvas, 0);
148
+ const tab = keyOn(menuItems(canvas)[0], "Tab");
149
+ assert.equal(tab.defaultPrevented, false, "Tab keeps its move");
150
+ assert.equal(menuEl(canvas).hidden, true);
151
+ assert.equal(button.getAttribute("aria-expanded"), "false");
152
+ assert.equal(printed, 0);
153
+ });
154
+
155
+ test("a press outside, a pan or zoom, or opening another artboard's menu closes it; a press inside does not", async () => {
156
+ const canvas = await loadExport();
157
+ const first = openMenu(canvas, 0);
158
+ const pointerdown = (target: FakeElement) => (canvas.document.listeners.get("pointerdown") ?? []).forEach((listener) => listener({ target, button: 0 }));
159
+ pointerdown(menuItems(canvas)[0]);
160
+ assert.equal(menuEl(canvas).hidden, false, "inside the menu");
161
+ pointerdown(first);
162
+ assert.equal(menuEl(canvas).hidden, false, "the button toggles on its own click, not on pointerdown");
163
+ pointerdown(canvas.viewport);
164
+ assert.equal(menuEl(canvas).hidden, true, "outside");
165
+ assert.equal(first.getAttribute("aria-expanded"), "false");
166
+
167
+ openMenu(canvas, 0);
168
+ canvas.viewport.dispatch("keydown", { key: "+" });
169
+ assert.equal(menuEl(canvas).hidden, true, "a zoom closes it: the button moved away from under the menu");
170
+ openMenu(canvas, 0);
171
+ canvas.viewport.dispatch("wheel", { deltaX: 0, deltaY: 40, deltaMode: 0, ctrlKey: false, metaKey: false, shiftKey: false, clientX: 300, clientY: 300 });
172
+ assert.equal(menuEl(canvas).hidden, true, "a pan closes it");
173
+
174
+ const one = openMenu(canvas, 0);
175
+ const two = openMenu(canvas, 1);
176
+ assert.equal(one.getAttribute("aria-expanded"), "false");
177
+ assert.equal(two.getAttribute("aria-expanded"), "true");
178
+ assert.equal(menuEl(canvas).getAttribute("aria-label"), "Second actions");
179
+ });
180
+
181
+ test("the Settings menu and the device menu stay open through a pan: only an artboard's menu follows its button", async () => {
182
+ const canvas = await loadExport();
183
+ $(canvas, "gd-rail-settings").dispatch("click");
184
+ assert.equal(menuEl(canvas).hidden, false);
185
+ canvas.viewport.dispatch("keydown", { key: "+" });
186
+ assert.equal(menuEl(canvas).hidden, false, "Settings sits on the rail, which never moves");
187
+ });
188
+
189
+ test("single-key shortcuts stay off while the menu is open", async () => {
190
+ const canvas = await loadExport();
191
+ openMenu(canvas, 0);
192
+ const before = $(canvas, "gd-comment").getAttribute("aria-pressed");
193
+ press(canvas, "c", menuItems(canvas)[0]);
194
+ assert.equal($(canvas, "gd-comment").getAttribute("aria-pressed"), before, "C did nothing");
195
+ keyOn(menuItems(canvas)[0], "Escape");
196
+ press(canvas, "c", canvas.document.body);
197
+ assert.equal($(canvas, "gd-comment").getAttribute("aria-pressed"), "true", "back to normal after it closes");
198
+ });
199
+
200
+ test("the menu is measured at a neutral position, so a stale position cannot push it off the right edge", async () => {
201
+ const canvas = await loadExport();
202
+ const menu = menuEl(canvas);
203
+ // Like a fixed box without a width: it shrinks to the room right of its left edge, up to its content width.
204
+ Object.defineProperty(menu, "offsetWidth", { get: () => Math.min(500, 1200 - (parseFloat(menu.style.left) || 0)) });
205
+ menu.style.left = "1100px";
206
+ const button = menuButtonOf(canvas.boards[0].wrapper);
207
+ // A DOMRect also has right and bottom; placeMenu reads bottom.
208
+ button.rect = { left: 1150, top: 40, width: 28, height: 28, right: 1178, bottom: 68 } as FakeElement["rect"];
209
+ button.dispatch("click");
210
+ assert.equal(parseFloat(menu.style.left), 1200 - 500 - 12);
211
+ assert.equal(menu.style.top, "72px", "under the button");
212
+ });
213
+
214
+ test("a design reload closes an open artboard menu: its artboard is gone", async () => {
215
+ const canvas = await loadExport();
216
+ openMenu(canvas, 0);
217
+ await canvas.serverEvent("change", { slug: "alpha", file: "design.json" });
218
+ assert.equal(menuEl(canvas).hidden, true);
219
+ });
220
+
221
+ // ---- Export as PNG
222
+
223
+ type PngLog = { calls: string[]; draw: number[][]; names: string[]; during: Array<{ exporting: boolean; transform: string; width: string; height: string; highlight: string; mode: string }>; output: { width: number; height: number } | null; statusAtCapture: string[]; timeouts: number[] };
224
+
225
+ /**
226
+ * The canvas with a tab capture that hands back one 1200 x 800 frame (this window at 1×) and a canvas that records what it draws.
227
+ * `stalled`: the video never paints a new frame (sharing stopped); `setTimeout` then runs at once and logs its delay.
228
+ * `frozen`: the video never paints a new frame and no timer ever fires, so only the track's `ended` event can end the waits.
229
+ * `permission`: the capture's answer waits for it, like the browser's selector; a rejection is a denial.
230
+ * `ended`: the track has already ended when the capture is granted (an inactive stream).
231
+ * `replies`: more server replies, such as the design's comments.
232
+ * `track.end()` ends the shared track like the browser's Stop sharing: readyState "ended", then its `ended` event.
233
+ * `held`: the video paints its new frames only once `releaseFrames()` is called.
234
+ * `during[].highlight` is what the first artboard's inspector last heard about its highlight when the frame was grabbed,
235
+ * `during[].mode` what it last heard about comment mode.
236
+ */
237
+ async function pngCanvas(extra: { surface?: string; play?: () => Promise<void>; frame?: { width: number; height: number }; stalled?: boolean; frozen?: boolean; held?: boolean; permission?: Promise<void>; ended?: boolean; replies?: Record<string, unknown> } = {}) {
238
+ const log: PngLog = { calls: [], draw: [], names: [], during: [], output: null, statusAtCapture: [], timeouts: [] };
239
+ const endedListeners: Array<() => void> = [];
240
+ let holding = extra.held === true;
241
+ const heldFrames: Array<() => void> = [];
242
+ const releaseFrames = () => { holding = false; heldFrames.splice(0).forEach((done) => done()); };
243
+ const track = {
244
+ readyState: extra.ended ? "ended" : "live",
245
+ stop: () => log.calls.push("stop"),
246
+ getSettings: () => (extra.surface ? { displaySurface: extra.surface } : {}),
247
+ addEventListener: (type: string, listener: () => void) => { if (type === "ended") endedListeners.push(listener); },
248
+ end() { track.readyState = "ended"; endedListeners.splice(0).forEach((listener) => listener()); },
249
+ };
250
+ const stream = { getTracks: () => [track], getVideoTracks: () => [track] };
251
+ let status: FakeElement | null = null;
252
+ const canvas = await loadExport(extra.replies ?? {}, {
253
+ confirm: () => { log.calls.push("confirm"); return true; },
254
+ navigator: { mediaDevices: { getDisplayMedia: async (options: unknown) => {
255
+ log.calls.push(`capture ${JSON.stringify(options)}`);
256
+ log.statusAtCapture.push(status!.textContent);
257
+ if (extra.permission) await extra.permission;
258
+ return stream;
259
+ } } },
260
+ URL: { createObjectURL: () => { log.calls.push("url"); return "blob:test"; }, revokeObjectURL: () => log.calls.push("revoke") },
261
+ ...(extra.stalled ? { setTimeout: (callback: () => void, ms?: number) => { log.timeouts.push(ms ?? 0); const timer = setTimeout(callback, 0); timer.unref(); return timer; } } : {}),
262
+ ...(extra.frozen ? { setTimeout: (_callback: () => void, ms?: number) => { log.timeouts.push(ms ?? 0); return 0; } } : {}),
263
+ });
264
+ status = $(canvas, "gd-status");
265
+ const frame = extra.frame ?? { width: 400, height: 300 };
266
+ canvas.boards[0].frame.rect = { left: 100, top: 100, ...frame };
267
+ const document = canvas.document as any;
268
+ const create = document.createElement.bind(document);
269
+ document.createElement = (tag: string) => {
270
+ if (tag === "video") return { videoWidth: 1200, videoHeight: 800, play: extra.play ?? (async () => { log.calls.push("play"); }), requestVideoFrameCallback: (done: () => void) => {
271
+ log.calls.push("frame");
272
+ if (holding) heldFrames.push(done);
273
+ else if (!extra.stalled && !extra.frozen) done();
274
+ } };
275
+ if (tag === "canvas") {
276
+ const output: any = {
277
+ width: 0,
278
+ height: 0,
279
+ getContext: () => ({ drawImage: (_video: unknown, ...args: number[]) => {
280
+ log.draw.push(args);
281
+ log.during.push({ exporting: canvas.document.body.classes.has("gd-exporting"), transform: canvas.world.style.transform, width: canvas.boards[0].frame.style.width, height: canvas.boards[0].frame.style.height, highlight: lastHighlight(canvas.boards[0].frame), mode: lastMode(canvas.boards[0].frame) });
282
+ log.calls.push("draw");
283
+ } }),
284
+ toBlob: (done: (blob: object) => void) => { log.calls.push("encode"); done({}); },
285
+ };
286
+ log.output = output;
287
+ return output;
288
+ }
289
+ if (tag === "a") return { click() { log.names.push(this.download); }, href: "", download: "" };
290
+ return create(tag);
291
+ };
292
+ return { canvas, log, track, releaseFrames };
293
+ }
294
+
295
+ /** The last highlight message an artboard frame got: "gd:highlight <id>", "gd:clear" or "" for none. */
296
+ function lastHighlight(frame: FakeElement) {
297
+ const last = frame.contentWindow!.posted.filter((message) => message.type === "gd:highlight" || message.type === "gd:clear").at(-1);
298
+ return last ? `${last.type}${last.id ? ` ${last.id}` : ""}` : "";
299
+ }
300
+
301
+ /** What an artboard frame last heard about comment mode: "on", "off" or "" for nothing. */
302
+ function lastMode(frame: FakeElement) {
303
+ const last = frame.contentWindow!.posted.filter((message) => message.type === "gd:mode").at(-1);
304
+ return last ? (last.enabled ? "on" : "off") : "";
305
+ }
306
+
307
+ for (const [name, navigator] of [
308
+ ["missing", undefined],
309
+ ["denied", { mediaDevices: { getDisplayMedia: async () => { throw new Error("Permission denied."); } } }],
310
+ ] as const) test(`a ${name} tab capture says so on the status line and the toast, and suggests the browser screenshot tool`, async () => {
311
+ const canvas = await loadExport({}, { navigator });
312
+ const before = canvas.world.style.transform;
313
+ choose(canvas, "Export as PNG");
314
+ await settle();
315
+ const reason = name === "missing" ? "Tab capture is not available in this browser." : "Permission denied.";
316
+ assert.equal(statusText(canvas), `Could not export the artboard. ${reason} Use your browser's screenshot tool instead.`);
317
+ assert.equal(statusIsError(canvas), true);
318
+ assert.equal(toastText(canvas), statusText(canvas));
319
+ assert.equal($(canvas, "gd-toast").hidden, false);
320
+ assert.equal(canvas.world.style.transform, before);
321
+ assert.equal(canvas.navMode.textContent, "Navigating");
322
+ assert.deepEqual(canvas.posts, []);
323
+ });
324
+
325
+ const CHOOSE_TAB = "Choose this canvas tab in the browser's capture selector. Choosing another tab or screen may export the wrong content.";
326
+
327
+ for (const scale of [1, 2]) test(`export ${scale}× warns about the tab on the status line, crops this tab's frame to the artboard at 100% and stops the capture`, async () => {
328
+ const { canvas, log } = await pngCanvas();
329
+ const before = canvas.world.style.transform;
330
+ choose(canvas, scale === 1 ? "Export as PNG" : "Export as PNG at 2×");
331
+ await settle();
332
+ assert.equal(log.calls[0], 'capture {"video":{"displaySurface":"browser"},"audio":false,"preferCurrentTab":true}');
333
+ assert.deepEqual(log.statusAtCapture, [CHOOSE_TAB], "the status line names the tab to choose while the selector is open");
334
+ assert.deepEqual(log.draw, [[100, 100, 400, 300, 0, 0, 400 * scale, 300 * scale]]);
335
+ assert.deepEqual(log.names, [`01-a${scale === 2 ? "@2x" : ""}.png`]);
336
+ assert.equal(log.output?.width, 400 * scale);
337
+ assert.equal(log.output?.height, 300 * scale);
338
+ assert.equal(log.calls.filter((call) => call === "stop").length, 1);
339
+ assert.ok(log.calls.indexOf("stop") < log.calls.indexOf("encode"), "the capture stops right after the frame is grabbed");
340
+ assert.ok(log.calls.indexOf("frame") > log.calls.indexOf("play") && log.calls.indexOf("frame") < log.calls.indexOf("draw"), "the frame drawn is a new one, painted after the layout");
341
+ assert.ok(log.calls.indexOf("revoke") > log.calls.indexOf("url"), "the download link is released");
342
+ assert.equal(log.during.length, 1);
343
+ assert.equal(log.during[0].exporting, true, "the canvas chrome is hidden while the frame is grabbed");
344
+ assert.match(log.during[0].transform, /scale\(1\)$/, "the artboard is at 100%");
345
+ assert.deepEqual([log.during[0].width, log.during[0].height], ["400px", "300px"], "at its own size, not Desktop's window width (canvas-layout S8)");
346
+ assert.equal(canvas.document.body.classes.has("gd-exporting"), false, "the chrome comes back");
347
+ assert.equal(canvas.world.style.transform, before, "the view comes back");
348
+ assert.equal(canvas.navMode.textContent, "Navigating", "and so does navigation mode");
349
+ assert.equal(canvas.boards[0].frame.style.width, "400px");
350
+ assert.equal(toastText(canvas), scale === 2 ? "Exported PNG at 2× (upscaled)." : "Exported PNG.", "1× pixels upscaled to 2× say so");
351
+ assert.equal(statusText(canvas), toastText(canvas), "the tab warning gives way to the result");
352
+ assert.equal(statusIsError(canvas), false);
353
+ assert.deepEqual(canvas.posts, []);
354
+ });
355
+
356
+ test("D1: Export as PNG asks for the capture at once, from the menu click: no confirm dialog spends the click's activation", async () => {
357
+ const { canvas, log } = await pngCanvas();
358
+ choose(canvas, "Export as PNG");
359
+ assert.deepEqual(log.calls.slice(0, 1), ['capture {"video":{"displaySurface":"browser"},"audio":false,"preferCurrentTab":true}'], "the capture starts within the click itself");
360
+ await settle();
361
+ assert.equal(log.calls.includes("confirm"), false, "no blocking dialog before the capture");
362
+ assert.deepEqual(log.statusAtCapture, [CHOOSE_TAB]);
363
+ });
364
+
365
+ test("D4: a capture that stops painting frames gives up waiting after 500 ms and still exports and restores the canvas", async () => {
366
+ const { canvas, log } = await pngCanvas({ stalled: true });
367
+ const before = canvas.world.style.transform;
368
+ choose(canvas, "Export as PNG");
369
+ await settle(16);
370
+ assert.equal(log.calls.filter((call) => call === "frame").length, 2, "both frame waits were asked for");
371
+ assert.equal(log.timeouts.filter((ms) => ms === 500).length, 2, "each bounded by 500 ms");
372
+ assert.deepEqual(log.draw, [[100, 100, 400, 300, 0, 0, 400, 300]]);
373
+ assert.deepEqual(log.names, ["01-a.png"]);
374
+ assert.equal(canvas.document.body.classes.has("gd-exporting"), false, "the chrome comes back");
375
+ assert.equal(canvas.world.style.transform, before);
376
+ assert.equal(canvas.navMode.textContent, "Navigating");
377
+ });
378
+
379
+ // #3153 review, case 2: sharing that ends without a frame must end the export and give the canvas back.
380
+
381
+ const STOPPED = "Could not export the artboard. Sharing stopped before the artboard was captured. Use your browser's screenshot tool instead.";
382
+
383
+ test("#3153 case 2: no frame callback, then the track's ended event: the export ends at once with a reason and restores the canvas", async () => {
384
+ const { canvas, log, track } = await pngCanvas({ frozen: true });
385
+ const before = canvas.world.style.transform;
386
+ choose(canvas, "Export as PNG");
387
+ await settle();
388
+ assert.equal(log.calls.filter((call) => call === "frame").length, 1, "waiting for the first new frame");
389
+ assert.equal(canvas.document.body.classes.has("gd-exporting"), true, "still waiting, no timer fired");
390
+ track.end();
391
+ await settle();
392
+ assert.deepEqual(log.draw, [], "nothing grabbed");
393
+ assert.deepEqual(log.names, [], "nothing downloaded");
394
+ assert.equal(log.calls.filter((call) => call === "stop").length, 1, "the capture is stopped once");
395
+ assert.equal(canvas.document.body.classes.has("gd-exporting"), false, "the chrome comes back");
396
+ assert.equal(canvas.world.style.transform, before, "the view comes back");
397
+ assert.equal(canvas.navMode.textContent, "Navigating", "the artboard it opened is closed again");
398
+ assert.equal(statusText(canvas), STOPPED);
399
+ assert.equal(statusIsError(canvas), true);
400
+ assert.equal(toastText(canvas), STOPPED);
401
+ });
402
+
403
+ test("#3153 case 2: a capture whose track has already ended when it is granted (an inactive stream) exports nothing and never opens the artboard", async () => {
404
+ const { canvas, log } = await pngCanvas({ frozen: true, ended: true });
405
+ const before = canvas.world.style.transform;
406
+ choose(canvas, "Export as PNG");
407
+ await settle();
408
+ assert.equal(log.calls.includes("frame"), false, "no frame is waited for");
409
+ assert.deepEqual(log.draw, []);
410
+ assert.equal(log.calls.filter((call) => call === "stop").length, 1);
411
+ assert.equal(canvas.document.body.classes.has("gd-exporting"), false);
412
+ assert.equal(canvas.world.style.transform, before);
413
+ assert.equal(canvas.navMode.textContent, "Navigating");
414
+ assert.equal(statusText(canvas), STOPPED);
415
+ });
416
+
417
+ // #3153 review, case 1: a design.json reload while the capture's permission is pending replaces every board object.
418
+
419
+ /** Focuses the first artboard, starts a PNG export whose permission waits, then reloads design.json; returns how to answer. */
420
+ async function exportAcrossReload(focused: boolean, replies: Record<string, unknown> = {}) {
421
+ let grant!: () => void;
422
+ let deny!: (error: Error) => void;
423
+ const permission = new Promise<void>((resolve, reject) => { grant = resolve; deny = reject; });
424
+ permission.catch(() => {});
425
+ const { canvas, log } = await pngCanvas({ permission });
426
+ if (focused) click(canvas.boards[0].shield!, 200, 200);
427
+ const view = canvas.world.style.transform;
428
+ choose(canvas, "Export as PNG");
429
+ await settle();
430
+ assert.equal(log.calls.filter((call) => call.startsWith("capture ")).length, 1, "the browser's selector is open");
431
+ Object.assign(canvas.replies, replies);
432
+ await canvas.serverEvent("change", { slug: "alpha", file: "design.json" });
433
+ // A replaced board leaves the page: like a browser, its frame no longer has a box.
434
+ canvas.boards[0].frame.rect = { left: 0, top: 0, width: 0, height: 0 };
435
+ const current = boardsOf(canvas);
436
+ assert.ok(current.every((wrapper) => !canvas.boards.some((old) => old.wrapper === wrapper)), "the reload built new board objects");
437
+ return { canvas, log, view, current, grant, deny };
438
+ }
439
+
440
+ const frameOf = (wrapper: FakeElement) => findAll(wrapper, (element) => element.localName === "iframe")[0];
441
+
442
+ test("#3153 case 1: focus, export with the permission pending, reload design.json, deny: the reloaded artboard is focused again, not the replaced one", async () => {
443
+ const { canvas, view, current, deny } = await exportAcrossReload(true);
444
+ assert.match(canvas.navMode.textContent, /^Using: First/, "the reload kept focus mode on the same file");
445
+ deny(new Error("Permission denied."));
446
+ await settle();
447
+ assert.equal(statusText(canvas), "Could not export the artboard. Permission denied. Use your browser's screenshot tool instead.");
448
+ assert.deepEqual(current.map((wrapper) => wrapper.classes.has("gd-focus-board")), [true, false], "the current First is the open artboard");
449
+ assert.deepEqual(current.map((wrapper) => wrapper.inert), [false, true], "only the other artboard is inert");
450
+ assert.match(canvas.navMode.textContent, /^Using: First/);
451
+ assert.equal(canvas.world.style.transform, view, "the focus view comes back");
452
+ assert.ok(isActive(canvas, menuButtonOf(current[0])), "keyboard focus on the current First's ⋯ button");
453
+ });
454
+
455
+ test("#3153 case 1: a capture granted after a design.json reload exports the reloaded artboard and gives it back focused", async () => {
456
+ const { canvas, log, view, current, grant } = await exportAcrossReload(true);
457
+ frameOf(current[0]).rect = { left: 100, top: 100, width: 400, height: 300 };
458
+ grant();
459
+ await settle();
460
+ assert.deepEqual(log.draw, [[100, 100, 400, 300, 0, 0, 400, 300]], "cropped from the current frame");
461
+ assert.deepEqual(log.names, ["01-a.png"]);
462
+ assert.equal(statusText(canvas), "Exported PNG.");
463
+ assert.deepEqual(current.map((wrapper) => wrapper.classes.has("gd-focus-board")), [true, false]);
464
+ assert.deepEqual(current.map((wrapper) => wrapper.inert), [false, true]);
465
+ assert.equal(canvas.world.style.transform, view);
466
+ assert.ok(isActive(canvas, menuButtonOf(current[0])));
467
+ });
468
+
469
+ test("#3153 case 1: when the reload removed the artboard, the export says so, grabs nothing and leaves the canvas navigating", async () => {
470
+ const manifest = { slug: "alpha", title: "Alpha", brief: "", artboards: [{ file: "02-b.html", title: "Second", tradeoff: "", width: 400, height: 300 }] };
471
+ const { canvas, log, view, current, grant } = await exportAcrossReload(false, { "/t/api/designs/alpha": manifest });
472
+ assert.equal(current.length, 1);
473
+ grant();
474
+ await settle();
475
+ assert.deepEqual(log.draw, []);
476
+ assert.equal(log.calls.filter((call) => call === "stop").length, 1);
477
+ assert.equal(statusText(canvas), "Could not export the artboard. The artboard is no longer in the design. Use your browser's screenshot tool instead.");
478
+ assert.equal(canvas.navMode.textContent, "Navigating");
479
+ assert.deepEqual(current.map((wrapper) => wrapper.inert), [false]);
480
+ assert.equal(canvas.document.body.classes.has("gd-exporting"), false);
481
+ assert.equal(canvas.world.style.transform, view);
482
+ });
483
+
484
+ test("#3153 case 1: when a reload removed the open artboard, the export leaves focus mode cleanly instead of reopening it", async () => {
485
+ const manifest = { slug: "alpha", title: "Alpha", brief: "", artboards: [{ file: "02-b.html", title: "Second", tradeoff: "", width: 400, height: 300 }] };
486
+ const { canvas, current, deny } = await exportAcrossReload(true, { "/t/api/designs/alpha": manifest });
487
+ assert.equal(canvas.navMode.textContent, "Navigating", "the reload already left focus mode");
488
+ const overview = canvas.world.style.transform;
489
+ deny(new Error("Permission denied."));
490
+ await settle();
491
+ assert.equal(canvas.navMode.textContent, "Navigating");
492
+ assert.deepEqual(current.map((wrapper) => wrapper.inert), [false]);
493
+ assert.equal(canvas.world.style.transform, overview, "the overview stays, not the old focus view");
494
+ });
495
+
496
+ test("D5: after a PNG export, focus is back on the artboard's ⋯ button", async () => {
497
+ const { canvas, log } = await pngCanvas();
498
+ const button = openMenu(canvas, 0);
499
+ itemNamed(canvas, "Export as PNG").dispatch("click");
500
+ await settle();
501
+ assert.equal(log.draw.length, 1, "it exported");
502
+ assert.ok(isActive(canvas, button), "not left on the viewport or the closed artboard");
503
+ });
504
+
505
+ test("an export from an open artboard at Phone size grabs it at its own size and gives it back at Phone, still open", async () => {
506
+ const { canvas, log } = await pngCanvas();
507
+ click(canvas.boards[0].shield!, 200, 200);
508
+ $(canvas, "gd-device").dispatch("click");
509
+ findAll($(canvas, "gd-device-menu"), (element) => element.dataset.size === "phone")[0].dispatch("click");
510
+ assert.equal(canvas.boards[0].frame.style.width, "390px");
511
+ const before = canvas.world.style.transform;
512
+ choose(canvas, "Export as PNG");
513
+ await settle();
514
+ assert.deepEqual([log.during[0].width, log.during[0].height], ["400px", "300px"], "Desktop's own size, not Phone's");
515
+ assert.match(canvas.navMode.textContent, /^Using: First/, "the artboard stays open");
516
+ assert.equal(canvas.boards[0].frame.style.width, "390px", "at Phone again");
517
+ assert.equal($(canvas, "gd-device-name").textContent, "Phone");
518
+ assert.equal(canvas.world.style.transform, before);
519
+ });
520
+
521
+ test("an export from All sizes grabs the artboard's own frame without the size frames and gives All sizes back", async () => {
522
+ const { canvas, log } = await pngCanvas();
523
+ click(canvas.boards[0].shield!, 200, 200);
524
+ $(canvas, "gd-device").dispatch("click");
525
+ findAll($(canvas, "gd-device-menu"), (element) => element.dataset.size === "all")[0].dispatch("click");
526
+ const sizeFrames = () => withClass(canvas.viewport, "gd-size-frame").length;
527
+ assert.equal(sizeFrames(), 3);
528
+ const during: number[] = [];
529
+ const document = canvas.document as any;
530
+ const create = document.createElement;
531
+ document.createElement = (tag: string) => {
532
+ if (tag === "video") during.push(sizeFrames());
533
+ return create(tag);
534
+ };
535
+ choose(canvas, "Export as PNG");
536
+ await settle();
537
+ assert.deepEqual(during, [0], "Desktop while the frame is grabbed: no size frames");
538
+ assert.deepEqual([log.during[0].width, log.during[0].height], ["400px", "300px"]);
539
+ assert.match(canvas.navMode.textContent, /^Using: First/, "the artboard stays open");
540
+ assert.equal($(canvas, "gd-device-name").textContent, "All sizes");
541
+ assert.equal(sizeFrames(), 3, "All sizes again");
542
+ assert.ok(canvas.boards[0].wrapper.classes.has("gd-all-sizes"));
543
+ });
544
+
545
+ test("E1: an export while the comment box is open on an All sizes frame closes it first: that frame clears its outline before it is removed", async () => {
546
+ const { canvas } = await pngCanvas();
547
+ click(canvas.boards[0].shield!, 200, 200);
548
+ $(canvas, "gd-device").dispatch("click");
549
+ findAll($(canvas, "gd-device-menu"), (element) => element.dataset.size === "all")[0].dispatch("click");
550
+ $(canvas, "gd-comment").dispatch("click");
551
+ const phoneSection = withClass(canvas.viewport, "gd-size-frame")[0];
552
+ const phone = findAll(phoneSection, (element) => element.localName === "iframe")[0];
553
+ canvas.message(phone.contentWindow, inspectorPick(phone, { type: "gd:pick", selector: "#cta", excerpt: "Buy", rect: { x: 1, y: 1, width: 10, height: 10 } }));
554
+ const popover = $(canvas, "gd-popover");
555
+ assert.equal(popover.hidden, false, "the comment box is open on the Phone frame");
556
+ // Whether the Phone frame was still in the viewport when it was told to clear its outline.
557
+ const shown = (element: FakeElement) => {
558
+ for (let at: FakeElement | null = element; at; at = at.parentElement) if (at === canvas.viewport) return true;
559
+ return false;
560
+ };
561
+ const clears: boolean[] = [];
562
+ const post = phone.contentWindow!.postMessage;
563
+ phone.contentWindow!.postMessage = (message: any) => {
564
+ if (message.type === "gd:clear") clears.push(shown(phoneSection));
565
+ post(message);
566
+ };
567
+ choose(canvas, "Export as PNG");
568
+ await settle();
569
+ assert.equal(popover.hidden, true, "no comment box is left on a frame that is gone");
570
+ assert.deepEqual(clears, [true], "the Phone frame cleared its outline while it was still shown");
571
+ assert.equal($(canvas, "gd-device-name").textContent, "All sizes", "All sizes comes back");
572
+ assert.equal(shown(phoneSection), false, "with new size frames");
573
+ $(canvas, "gd-popover-cancel").dispatch("click");
574
+ assert.deepEqual(clears, [true], "a later Cancel sends nothing to the removed frame");
575
+ });
576
+
577
+ test("an artboard bigger than the window names the window size it needs and grabs nothing", async () => {
578
+ const { canvas, log } = await pngCanvas({ frame: { width: 1440, height: 900 } });
579
+ const before = canvas.world.style.transform;
580
+ choose(canvas, "Export as PNG");
581
+ await settle();
582
+ assert.deepEqual(log.draw, []);
583
+ assert.equal(log.calls.filter((call) => call === "stop").length, 1);
584
+ assert.equal(statusText(canvas), "Could not export the artboard. The artboard needs a browser window of at least 1440 × 900 px. Make the window bigger or use full screen (F11), then try again. Use your browser's screenshot tool instead.");
585
+ assert.equal(canvas.document.body.classes.has("gd-exporting"), false);
586
+ assert.equal(canvas.world.style.transform, before);
587
+ assert.deepEqual(canvas.posts, []);
588
+ });
589
+
590
+ for (const [surface, reason] of [["window", "You shared a window, not this tab, so the artboard cannot be cropped from it."], ["monitor", "You shared a screen, not this tab, so the artboard cannot be cropped from it."]]) {
591
+ test(`sharing a ${surface} instead of the tab exports nothing and explains it`, async () => {
592
+ const { canvas, log } = await pngCanvas({ surface });
593
+ const before = canvas.world.style.transform;
594
+ choose(canvas, "Export as PNG");
595
+ await settle();
596
+ assert.deepEqual(log.draw, []);
597
+ assert.equal(log.calls.filter((call) => call === "stop").length, 1);
598
+ assert.equal(statusText(canvas), `Could not export the artboard. ${reason} Use your browser's screenshot tool instead.`);
599
+ assert.equal(canvas.navMode.textContent, "Navigating", "the artboard never opened");
600
+ assert.equal(canvas.world.style.transform, before);
601
+ assert.deepEqual(canvas.posts, []);
602
+ });
603
+ }
604
+
605
+ // CodeRabbit 4541511182: the inspector draws a selected comment's outline inside the artboard, where .gd-exporting cannot hide it.
606
+ const COMMENTS = (file: string) => ({ "/t/api/designs/alpha/comments": { comments: [{ id: "abc123", file, selector: "h1", excerpt: "First", comment: "Update", status: "open", sentAt: null }] } });
607
+ const showComment = (canvas: Canvas) => withClass($(canvas, "gd-comment-list"), "gd-comment-show")[0].dispatch("click");
608
+
609
+ test("M-D1: a selected comment's highlight inside the artboard is cleared for the grabbed frame and shown again afterwards", async () => {
610
+ const { canvas, log } = await pngCanvas({ replies: COMMENTS("01-a.html") });
611
+ showComment(canvas);
612
+ assert.equal(lastHighlight(canvas.boards[0].frame), "gd:highlight abc123");
613
+ choose(canvas, "Export as PNG");
614
+ await settle();
615
+ assert.equal(log.draw.length, 1, "it exported");
616
+ assert.equal(log.during[0].highlight, "gd:clear", "no comment outline in the PNG");
617
+ assert.equal(lastHighlight(canvas.boards[0].frame), "gd:highlight abc123", "the outline comes back");
618
+ });
619
+
620
+ test("M-D1: a failed export also gives the selected comment's highlight back", async () => {
621
+ const { canvas, log } = await pngCanvas({ replies: COMMENTS("01-a.html"), frame: { width: 1440, height: 900 } });
622
+ showComment(canvas);
623
+ choose(canvas, "Export as PNG");
624
+ await settle();
625
+ assert.deepEqual(log.draw, []);
626
+ assert.ok(canvas.boards[0].frame.contentWindow!.posted.some((message) => message.type === "gd:clear"), "cleared for the capture");
627
+ assert.equal(lastHighlight(canvas.boards[0].frame), "gd:highlight abc123");
628
+ });
629
+
630
+ test("M-D1: with no selected comment on the artboard, the export clears it and sends no highlight back", async () => {
631
+ const { canvas, log } = await pngCanvas({ replies: COMMENTS("02-b.html") });
632
+ showComment(canvas);
633
+ assert.equal(lastHighlight(canvas.boards[1].frame), "gd:highlight abc123");
634
+ choose(canvas, "Export as PNG");
635
+ await settle();
636
+ assert.equal(log.during[0].highlight, "gd:clear");
637
+ assert.equal(lastHighlight(canvas.boards[0].frame), "gd:clear", "the other artboard's comment is not highlighted in this one");
638
+ assert.equal(lastHighlight(canvas.boards[1].frame), "gd:highlight abc123", "nor cleared in its own");
639
+ });
640
+
641
+ // CodeRabbit round 2 (#3153): a second export, a resize, the hover outline and a reload during the frame waits.
642
+
643
+ test("S3a: a second PNG export while one is waiting for the capture is ignored; the next one after it runs", async () => {
644
+ let grant!: () => void;
645
+ const permission = new Promise<void>((resolve) => { grant = resolve; });
646
+ const { canvas, log } = await pngCanvas({ permission });
647
+ choose(canvas, "Export as PNG");
648
+ choose(canvas, "Export as PNG at 2×");
649
+ await settle();
650
+ assert.equal(log.calls.filter((call) => call.startsWith("capture ")).length, 1, "one capture request, not two");
651
+ grant();
652
+ await settle();
653
+ assert.deepEqual(log.draw, [[100, 100, 400, 300, 0, 0, 400, 300]], "only the first export grabbed a frame");
654
+ assert.deepEqual(log.names, ["01-a.png"]);
655
+ assert.equal(statusText(canvas), "Exported PNG.");
656
+ choose(canvas, "Export as PNG");
657
+ await settle();
658
+ assert.equal(log.calls.filter((call) => call.startsWith("capture ")).length, 2, "a finished export lets the next one start");
659
+ assert.deepEqual(log.names, ["01-a.png", "01-a.png"]);
660
+ });
661
+
662
+ test("S3b: a fitted overview resized while the capture is pending stays fitted to the new size after the export", async () => {
663
+ let deny!: (error: Error) => void;
664
+ const permission = new Promise<void>((_resolve, reject) => { deny = reject; });
665
+ permission.catch(() => {});
666
+ const { canvas } = await pngCanvas({ permission });
667
+ Object.defineProperty(canvas.world, "offsetWidth", { get: () => 9000 });
668
+ Object.defineProperty(canvas.world, "offsetHeight", { get: () => 1000 });
669
+ canvas.viewport.rect = { left: 0, top: 50, width: 400, height: 300 };
670
+ $(canvas, "gd-fit").dispatch("click");
671
+ assert.equal(canvas.zoomLevel.textContent, "5%");
672
+ choose(canvas, "Export as PNG");
673
+ await settle();
674
+ canvas.viewport.rect = { left: 0, top: 50, width: 1800, height: 900 };
675
+ canvas.windowEvent("resize");
676
+ assert.equal(canvas.zoomLevel.textContent, "19%", "the overview refit while the selector was open");
677
+ deny(new Error("Permission denied."));
678
+ await settle();
679
+ assert.equal(canvas.zoomLevel.textContent, "19%", "not the view from before the resize");
680
+ const after = canvas.world.style.transform;
681
+ $(canvas, "gd-fit").dispatch("click");
682
+ assert.equal(after, canvas.world.style.transform, "the view Fit gives at the new size");
683
+ });
684
+
685
+ test("S3b: an open artboard resized while the capture is pending is centered for the new size after the export", async () => {
686
+ let deny!: (error: Error) => void;
687
+ const permission = new Promise<void>((_resolve, reject) => { deny = reject; });
688
+ permission.catch(() => {});
689
+ const { canvas } = await pngCanvas({ permission });
690
+ click(canvas.boards[0].shield!, 200, 200);
691
+ const small = canvas.world.style.transform;
692
+ choose(canvas, "Export as PNG");
693
+ await settle();
694
+ canvas.viewport.rect = { left: 0, top: 50, width: 1800, height: 900 };
695
+ canvas.windowEvent("resize");
696
+ const centered = canvas.world.style.transform;
697
+ assert.notEqual(centered, small, "the resize centered the artboard again");
698
+ deny(new Error("Permission denied."));
699
+ await settle();
700
+ assert.match(canvas.navMode.textContent, /^Using: First/);
701
+ assert.equal(canvas.world.style.transform, centered, "not the focus view from before the resize");
702
+ });
703
+
704
+ test("S3c: comment mode is off in the artboard while its frame is grabbed, so no hover outline is in the PNG; it comes back after", async () => {
705
+ const { canvas, log } = await pngCanvas();
706
+ $(canvas, "gd-comment").dispatch("click");
707
+ assert.equal(lastMode(canvas.boards[0].frame), "on");
708
+ choose(canvas, "Export as PNG");
709
+ await settle();
710
+ assert.equal(log.draw.length, 1, "it exported");
711
+ assert.equal(log.during[0].mode, "off", "the inspector draws no hover outline in the grabbed frame");
712
+ assert.equal(lastMode(canvas.boards[0].frame), "on", "comment mode is back in the artboard");
713
+ assert.equal(lastMode(canvas.boards[1].frame), "on", "the other artboard was never touched");
714
+ });
715
+
716
+ test("S3c: a failed export also gives comment mode back to the artboard", async () => {
717
+ const { canvas, log } = await pngCanvas({ frame: { width: 1440, height: 900 } });
718
+ $(canvas, "gd-comment").dispatch("click");
719
+ choose(canvas, "Export as PNG");
720
+ await settle();
721
+ assert.deepEqual(log.draw, []);
722
+ assert.ok(canvas.boards[0].frame.contentWindow!.posted.some((message) => message.type === "gd:mode" && message.enabled === false), "off for the capture");
723
+ assert.equal(lastMode(canvas.boards[0].frame), "on");
724
+ });
725
+
726
+ const CHANGED = "Could not export the artboard. The artboard was reloaded or closed during the capture. Use your browser's screenshot tool instead.";
727
+
728
+ for (const [name, interrupt] of [
729
+ ["a design.json reload replaces the board", (canvas: Canvas) => canvas.serverEvent("change", { slug: "alpha", file: "design.json" })],
730
+ ["Back closes the artboard", async (canvas: Canvas) => { $(canvas, "gd-back").dispatch("click"); }],
731
+ // S11(a): the artboard's file changed, so its frame reloads in place: same board object, new src.
732
+ ["the artboard's file changes and its frame reloads in place", (canvas: Canvas) => canvas.serverEvent("change", { slug: "alpha", file: "01-a.html" })],
733
+ ] as const) {
734
+ test(`S3d: when ${name} while the capture's frames are awaited, nothing is drawn or downloaded and the export fails`, async () => {
735
+ const { canvas, log, releaseFrames } = await pngCanvas({ held: true });
736
+ const before = canvas.world.style.transform;
737
+ choose(canvas, "Export as PNG");
738
+ await settle();
739
+ assert.equal(log.calls.filter((call) => call === "frame").length, 1, "waiting for a new frame");
740
+ await interrupt(canvas);
741
+ releaseFrames();
742
+ await settle();
743
+ assert.deepEqual(log.draw, [], "the old rectangle is never cropped from the frame");
744
+ assert.deepEqual(log.names, [], "nothing downloaded");
745
+ assert.equal(log.calls.filter((call) => call === "stop").length, 1, "the capture is stopped once");
746
+ assert.equal(statusText(canvas), CHANGED);
747
+ assert.equal(statusIsError(canvas), true);
748
+ assert.equal(toastText(canvas), CHANGED);
749
+ assert.equal(canvas.document.body.classes.has("gd-exporting"), false, "the chrome comes back");
750
+ assert.equal(canvas.navMode.textContent, "Navigating");
751
+ assert.equal(canvas.world.style.transform, before, "the view comes back");
752
+ });
753
+ }
754
+
755
+ // S11(b): an artboard open before the export and left during the capture stays closed afterwards.
756
+ for (const [name, leave] of [
757
+ ["Back", (canvas: Canvas) => { $(canvas, "gd-back").dispatch("click"); }],
758
+ ["Shift+Esc", (canvas: Canvas) => {
759
+ const chord: any = { key: "Escape", shiftKey: true, ctrlKey: false, metaKey: false, altKey: false, target: $(canvas, "gd-back"), defaultPrevented: false, preventDefault() { chord.defaultPrevented = true; } };
760
+ for (const listener of canvas.document.listeners.get("keydown") ?? []) listener(chord);
761
+ }],
762
+ ] as const) {
763
+ test(`S11b: an open artboard left with ${name} while the capture's frames are awaited is not reopened after the failed export`, async () => {
764
+ const { canvas, log, releaseFrames } = await pngCanvas({ held: true });
765
+ click(canvas.boards[0].shield!, 200, 200);
766
+ assert.match(canvas.navMode.textContent, /^Using: First/);
767
+ choose(canvas, "Export as PNG");
768
+ await settle();
769
+ assert.equal(log.calls.filter((call) => call === "frame").length, 1, "waiting for a new frame");
770
+ leave(canvas);
771
+ assert.equal(canvas.navMode.textContent, "Navigating", "the artboard was left");
772
+ const left = canvas.world.style.transform;
773
+ releaseFrames();
774
+ await settle();
775
+ assert.deepEqual(log.draw, []);
776
+ assert.deepEqual(log.names, []);
777
+ assert.equal(statusText(canvas), CHANGED);
778
+ assert.equal(canvas.navMode.textContent, "Navigating", "not reopened");
779
+ assert.deepEqual(boardsOf(canvas).map((wrapper) => wrapper.classes.has("gd-focus-board")), [false, false], "no artboard is open");
780
+ assert.deepEqual(boardsOf(canvas).map((wrapper) => wrapper.inert), [false, false]);
781
+ assert.equal(canvas.world.style.transform, left, "the overview leaving gave, not the focus view from before");
782
+ assert.equal(canvas.document.body.classes.has("gd-exporting"), false);
783
+ });
784
+ }
785
+
786
+ // S21 E1: a design.json reload builds new board objects, so the artboard left during the capture must stay closed
787
+ // whether the reload comes before or after Back.
788
+ for (const [name, interrupt] of [
789
+ ["Back, then a design.json reload", async (canvas: Canvas) => {
790
+ $(canvas, "gd-back").dispatch("click");
791
+ await canvas.serverEvent("change", { slug: "alpha", file: "design.json" });
792
+ }],
793
+ ["a design.json reload, then Back", async (canvas: Canvas) => {
794
+ await canvas.serverEvent("change", { slug: "alpha", file: "design.json" });
795
+ assert.match(canvas.navMode.textContent, /^Using: First/, "the reload kept focus mode on the same file");
796
+ $(canvas, "gd-back").dispatch("click");
797
+ }],
798
+ ] as const) {
799
+ test(`S21 E1: an open artboard left during the capture stays closed after ${name}`, async () => {
800
+ const { canvas, log, releaseFrames } = await pngCanvas({ held: true });
801
+ click(canvas.boards[0].shield!, 200, 200);
802
+ assert.match(canvas.navMode.textContent, /^Using: First/);
803
+ choose(canvas, "Export as PNG");
804
+ await settle();
805
+ assert.equal(log.calls.filter((call) => call === "frame").length, 1, "waiting for a new frame");
806
+ await interrupt(canvas);
807
+ assert.equal(canvas.navMode.textContent, "Navigating", "the artboard was left");
808
+ releaseFrames();
809
+ await settle();
810
+ assert.deepEqual(log.draw, [], "nothing drawn");
811
+ assert.deepEqual(log.names, [], "nothing downloaded");
812
+ assert.equal(statusText(canvas), CHANGED);
813
+ assert.equal(canvas.navMode.textContent, "Navigating", "not reopened");
814
+ assert.deepEqual(boardsOf(canvas).map((wrapper) => wrapper.classes.has("gd-focus-board")), [false, false], "no artboard is open");
815
+ assert.deepEqual(boardsOf(canvas).map((wrapper) => wrapper.inert), [false, false]);
816
+ assert.equal(canvas.document.body.classes.has("gd-exporting"), false);
817
+ });
818
+ }
819
+
820
+ // S21 E2: a design switch during an export keeps the new design's view; the old design's view is not restored over it.
821
+ test("S21 E2: a show event for another design while the capture is pending leaves that design's fit, not the old design's view", async () => {
822
+ // The fake world has no box, which Fit needs; alpha is zoomed in, so its view is not the fit any design gets.
823
+ const zoomed = (canvas: Canvas) => {
824
+ Object.defineProperty(canvas.world, "offsetWidth", { get: () => 2000 });
825
+ Object.defineProperty(canvas.world, "offsetHeight", { get: () => 1000 });
826
+ $(canvas, "gd-zoom-in").dispatch("click");
827
+ return canvas.world.style.transform;
828
+ };
829
+ const plain = await pngCanvas();
830
+ const alphaView = zoomed(plain.canvas);
831
+ await plain.canvas.serverEvent("show", { slug: "beta" });
832
+ await settle();
833
+ const betaFit = plain.canvas.world.style.transform;
834
+ assert.notEqual(betaFit, alphaView, "beta's fit differs from alpha's view");
835
+
836
+ let grant!: () => void;
837
+ const permission = new Promise<void>((resolve) => { grant = resolve; });
838
+ const { canvas, log } = await pngCanvas({ permission });
839
+ assert.equal(zoomed(canvas), alphaView);
840
+ choose(canvas, "Export as PNG");
841
+ await settle();
842
+ assert.equal(log.calls.filter((call) => call.startsWith("capture ")).length, 1, "the browser's selector is open");
843
+ await canvas.serverEvent("show", { slug: "beta" });
844
+ await settle();
845
+ assert.equal(canvas.world.style.transform, betaFit, "beta loaded and fitted");
846
+ grant();
847
+ await settle();
848
+ assert.deepEqual(log.draw, []);
849
+ assert.deepEqual(log.names, []);
850
+ assert.equal(canvas.document.getElementById("gd-title").textContent, "Beta");
851
+ assert.equal(canvas.navMode.textContent, "Navigating");
852
+ assert.equal(canvas.world.style.transform, betaFit, "beta's fit, not alpha's view from before the export");
853
+ assert.equal(canvas.document.body.classes.has("gd-exporting"), false);
854
+ });
855
+
856
+ test("a capture failure stops the stream and restores the canvas view", async () => {
857
+ const { canvas, log } = await pngCanvas({ play: async () => { throw new Error("The video could not play."); } });
858
+ const before = canvas.world.style.transform;
859
+ choose(canvas, "Export as PNG");
860
+ await settle();
861
+ assert.equal(log.calls.filter((call) => call === "stop").length, 1);
862
+ assert.equal(canvas.world.style.transform, before);
863
+ assert.equal(canvas.navMode.textContent, "Navigating");
864
+ assert.equal(canvas.document.body.classes.has("gd-exporting"), false);
865
+ assert.equal(statusText(canvas), "Could not export the artboard. The video could not play. Use your browser's screenshot tool instead.");
866
+ assert.deepEqual(canvas.posts, []);
867
+ });
868
+
869
+ // ---- Export as PDF and Download HTML
870
+
871
+ /** Both design artboard files, as the server serves them. */
872
+ const ARTBOARD_FILES = { [ARTBOARD_URL]: { __text: "<p>A</p>" }, "/t/files/alpha/02-b.html": { __text: "<p>B</p>" } };
873
+
874
+ test("Export as PDF prints the artboard alone at its size once its frame has loaded, then cleans up", async () => {
875
+ let printed = 0;
876
+ const canvas = await loadExport(ARTBOARD_FILES, { print: () => printed++ });
877
+ choose(canvas, "Export as PDF");
878
+ await settle(4);
879
+ const body = canvas.document.body;
880
+ const holders = withClass(body, "gd-print");
881
+ assert.equal(holders.length, 1, "a print container is added to the page");
882
+ assert.equal(body.classes.has("gd-printing"), true);
883
+ const frame = holders[0].children[0];
884
+ assert.equal(frame.localName, "iframe");
885
+ assert.equal(frame.getAttribute("src"), ARTBOARD_URL);
886
+ assert.equal(frame.getAttribute("sandbox"), "allow-scripts", "sandboxed like the canvas frames");
887
+ assert.equal(frame.getAttribute("referrerpolicy"), "no-referrer");
888
+ assert.equal(frame.title, "First artboard");
889
+ assert.deepEqual([frame.style.width, frame.style.height], ["400px", "300px"]);
890
+ assert.equal(printed, 0, "printing waits for the artboard");
891
+ frame.dispatch("load");
892
+ assert.equal(printed, 1);
893
+ canvas.windowEvent("afterprint");
894
+ assert.equal(withClass(body, "gd-print").length, 0, "the container is removed after printing");
895
+ assert.equal(body.classes.has("gd-printing"), false);
896
+ assert.deepEqual(canvas.posts, [], "nothing is sent to the server");
897
+ });
898
+
899
+ test("a second Export as PDF replaces the first one's container and ends the first one: one page rule, one afterprint listener (D3)", async () => {
900
+ const canvas = await loadExport(ARTBOARD_FILES, { print: () => {} });
901
+ // canvas.css with a CSSOM, where each export sets its page size.
902
+ const rules: string[] = [];
903
+ const sheet = { href: "/t/assets/canvas.css", cssRules: rules, insertRule: (text: string, index: number) => { rules.splice(index, 0, text); return index; }, deleteRule: (index: number) => { rules.splice(index, 1); } };
904
+ (canvas.document as any).styleSheets = [sheet];
905
+ const listeners = canvas.windowListenerCount("afterprint");
906
+ choose(canvas, "Export as PDF", 0);
907
+ assert.deepEqual(rules, ["@page { size: 400px 300px; }"]);
908
+ choose(canvas, "Export as PDF", 1);
909
+ await settle(4);
910
+ const holders = withClass(canvas.document.body, "gd-print");
911
+ assert.equal(holders.length, 1);
912
+ assert.equal(holders[0].children[0].getAttribute("src"), "/t/files/alpha/02-b.html");
913
+ assert.deepEqual(rules, ["@page { size: 400px 300px; }"], "the first export's page rule is gone, only the second's is left");
914
+ assert.equal(canvas.windowListenerCount("afterprint"), listeners + 1, "the first export no longer waits for afterprint");
915
+ assert.equal(canvas.document.body.classes.has("gd-printing"), true);
916
+ canvas.windowEvent("afterprint");
917
+ assert.deepEqual(rules, []);
918
+ assert.equal(withClass(canvas.document.body, "gd-print").length, 0);
919
+ assert.equal(canvas.document.body.classes.has("gd-printing"), false);
920
+ });
921
+
922
+ /** canvas.css with a CSSOM, where each PDF export sets its page size; `rules` is what it holds. */
923
+ function printSheet(canvas: Canvas) {
924
+ const rules: string[] = ["@page { margin: 0; }"];
925
+ const sheet = { href: "/t/assets/canvas.css", cssRules: rules, insertRule: (text: string, index: number) => { rules.splice(index, 0, text); return index; }, deleteRule: (index: number) => { rules.splice(index, 1); } };
926
+ (canvas.document as any).styleSheets = [sheet];
927
+ return rules;
928
+ }
929
+
930
+ test("#3153 case 3: two PDFs started before the first frame loads, then the second one printed: neither page rule, container nor listener is left", async () => {
931
+ let printed = 0;
932
+ const canvas = await loadExport(ARTBOARD_FILES, { print: () => printed++ });
933
+ const rules = printSheet(canvas);
934
+ const listeners = canvas.windowListenerCount("afterprint");
935
+ choose(canvas, "Export as PDF", 0);
936
+ choose(canvas, "Export as PDF", 1);
937
+ assert.deepEqual(rules, ["@page { margin: 0; }", "@page { size: 400px 300px; }"], "the superseded export's rule is gone at once");
938
+ await settle(4);
939
+ const holders = withClass(canvas.document.body, "gd-print");
940
+ assert.equal(holders.length, 1);
941
+ holders[0].children[0].dispatch("load");
942
+ assert.equal(printed, 1, "only the second one prints");
943
+ canvas.windowEvent("afterprint");
944
+ assert.deepEqual(rules, ["@page { margin: 0; }"], "canvas.css's own rules stay, no export rule survives");
945
+ assert.equal(withClass(canvas.document.body, "gd-print").length, 0);
946
+ assert.equal(canvas.document.body.classes.has("gd-printing"), false);
947
+ assert.equal(canvas.windowListenerCount("afterprint"), listeners);
948
+ });
949
+
950
+ test("an Export as PDF whose print() throws cleans up its container, page rule and listener and says so", async () => {
951
+ const canvas = await loadExport(ARTBOARD_FILES, { print: () => { throw new Error("Printing is blocked"); } });
952
+ const rules = printSheet(canvas);
953
+ const listeners = canvas.windowListenerCount("afterprint");
954
+ choose(canvas, "Export as PDF");
955
+ await settle(4);
956
+ withClass(canvas.document.body, "gd-print")[0].children[0].dispatch("load");
957
+ assert.deepEqual(rules, ["@page { margin: 0; }"]);
958
+ assert.equal(withClass(canvas.document.body, "gd-print").length, 0);
959
+ assert.equal(canvas.document.body.classes.has("gd-printing"), false);
960
+ assert.equal(canvas.windowListenerCount("afterprint"), listeners);
961
+ assert.equal(statusText(canvas), "Could not print the artboard (Printing is blocked). Open it from design/ in your project instead.");
962
+ assert.equal(statusIsError(canvas), true);
963
+ assert.equal(toastText(canvas), statusText(canvas));
964
+ });
965
+
966
+ // CodeRabbit 4543489161: an iframe also fires load for the server's 404 page, which would then be printed.
967
+ for (const [name, reply, reason] of [["is gone (404)", undefined, "HTTP 404"], ["cannot be fetched", { __throw: "Failed to fetch" }, "Failed to fetch"]] as const) {
968
+ test(`M-D2: Export as PDF of an artboard file that ${name} says so, prints nothing and leaves no container, page rule or listener`, async () => {
969
+ let printed = 0;
970
+ const canvas = await loadExport(reply ? { [ARTBOARD_URL]: reply } : {}, { print: () => printed++ });
971
+ const rules = printSheet(canvas);
972
+ const listeners = canvas.windowListenerCount("afterprint");
973
+ choose(canvas, "Export as PDF");
974
+ await settle(4);
975
+ assert.equal(printed, 0);
976
+ assert.equal(withClass(canvas.document.body, "gd-print").length, 0);
977
+ assert.equal(canvas.document.body.classes.has("gd-printing"), false);
978
+ assert.deepEqual(rules, ["@page { margin: 0; }"]);
979
+ assert.equal(canvas.windowListenerCount("afterprint"), listeners);
980
+ assert.ok(canvas.fetched.includes(ARTBOARD_URL), "the file was read before the frame loads it");
981
+ assert.equal(statusText(canvas), `Could not print the artboard (${reason}). Open it from design/ in your project instead.`);
982
+ assert.equal(statusIsError(canvas), true);
983
+ assert.equal(toastText(canvas), statusText(canvas));
984
+ assert.deepEqual(canvas.posts, []);
985
+ });
986
+ }
987
+
988
+ test("M-D2: a PDF export superseded while its file is read reports nothing when that read fails; the newer one prints", async () => {
989
+ let printed = 0;
990
+ let answer!: (reply: unknown) => void;
991
+ const canvas = await loadExport({ [ARTBOARD_URL]: new Promise((resolve) => { answer = resolve; }), "/t/files/alpha/02-b.html": { __text: "<p>B</p>" } }, { print: () => printed++ });
992
+ const rules = printSheet(canvas);
993
+ choose(canvas, "Export as PDF", 0);
994
+ choose(canvas, "Export as PDF", 1);
995
+ await settle(4);
996
+ answer({ __http: 404 });
997
+ await settle(4);
998
+ assert.equal(statusIsError(canvas), false, "the superseded export says nothing");
999
+ const holders = withClass(canvas.document.body, "gd-print");
1000
+ assert.equal(holders.length, 1);
1001
+ assert.equal(holders[0].children[0].getAttribute("src"), "/t/files/alpha/02-b.html");
1002
+ assert.deepEqual(rules, ["@page { margin: 0; }", "@page { size: 400px 300px; }"]);
1003
+ holders[0].children[0].dispatch("load");
1004
+ assert.equal(printed, 1);
1005
+ });
1006
+
1007
+ test("S3e: the print frame's blank load before its src is set never prints; the artboard's own load does", async () => {
1008
+ let printed = 0;
1009
+ let answer!: (reply: unknown) => void;
1010
+ const canvas = await loadExport({ [ARTBOARD_URL]: new Promise((resolve) => { answer = resolve; }) }, { print: () => printed++ });
1011
+ choose(canvas, "Export as PDF");
1012
+ await settle(4);
1013
+ const frame = withClass(canvas.document.body, "gd-print")[0].children[0];
1014
+ assert.equal(frame.getAttribute("src"), null, "the file is still being read");
1015
+ // Firefox before 148 loads the empty frame's about:blank asynchronously, after its insertion.
1016
+ frame.dispatch("load");
1017
+ assert.equal(printed, 0, "about:blank is not the artboard");
1018
+ answer({ __text: "<p>A</p>" });
1019
+ await settle(4);
1020
+ assert.equal(frame.getAttribute("src"), ARTBOARD_URL);
1021
+ frame.dispatch("load");
1022
+ assert.equal(printed, 1, "printed once the artboard loaded");
1023
+ });
1024
+
1025
+ /**
1026
+ * Download HTML under the canvas base `base`, the artboard served through the server's own injection
1027
+ * (injectInspector), so a change in the injected tag fails here. Returns the downloads and the saved blobs.
1028
+ */
1029
+ async function downloadServed(base: string, original: string) {
1030
+ const names: string[] = [];
1031
+ const blobs: Array<{ parts: unknown[]; type: string }> = [];
1032
+ const fileUrl = `${base}files/alpha/01-a.html`;
1033
+ // The default replies live under /t/; any other base needs its own design load.
1034
+ const designReplies = base === "/t/" ? {} : {
1035
+ [`${base}api/system`]: { exists: false },
1036
+ [`${base}api/designs`]: { designs: [{ slug: "alpha", title: "Alpha", valid: true }] },
1037
+ [`${base}api/designs/alpha`]: { slug: "alpha", title: "Alpha", brief: "", artboards: [{ file: "01-a.html", title: "First", tradeoff: "", width: 400, height: 300 }] },
1038
+ [`${base}api/designs/alpha/comments`]: { comments: [] },
1039
+ [`${base}api/designs/alpha/handoffs`]: { version: 1, chosen: null, handoffs: {} },
1040
+ [`${base}api/designs/alpha/parts`]: { version: 1, parts: [] },
1041
+ };
1042
+ const canvas = await loadExport({ ...designReplies, [fileUrl]: { __text: injectInspector(original, base) } }, {
1043
+ Blob: class { constructor(parts: unknown[], options: { type: string }) { blobs.push({ parts, type: options.type }); } },
1044
+ URL: { createObjectURL: () => "blob:test", revokeObjectURL: () => names.push("revoked") },
1045
+ }, { base });
1046
+ const document = canvas.document as any;
1047
+ const create = document.createElement.bind(document);
1048
+ document.createElement = (tag: string) => (tag === "a" ? { click() { names.push(this.download); }, href: "", download: "" } : create(tag));
1049
+ choose(canvas, "Download HTML");
1050
+ await settle(4);
1051
+ return { canvas, names, blobs: JSON.parse(JSON.stringify(blobs)), fileUrl };
1052
+ }
1053
+
1054
+ test("Download HTML saves the artboard file as written, without the inspector the server injects", async () => {
1055
+ const original = "<!doctype html><title>A</title><p>Hello</p></body></html>";
1056
+ const { canvas, names, blobs, fileUrl } = await downloadServed("/t/", original);
1057
+ assert.deepEqual(names, ["01-a.html", "revoked"]);
1058
+ assert.deepEqual(blobs, [{ parts: [original], type: "text/html" }]);
1059
+ assert.ok(canvas.fetched.includes(fileUrl));
1060
+ assert.deepEqual(canvas.posts, []);
1061
+ assert.equal(statusIsError(canvas), false);
1062
+ });
1063
+
1064
+ test("S25: Download HTML removes the inspector the server injects when the base holds characters the server escapes", async () => {
1065
+ const original = "<!doctype html><title>A</title><p>Hello</p></body></html>";
1066
+ const base = "/t&x\"'<>/";
1067
+ const { canvas, names, blobs, fileUrl } = await downloadServed(base, original);
1068
+ assert.deepEqual(names, ["01-a.html", "revoked"]);
1069
+ assert.deepEqual(blobs, [{ parts: [original], type: "text/html" }], "no inspector tag left");
1070
+ assert.ok(canvas.fetched.includes(fileUrl));
1071
+ assert.equal(statusIsError(canvas), false);
1072
+ // An artboard without </body> gets the tag at its end; it is removed there too.
1073
+ const bare = "<p>No body end</p>";
1074
+ assert.deepEqual((await downloadServed(base, bare)).blobs, [{ parts: [bare], type: "text/html" }]);
1075
+ });
1076
+
1077
+ test("a failed Download HTML says so with the reason and downloads nothing", async () => {
1078
+ const names: string[] = [];
1079
+ const canvas = await loadExport({}, { Blob: class {}, URL: { createObjectURL: () => "blob:test", revokeObjectURL: () => {} } });
1080
+ const document = canvas.document as any;
1081
+ const create = document.createElement.bind(document);
1082
+ document.createElement = (tag: string) => (tag === "a" ? { click() { names.push(this.download); }, href: "", download: "" } : create(tag));
1083
+ choose(canvas, "Download HTML");
1084
+ await settle(4);
1085
+ assert.deepEqual(names, []);
1086
+ assert.equal(statusText(canvas), "Could not download the artboard (HTTP 404). Open it from design/ in your project instead.");
1087
+ assert.equal(statusIsError(canvas), true);
1088
+ assert.equal(toastText(canvas), statusText(canvas));
1089
+ assert.deepEqual(canvas.posts, []);
1090
+ });
1091
+
1092
+ // ---- source pins, markup, styles and docs
1093
+
1094
+ /** The source without its comments, so a word in a sentence never counts as code. */
1095
+ const code = (source: string) => source.replace(/\/\*[^]*?\*\//g, "").replace(/(^|[^:"'`])\/\/.*$/gm, "$1");
1096
+
1097
+ test("canvas-export.js reaches the browser only through ctx.win and ctx.doc, changes the view through the store and keeps its English strings in one TEXT block", () => {
1098
+ const source = read("canvas-export.js");
1099
+ const body = code(source);
1100
+ for (const global of ["window", "document", "navigator", "URL", "Blob", "fetch", "requestAnimationFrame", "setTimeout", "print", "confirm", "innerWidth", "innerHeight", "localStorage"]) {
1101
+ assert.ok(!new RegExp(`(?<![\\w.$])${global}\\s*[.(\\[]`).test(body), `${global} only through win or doc`);
1102
+ }
1103
+ for (const used of ["win.navigator", "win.print", "win.URL", "win.Blob", "win.fetch", "win.requestAnimationFrame", "doc.body", "doc.createElement"]) assert.ok(body.includes(used), used);
1104
+ assert.match(body, /store\.setView\(/);
1105
+ assert.match(body, /store\.setFocus\(\{ size/, "the size goes back through setFocus, the sizes PR's path");
1106
+ assert.match(body, /actions\.setFrameSize\(/);
1107
+ assert.ok(!/\.confirm\(/.test(body), "no blocking confirm before the capture: it would spend the click's activation (D1)");
1108
+ assert.match(body, /return \{ boardMenuButton, closeBoardMenu, relabel \};\s*\}\s*$/, "the other modules only need the button and closing its menu (D2); relabel is the language's (canvas-boot.js)");
1109
+ assert.ok(!/\bstate\.(?:size|focus|menu)\s*=(?!=)/.test(body));
1110
+ assert.ok(source.indexOf("const TEXT = Object.freeze({") >= 0 && source.indexOf("const TEXT = Object.freeze({") < source.indexOf("export function init"), "the strings sit in one TEXT block before init");
1111
+ // Its strings go through ctx.i18n, checked against canvas-i18n-es.js in tests/design-canvas-i18n.test.ts.
1112
+ assert.ok(!/createAlert|explain\(|setRaw|variant|Try another direction|Compare with app|Implement this|enterCompare/.test(body), "no alert helpers, no other menu items");
1113
+ assert.ok(!/\b(?:state|view|savedView)\.(?:x|y|zoom|fitted)\s*(?:[-+*/]?=)(?!=)/.test(body));
1114
+ assert.ok(!/Object\.assign\(\s*state\b/.test(body));
1115
+ assert.ok(!/https?:\/\//i.test(source), "no remote URL literals");
1116
+ });
1117
+
1118
+ test("canvas-export.js is an allowlisted module wired by canvas-boot.js", () => {
1119
+ assert.equal(DESIGN_CANVAS_ASSETS["canvas-export.js"], "text/javascript; charset=utf-8");
1120
+ const boot = read("canvas-boot.js");
1121
+ assert.match(boot, /import \* as exporter from "\.\/canvas-export\.js";/);
1122
+ assert.match(boot, /const MODULES = \[[^\]]*\bexporter\b[^\]]*\];/);
1123
+ assert.match(read("canvas-boards.js"), /actions\.boardMenuButton\(board\)/, "the boards ask for the button when they are built, never at init");
1124
+ });
1125
+
1126
+ test("index.html's sprite holds the menu and export icons", () => {
1127
+ const html = read("index.html");
1128
+ for (const icon of ["i-more", "i-image", "i-file", "i-download"]) assert.match(html, new RegExp(`<symbol id="${icon}" viewBox="0 0 24 24">`));
1129
+ assert.ok(!/data-i18n/.test(html.slice(html.indexOf('<svg id="gd-sprite"'), html.indexOf("</svg>"))));
1130
+ });
1131
+
1132
+ /** The body of the first `selector {` rule in canvas.css. */
1133
+ function rule(css: string, selector: string) {
1134
+ const start = css.indexOf(`\n${selector} {`);
1135
+ assert.ok(start >= 0, `${selector} is styled`);
1136
+ return css.slice(start, css.indexOf("}", start) + 1);
1137
+ }
1138
+
1139
+ test("canvas.css: one Export section on --gd-* tokens hides the chrome while exporting and prints only the print container", () => {
1140
+ const css = read("canvas.css");
1141
+ assert.equal(css.split("/* Export (canvas-export.js)").length - 1, 1, "one Export section");
1142
+ const section = css.slice(css.indexOf("/* Export (canvas-export.js)"));
1143
+ for (const selector of [".gd-menu-button", ".gd-exporting .gd-viewport", ".gd-print"]) {
1144
+ const text = rule(section, selector);
1145
+ assert.ok(!/#[0-9a-fA-F]{3,8}\b|rgba?\(/.test(text), `${selector}: tokens only`);
1146
+ assert.ok(!/var\(--(?!gd-)/.test(text), `${selector}: only --gd-* tokens`);
1147
+ assert.ok(!/transition|animation/.test(text), `${selector}: no motion`);
1148
+ }
1149
+ assert.match(css, /\.gd-menu-button:focus-visible[^{]*{[^}]*outline:\s*2px solid var\(--gd-focus\)/);
1150
+ assert.match(css, /\.gd-exporting \.gd-viewport\s*\{[^}]*position:\s*fixed;[^}]*inset:\s*0;/);
1151
+ assert.match(css, /\.gd-exporting \.gd-viewport > :not\(\.gd-world\)/);
1152
+ for (const hidden of ["gd-pins", "gd-artboard:not(.gd-focus-board)"]) assert.ok(section.includes(`.gd-exporting .${hidden}`), hidden);
1153
+ assert.match(css, /@media print\s*\{[^]*body\.gd-printing > :not\(\.gd-print\)\s*\{\s*display:\s*none/);
1154
+ assert.match(css, /@page\s*\{\s*margin:\s*0/);
1155
+ assert.ok(!/border-radius:\s*50%/.test(section), "S4: no dots");
1156
+ });
1157
+
1158
+ test("the docs describe the artboard menu and its exports", () => {
1159
+ const docs = readFileSync(fileURLToPath(new URL("../docs/gentle-shell.md", import.meta.url)), "utf8");
1160
+ const section = docs.slice(docs.indexOf("### Gentle Design"), docs.indexOf("### Gentle Music"));
1161
+ const start = section.indexOf("- **Export**");
1162
+ assert.ok(start >= 0, "an Export entry");
1163
+ const entry = section.slice(start, section.indexOf("\n", start));
1164
+ for (const part of ["**⋯**", "not the Design system board", "**Export as PNG**", "**Export as PNG at 2×**", "**Export as PDF**", "**Download HTML**", "*Save as PDF*", "canvas tab", "`<artboard>@2x.png`", "`F11`", "Chromium", "screenshot tool", "inspector", "only read the artboard file from the canvas server", "nothing is uploaded"]) assert.ok(entry.includes(part), `the Export entry mentions ${part}`);
1165
+ assert.ok(entry.includes("opens a menu with **Export as PNG**, **Export as PNG at 2×**, **Export as PDF** and **Download HTML**,"), "the export items, and only them (S7)");
1166
+ for (const cut of ["Try another direction", "Compare with app"]) assert.ok(!entry.includes(cut), `${cut} is not in this menu`);
1167
+ assert.ok(!entry.includes("Nothing goes to the canvas server"), "PDF and HTML read the artboard from the server (S3f)");
1168
+ });