@agent-native/core 0.80.4 → 0.80.6

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 (341) hide show
  1. package/corpus/README.md +2 -2
  2. package/corpus/core/CHANGELOG.md +28 -2
  3. package/corpus/core/docs/content/locales/ar-SA/real-time-collaboration.mdx +2 -2
  4. package/corpus/core/docs/content/locales/ar-SA/template-design.mdx +1 -1
  5. package/corpus/core/docs/content/locales/de-DE/real-time-collaboration.mdx +3 -3
  6. package/corpus/core/docs/content/locales/de-DE/template-design.mdx +1 -1
  7. package/corpus/core/docs/content/locales/es-ES/real-time-collaboration.mdx +2 -2
  8. package/corpus/core/docs/content/locales/es-ES/template-design.mdx +1 -1
  9. package/corpus/core/docs/content/locales/fr-FR/real-time-collaboration.mdx +2 -2
  10. package/corpus/core/docs/content/locales/fr-FR/template-design.mdx +1 -1
  11. package/corpus/core/docs/content/locales/hi-IN/template-design.mdx +1 -1
  12. package/corpus/core/docs/content/locales/ja-JP/real-time-collaboration.mdx +2 -2
  13. package/corpus/core/docs/content/locales/ja-JP/template-design.mdx +1 -1
  14. package/corpus/core/docs/content/locales/ko-KR/real-time-collaboration.mdx +2 -2
  15. package/corpus/core/docs/content/locales/ko-KR/template-design.mdx +1 -1
  16. package/corpus/core/docs/content/locales/pt-BR/real-time-collaboration.mdx +2 -2
  17. package/corpus/core/docs/content/locales/pt-BR/template-design.mdx +1 -1
  18. package/corpus/core/docs/content/locales/zh-CN/real-time-collaboration.mdx +2 -2
  19. package/corpus/core/docs/content/locales/zh-CN/template-design.mdx +1 -1
  20. package/corpus/core/docs/content/locales/zh-TW/real-time-collaboration.mdx +2 -2
  21. package/corpus/core/docs/content/locales/zh-TW/template-design.mdx +1 -1
  22. package/corpus/core/docs/content/real-time-collaboration.mdx +2 -2
  23. package/corpus/core/docs/content/template-design.mdx +1 -1
  24. package/corpus/core/package.json +3 -7
  25. package/corpus/core/src/action.ts +21 -0
  26. package/corpus/core/src/agent/durable-background.ts +32 -11
  27. package/corpus/core/src/agent/production-agent.ts +11 -1
  28. package/corpus/core/src/agent/run-loop-with-resume.ts +3 -1
  29. package/corpus/core/src/brand-kit/fig/index.ts +17 -37
  30. package/corpus/core/src/cli/create.ts +1 -0
  31. package/corpus/core/src/cli/index.ts +1 -1
  32. package/corpus/core/src/cli/mcp-config-writers.ts +187 -51
  33. package/corpus/core/src/cli/skills.ts +18 -3
  34. package/corpus/core/src/client/AssistantChat.tsx +11 -1
  35. package/corpus/core/src/client/agent-chat.ts +12 -1
  36. package/corpus/core/src/client/composer/PromptComposer.tsx +100 -41
  37. package/corpus/core/src/client/org/OrgSwitcher.tsx +1 -1
  38. package/corpus/core/src/client/sharing/ShareButton.tsx +3 -27
  39. package/corpus/core/src/collab/presence.ts +1 -1
  40. package/corpus/core/src/mcp/connect-route.ts +34 -5
  41. package/corpus/core/src/server/action-discovery.ts +4 -0
  42. package/corpus/core/src/server/agent-chat-plugin.ts +20 -0
  43. package/corpus/core/src/sharing/registry.ts +17 -0
  44. package/corpus/core/src/templates/default/pnpm-workspace.yaml +1 -0
  45. package/corpus/core/src/templates/workspace-root/pnpm-workspace.yaml +1 -0
  46. package/corpus/templates/analytics/actions/dashboard-mutation-api.ts +2 -0
  47. package/corpus/templates/analytics/actions/update-dashboard.ts +8 -0
  48. package/corpus/templates/analytics/app/components/layout/Layout.tsx +1 -1
  49. package/corpus/templates/analytics/app/components/layout/Sidebar.tsx +117 -33
  50. package/corpus/templates/analytics/app/pages/adhoc/sql-dashboard/index.tsx +4 -0
  51. package/corpus/templates/analytics/app/pages/adhoc/sql-dashboard/types.ts +7 -0
  52. package/corpus/templates/analytics/changelog/2026-06-27-dashboards-can-now-nest-under-a-parent-in-the-sidebar-via-a-.md +6 -0
  53. package/corpus/templates/analytics/changelog/2026-06-29-analytics-pages-now-sit-closer-under-the-header-with-tighter.md +6 -0
  54. package/corpus/templates/assets/actions/generate-image-batch.ts +3 -0
  55. package/corpus/templates/assets/actions/generate-image.ts +3 -0
  56. package/corpus/templates/assets/changelog/2026-06-29-longer-agent-generation-window.md +6 -0
  57. package/corpus/templates/assets/netlify.toml +3 -3
  58. package/corpus/templates/assets/server/plugins/agent-chat.ts +4 -1
  59. package/corpus/templates/clips/app/components/capture-install-options.tsx +7 -8
  60. package/corpus/templates/clips/app/components/recorder/recorder-engine.ts +1 -1
  61. package/corpus/templates/content/AGENTS.md +57 -44
  62. package/corpus/templates/content/README.md +16 -0
  63. package/corpus/templates/content/actions/_builder-cms-read-client.ts +125 -0
  64. package/corpus/templates/content/actions/_builder-cms-source-adapter.ts +28 -6
  65. package/corpus/templates/content/actions/_builder-cms-write-adapter.ts +238 -69
  66. package/corpus/templates/content/actions/_builder-cms-write-settings.ts +125 -43
  67. package/corpus/templates/content/actions/_database-source-utils.ts +746 -97
  68. package/corpus/templates/content/actions/_database-utils.ts +17 -14
  69. package/corpus/templates/content/actions/_federation-join.ts +14 -2
  70. package/corpus/templates/content/actions/_join-suggestion.ts +89 -14
  71. package/corpus/templates/content/actions/_local-file-documents.ts +2 -1
  72. package/corpus/templates/content/actions/attach-content-database-source.ts +124 -5
  73. package/corpus/templates/content/actions/bind-content-database-source-field.ts +256 -0
  74. package/corpus/templates/content/actions/change-content-database-source-role.ts +420 -0
  75. package/corpus/templates/content/actions/create-document.ts +8 -0
  76. package/corpus/templates/content/actions/execute-builder-source-batch.ts +282 -0
  77. package/corpus/templates/content/actions/execute-builder-source-execution.ts +220 -8
  78. package/corpus/templates/content/actions/get-content-database.ts +10 -2
  79. package/corpus/templates/content/actions/prepare-builder-source-execution.ts +19 -2
  80. package/corpus/templates/content/actions/prepare-builder-source-review.ts +47 -15
  81. package/corpus/templates/content/actions/refresh-content-database-source.ts +11 -4
  82. package/corpus/templates/content/actions/review-content-database-source-change-set.ts +6 -2
  83. package/corpus/templates/content/actions/set-content-database-source-write-mode.ts +32 -12
  84. package/corpus/templates/content/actions/stage-builder-revision.ts +14 -10
  85. package/corpus/templates/content/actions/validate-builder-source-execution.ts +25 -3
  86. package/corpus/templates/content/app/blocks/BuilderDocsBlocks.tsx +10 -0
  87. package/corpus/templates/content/app/components/editor/BubbleToolbar.tsx +1 -0
  88. package/corpus/templates/content/app/components/editor/ContentReferencePreview.tsx +185 -0
  89. package/corpus/templates/content/app/components/editor/DocumentDatabase.tsx +1520 -553
  90. package/corpus/templates/content/app/components/editor/DocumentEditor.tsx +3 -0
  91. package/corpus/templates/content/app/components/editor/DocumentProperties.tsx +150 -1
  92. package/corpus/templates/content/app/components/editor/VisualEditor.tsx +19 -0
  93. package/corpus/templates/content/app/components/editor/database/DatabaseView.tsx +647 -66
  94. package/corpus/templates/content/app/components/editor/database-sources/BuilderSourceReviewDialog.tsx +543 -204
  95. package/corpus/templates/content/app/components/editor/extensions/ContentReferenceNode.tsx +82 -0
  96. package/corpus/templates/content/app/global.css +9 -0
  97. package/corpus/templates/content/app/hooks/use-content-database.ts +62 -0
  98. package/corpus/templates/content/app/i18n/zh-TW.ts +76 -0
  99. package/corpus/templates/content/app/i18n-data.ts +924 -0
  100. package/corpus/templates/content/changelog/2026-06-29-builder-review-checks-now-preserve-publish-and-unpublish-cho.md +6 -0
  101. package/corpus/templates/content/changelog/2026-06-29-database-sources-can-now-be-added-as-more-rows-or-matched.md +6 -0
  102. package/corpus/templates/content/changelog/2026-06-29-fixed-loading-the-final-rows-in-larger-databases-without-bre.md +6 -0
  103. package/corpus/templates/content/changelog/2026-06-29-reusable-mdx-references-now-preview-linked-local-documents-i.md +6 -0
  104. package/corpus/templates/content/shared/api.ts +91 -1
  105. package/corpus/templates/content/shared/builder-docs-blocks.ts +8 -0
  106. package/corpus/templates/content/shared/builder-mdx.ts +141 -4
  107. package/corpus/templates/content/shared/nfm.ts +62 -0
  108. package/corpus/templates/content/vite.config.ts +14 -7
  109. package/corpus/templates/design/.agents/skills/design-systems/SKILL.md +10 -11
  110. package/corpus/templates/design/AGENTS.md +5 -0
  111. package/corpus/templates/design/_gitignore +7 -0
  112. package/corpus/templates/design/actions/apply-visual-edit.ts +22 -12
  113. package/corpus/templates/design/actions/create-design-system.ts +15 -4
  114. package/corpus/templates/design/actions/create-file.ts +20 -1
  115. package/corpus/templates/design/actions/delete-design-system.ts +2 -2
  116. package/corpus/templates/design/actions/duplicate-design.ts +35 -9
  117. package/corpus/templates/design/actions/generate-design.ts +146 -69
  118. package/corpus/templates/design/actions/generate-screens.ts +51 -19
  119. package/corpus/templates/design/actions/get-design-snapshot.ts +5 -1
  120. package/corpus/templates/design/actions/get-design.ts +2 -0
  121. package/corpus/templates/design/actions/import-design-project.ts +28 -9
  122. package/corpus/templates/design/actions/import-document.ts +22 -8
  123. package/corpus/templates/design/actions/index-design-system-with-builder.ts +6 -153
  124. package/corpus/templates/design/actions/navigate.ts +105 -54
  125. package/corpus/templates/design/actions/set-default-design-system.ts +17 -3
  126. package/corpus/templates/design/actions/show-design-questions.ts +2 -0
  127. package/corpus/templates/design/actions/update-design.ts +2 -1
  128. package/corpus/templates/design/actions/view-screen.ts +12 -6
  129. package/corpus/templates/design/app/components/design/CanvasContextMenu.tsx +4 -4
  130. package/corpus/templates/design/app/components/design/DesignCanvas.tsx +159 -41
  131. package/corpus/templates/design/app/components/design/DesignExtensionsPanel.tsx +8 -4
  132. package/corpus/templates/design/app/components/design/DrawOverlay.tsx +37 -42
  133. package/corpus/templates/design/app/components/design/EditPanel.tsx +336 -183
  134. package/corpus/templates/design/app/components/design/LayersPanel.tsx +153 -34
  135. package/corpus/templates/design/app/components/design/MultiScreenCanvas.tsx +135 -33
  136. package/corpus/templates/design/app/components/design/QuestionFlow.tsx +6 -0
  137. package/corpus/templates/design/app/components/design/TweaksPanel.tsx +2 -1
  138. package/corpus/templates/design/app/components/design/inspector/AlignmentMatrix.tsx +4 -10
  139. package/corpus/templates/design/app/components/design/inspector/AutoLayoutMatrix.tsx +84 -43
  140. package/corpus/templates/design/app/components/design/inspector/ConstraintsWidget.tsx +4 -4
  141. package/corpus/templates/design/app/components/design/inspector/{FigmaColorPicker.tsx → DesignColorPicker.tsx} +89 -62
  142. package/corpus/templates/design/app/components/design/inspector/ExportSettingsPanel.tsx +14 -26
  143. package/corpus/templates/design/app/components/design/inspector/GradientEditor.tsx +40 -12
  144. package/corpus/templates/design/app/components/design/inspector/ImageFillControls.tsx +13 -4
  145. package/corpus/templates/design/app/components/design/inspector/SHADER_INTEGRATION.md +13 -13
  146. package/corpus/templates/design/app/components/design/inspector/ScrubInput.tsx +13 -9
  147. package/corpus/templates/design/app/components/design/inspector/ShaderControls.tsx +13 -4
  148. package/corpus/templates/design/app/components/design/inspector/ShaderFillsPanel.tsx +6 -6
  149. package/corpus/templates/design/app/components/design/inspector/{figma-icons.tsx → design-icons.tsx} +2 -2
  150. package/corpus/templates/design/app/components/design/inspector/index.ts +12 -12
  151. package/corpus/templates/design/app/components/design/inspector/scrub-input-utils.ts +5 -2
  152. package/corpus/templates/design/app/components/editor/PromptDialog.tsx +3 -3
  153. package/corpus/templates/design/app/components/layout/Layout.tsx +5 -2
  154. package/corpus/templates/design/app/components/layout/Sidebar.tsx +1 -1
  155. package/corpus/templates/design/app/components/visual-editor/CanvasCommentPins.tsx +167 -91
  156. package/corpus/templates/design/app/components/visual-editor/DrawOverlay.tsx +16 -3
  157. package/corpus/templates/design/app/components/visual-editor/SaveStatusIndicator.tsx +15 -0
  158. package/corpus/templates/design/app/global.css +4 -0
  159. package/corpus/templates/design/app/hooks/use-design-system.ts +4 -1
  160. package/corpus/templates/design/app/hooks/use-navigation-state.ts +38 -3
  161. package/corpus/templates/design/app/hooks/useDesignHotkeys.ts +9 -2
  162. package/corpus/templates/design/app/i18n/zh-TW.ts +22 -0
  163. package/corpus/templates/design/app/i18n-data.ts +527 -0
  164. package/corpus/templates/design/app/lib/design-systems.ts +6 -4
  165. package/corpus/templates/design/app/lib/design-templates.ts +15 -3
  166. package/corpus/templates/design/app/pages/DesignEditor.tsx +641 -158
  167. package/corpus/templates/design/app/pages/DesignSystemSetup.tsx +42 -34
  168. package/corpus/templates/design/app/pages/VisualEdit.tsx +100 -0
  169. package/corpus/templates/design/app/root.tsx +42 -9
  170. package/corpus/templates/design/app/routes/visual-edit.tsx +7 -0
  171. package/corpus/templates/design/changelog/2026-06-28-live-cursors-now-keep-names-beside-a-cleaner-pointer-marker.md +1 -1
  172. package/corpus/templates/design/changelog/2026-06-28-mode-switching-now-lives-in-a-compact-bottom-right-icon-dock.md +1 -1
  173. package/corpus/templates/design/changelog/2026-06-28-visual-code-design-mode.md +6 -0
  174. package/corpus/templates/design/changelog/2026-06-29-design-generation-prompts-now-show-connect-ai-before-sending.md +6 -0
  175. package/corpus/templates/design/changelog/2026-06-29-design-mode-top-chrome-now-groups-collaborators-preview-shar.md +1 -1
  176. package/corpus/templates/design/changelog/2026-06-29-fixed-design-editor-exports-and-gradient-edits-so-multi-scre.md +6 -0
  177. package/corpus/templates/design/changelog/2026-06-29-longer-hosted-agent-turns.md +6 -0
  178. package/corpus/templates/design/changelog/2026-06-29-png-export-handles-modern-css-color-functions-more-reliably.md +6 -0
  179. package/corpus/templates/design/changelog/2026-06-29-png-export-now-ignores-duplicate-clicks-while-a-download-is-.md +6 -0
  180. package/corpus/templates/design/changelog/2026-06-29-public-visual-edit-and-shared-design-links-now-invite-visito.md +6 -0
  181. package/corpus/templates/design/changelog/2026-06-29-visual-edit-actions-now-reject-missing-design-targets-before.md +6 -0
  182. package/corpus/templates/design/e2e/README.md +71 -0
  183. package/corpus/templates/design/e2e/global-setup.ts +157 -0
  184. package/corpus/templates/design/e2e/helpers.ts +148 -0
  185. package/corpus/templates/design/netlify.toml +3 -4
  186. package/corpus/templates/design/package.json +5 -1
  187. package/corpus/templates/design/playwright.config.ts +51 -0
  188. package/corpus/templates/design/server/handlers/index-design-system-with-builder.ts +121 -0
  189. package/corpus/templates/design/server/handlers/uploads.ts +89 -38
  190. package/corpus/templates/design/server/lib/builder-design-system-proxy.ts +181 -0
  191. package/corpus/templates/design/server/lib/coding-handoff.ts +33 -4
  192. package/corpus/templates/design/server/lib/design-export.ts +35 -8
  193. package/corpus/templates/design/server/plugins/agent-chat.ts +4 -0
  194. package/corpus/templates/design/server/plugins/auth.ts +10 -1
  195. package/corpus/templates/design/server/routes/api/index-design-system-with-builder.post.ts +1 -0
  196. package/corpus/templates/design/shared/api.ts +2 -0
  197. package/corpus/templates/design/shared/apply-edits.ts +12 -8
  198. package/corpus/templates/design/shared/canvas-math.ts +19 -1
  199. package/corpus/templates/design/shared/code-layer.ts +87 -28
  200. package/corpus/templates/design/shared/generation-session.ts +1 -0
  201. package/corpus/templates/design/shared/resolve-tweaks.ts +4 -3
  202. package/corpus/templates/design/shared/shader-presets.ts +10 -0
  203. package/corpus/templates/design/shared/source-mode.ts +9 -0
  204. package/corpus/templates/design/vitest.config.ts +2 -1
  205. package/corpus/templates/mail/app/components/layout/AppLayout.tsx +1 -1
  206. package/corpus/templates/plan/.agents/skills/visual-plan/references/canvas.md +1 -1
  207. package/corpus/templates/plan/AGENTS.md +1 -1
  208. package/corpus/templates/plan/actions/create-plan-design.ts +1 -1
  209. package/corpus/templates/plan/actions/validate-local-plan-source.ts +2 -10
  210. package/corpus/templates/plan/app/pages/PlansPage.tsx +1 -0
  211. package/corpus/templates/plan/docs/commenting-ux-plan.md +2 -2
  212. package/corpus/templates/plan/server/plan-content.ts +1 -1
  213. package/corpus/templates/plan/server/ui-plan-html.ts +2 -2
  214. package/corpus/templates/slides/actions/index-design-system-with-builder.ts +6 -153
  215. package/corpus/templates/slides/app/components/design-system/DesignSystemSetup.tsx +53 -38
  216. package/corpus/templates/slides/app/components/design-system/{fig-import-response.ts → builder-index-response.ts} +9 -6
  217. package/corpus/templates/slides/app/components/visual-editor/MultiSelectChip.tsx +1 -1
  218. package/corpus/templates/slides/changelog/2026-06-29-design-system-setup-now-indexes-uploaded-design-files-throug.md +6 -0
  219. package/corpus/templates/slides/changelog/2026-06-29-longer-hosted-agent-turns.md +6 -0
  220. package/corpus/templates/slides/netlify.toml +3 -6
  221. package/corpus/templates/slides/server/handlers/index-design-system-with-builder.ts +116 -0
  222. package/corpus/templates/slides/server/lib/builder-design-system-proxy.ts +179 -0
  223. package/corpus/templates/slides/server/plugins/agent-chat.ts +4 -1
  224. package/corpus/templates/slides/server/routes/api/index-design-system-with-builder.post.ts +1 -0
  225. package/dist/action.d.ts +15 -0
  226. package/dist/action.d.ts.map +1 -1
  227. package/dist/action.js +6 -0
  228. package/dist/action.js.map +1 -1
  229. package/dist/agent/durable-background.d.ts +9 -7
  230. package/dist/agent/durable-background.d.ts.map +1 -1
  231. package/dist/agent/durable-background.js +27 -11
  232. package/dist/agent/durable-background.js.map +1 -1
  233. package/dist/agent/production-agent.d.ts +7 -0
  234. package/dist/agent/production-agent.d.ts.map +1 -1
  235. package/dist/agent/production-agent.js +4 -1
  236. package/dist/agent/production-agent.js.map +1 -1
  237. package/dist/agent/run-loop-with-resume.d.ts +2 -1
  238. package/dist/agent/run-loop-with-resume.d.ts.map +1 -1
  239. package/dist/agent/run-loop-with-resume.js +2 -2
  240. package/dist/agent/run-loop-with-resume.js.map +1 -1
  241. package/dist/brand-kit/fig/index.d.ts +4 -4
  242. package/dist/brand-kit/fig/index.d.ts.map +1 -1
  243. package/dist/brand-kit/fig/index.js +14 -27
  244. package/dist/brand-kit/fig/index.js.map +1 -1
  245. package/dist/cli/create.d.ts.map +1 -1
  246. package/dist/cli/create.js +1 -0
  247. package/dist/cli/create.js.map +1 -1
  248. package/dist/cli/index.js +1 -1
  249. package/dist/cli/index.js.map +1 -1
  250. package/dist/cli/mcp-config-writers.d.ts +15 -7
  251. package/dist/cli/mcp-config-writers.d.ts.map +1 -1
  252. package/dist/cli/mcp-config-writers.js +198 -45
  253. package/dist/cli/mcp-config-writers.js.map +1 -1
  254. package/dist/cli/skills.d.ts +1 -1
  255. package/dist/cli/skills.d.ts.map +1 -1
  256. package/dist/cli/skills.js +18 -3
  257. package/dist/cli/skills.js.map +1 -1
  258. package/dist/client/AssistantChat.d.ts.map +1 -1
  259. package/dist/client/AssistantChat.js +11 -1
  260. package/dist/client/AssistantChat.js.map +1 -1
  261. package/dist/client/agent-chat.d.ts.map +1 -1
  262. package/dist/client/agent-chat.js +15 -2
  263. package/dist/client/agent-chat.js.map +1 -1
  264. package/dist/client/composer/PromptComposer.d.ts.map +1 -1
  265. package/dist/client/composer/PromptComposer.js +35 -1
  266. package/dist/client/composer/PromptComposer.js.map +1 -1
  267. package/dist/client/org/OrgSwitcher.js +1 -1
  268. package/dist/client/org/OrgSwitcher.js.map +1 -1
  269. package/dist/client/sharing/ShareButton.d.ts +1 -1
  270. package/dist/client/sharing/ShareButton.d.ts.map +1 -1
  271. package/dist/client/sharing/ShareButton.js +2 -15
  272. package/dist/client/sharing/ShareButton.js.map +1 -1
  273. package/dist/collab/presence.d.ts +1 -1
  274. package/dist/collab/presence.js +1 -1
  275. package/dist/collab/presence.js.map +1 -1
  276. package/dist/collab/routes.d.ts +1 -1
  277. package/dist/file-upload/actions/upload-image.d.ts +2 -2
  278. package/dist/mcp/connect-route.d.ts.map +1 -1
  279. package/dist/mcp/connect-route.js +34 -5
  280. package/dist/mcp/connect-route.js.map +1 -1
  281. package/dist/notifications/routes.d.ts +2 -2
  282. package/dist/observability/routes.d.ts +8 -8
  283. package/dist/resources/handlers.d.ts +1 -1
  284. package/dist/server/action-discovery.d.ts.map +1 -1
  285. package/dist/server/action-discovery.js +5 -0
  286. package/dist/server/action-discovery.js.map +1 -1
  287. package/dist/server/agent-chat-plugin.d.ts +6 -0
  288. package/dist/server/agent-chat-plugin.d.ts.map +1 -1
  289. package/dist/server/agent-chat-plugin.js +12 -3
  290. package/dist/server/agent-chat-plugin.js.map +1 -1
  291. package/dist/server/agent-engine-api-key-route.d.ts +1 -1
  292. package/dist/sharing/registry.d.ts.map +1 -1
  293. package/dist/sharing/registry.js +11 -0
  294. package/dist/sharing/registry.js.map +1 -1
  295. package/dist/templates/default/pnpm-workspace.yaml +1 -0
  296. package/dist/templates/workspace-root/pnpm-workspace.yaml +1 -0
  297. package/docs/content/locales/ar-SA/real-time-collaboration.mdx +2 -2
  298. package/docs/content/locales/ar-SA/template-design.mdx +1 -1
  299. package/docs/content/locales/de-DE/real-time-collaboration.mdx +3 -3
  300. package/docs/content/locales/de-DE/template-design.mdx +1 -1
  301. package/docs/content/locales/es-ES/real-time-collaboration.mdx +2 -2
  302. package/docs/content/locales/es-ES/template-design.mdx +1 -1
  303. package/docs/content/locales/fr-FR/real-time-collaboration.mdx +2 -2
  304. package/docs/content/locales/fr-FR/template-design.mdx +1 -1
  305. package/docs/content/locales/hi-IN/template-design.mdx +1 -1
  306. package/docs/content/locales/ja-JP/real-time-collaboration.mdx +2 -2
  307. package/docs/content/locales/ja-JP/template-design.mdx +1 -1
  308. package/docs/content/locales/ko-KR/real-time-collaboration.mdx +2 -2
  309. package/docs/content/locales/ko-KR/template-design.mdx +1 -1
  310. package/docs/content/locales/pt-BR/real-time-collaboration.mdx +2 -2
  311. package/docs/content/locales/pt-BR/template-design.mdx +1 -1
  312. package/docs/content/locales/zh-CN/real-time-collaboration.mdx +2 -2
  313. package/docs/content/locales/zh-CN/template-design.mdx +1 -1
  314. package/docs/content/locales/zh-TW/real-time-collaboration.mdx +2 -2
  315. package/docs/content/locales/zh-TW/template-design.mdx +1 -1
  316. package/docs/content/real-time-collaboration.mdx +2 -2
  317. package/docs/content/template-design.mdx +1 -1
  318. package/package.json +3 -7
  319. package/src/templates/default/pnpm-workspace.yaml +1 -0
  320. package/src/templates/workspace-root/pnpm-workspace.yaml +1 -0
  321. package/corpus/core/src/brand-kit/fig/decode.ts +0 -410
  322. package/corpus/core/src/brand-kit/fig/extract-design-system.ts +0 -947
  323. package/corpus/core/src/brand-kit/fig/fig-to-html.ts +0 -1906
  324. package/corpus/templates/design/actions/import-figma.ts +0 -55
  325. package/corpus/templates/design/changelog/2026-06-28-figma-style-code-design-mode.md +0 -6
  326. package/corpus/templates/design/server/handlers/import-figma-system.ts +0 -86
  327. package/corpus/templates/design/server/routes/api/import-figma-system.post.ts +0 -1
  328. package/corpus/templates/slides/server/handlers/import-figma-system.ts +0 -101
  329. package/corpus/templates/slides/server/routes/api/import-figma-system.post.ts +0 -1
  330. package/dist/brand-kit/fig/decode.d.ts +0 -33
  331. package/dist/brand-kit/fig/decode.d.ts.map +0 -1
  332. package/dist/brand-kit/fig/decode.js +0 -358
  333. package/dist/brand-kit/fig/decode.js.map +0 -1
  334. package/dist/brand-kit/fig/extract-design-system.d.ts +0 -44
  335. package/dist/brand-kit/fig/extract-design-system.d.ts.map +0 -1
  336. package/dist/brand-kit/fig/extract-design-system.js +0 -752
  337. package/dist/brand-kit/fig/extract-design-system.js.map +0 -1
  338. package/dist/brand-kit/fig/fig-to-html.d.ts +0 -246
  339. package/dist/brand-kit/fig/fig-to-html.d.ts.map +0 -1
  340. package/dist/brand-kit/fig/fig-to-html.js +0 -1506
  341. package/dist/brand-kit/fig/fig-to-html.js.map +0 -1
@@ -1,1906 +0,0 @@
1
- /**
2
- * Convert a decoded Figma document (NODE_CHANGES message) into one HTML
3
- * file per top-level frame. Each node renders as a <div> (or <span> for
4
- * TEXT) with an inline `style="..."` covering layout, background, border,
5
- * radius, shadows, blurs, text, transform, autolayout (flexbox), and
6
- * opacity/blend. Component instances are inlined and tagged with
7
- * data-component-name / data-variant-name / data-component-description /
8
- * data-component-doc-link / data-annotations attributes, matching the
9
- * figma-plugin smart-export conventions.
10
- */
11
-
12
- import * as path from "node:path";
13
-
14
- export interface Guid {
15
- sessionID: number;
16
- localID: number;
17
- }
18
-
19
- interface Color {
20
- r: number;
21
- g: number;
22
- b: number;
23
- a: number;
24
- }
25
-
26
- interface Paint {
27
- type?: string;
28
- color?: Color;
29
- opacity?: number;
30
- visible?: boolean;
31
- blendMode?: string;
32
- stops?: Array<{ color: Color; position: number }>;
33
- transform?: {
34
- m00: number;
35
- m01: number;
36
- m02: number;
37
- m10: number;
38
- m11: number;
39
- m12: number;
40
- };
41
- // hash may be a hex string (JSON-decoded) or raw bytes (kiwi-decoder).
42
- image?: { hash?: string | Uint8Array | number[]; name?: string };
43
- imageScaleMode?: string;
44
- rotation?: number;
45
- scale?: number;
46
- }
47
-
48
- interface Effect {
49
- type?: string;
50
- visible?: boolean;
51
- color?: Color;
52
- offset?: { x: number; y: number };
53
- radius?: number;
54
- spread?: number;
55
- blendMode?: string;
56
- }
57
-
58
- interface Annotation {
59
- label?: string;
60
- labelV2?: string;
61
- properties?: unknown[];
62
- }
63
-
64
- interface ComponentPropDef {
65
- id?: Guid;
66
- name?: string;
67
- type?: string;
68
- }
69
-
70
- export interface FigNode {
71
- guid?: Guid;
72
- // Library-stable identifier used by override paths (`symbolOverrides[].guidPath`)
73
- // and `derivedSymbolData[].guidPath`. When a node is a remix of a library
74
- // component, the `guid` is local to this document but `overrideKey` is the
75
- // GUID from the source library. Override-path matching MUST use this when
76
- // available so that overrides authored against the library still apply.
77
- overrideKey?: Guid;
78
- parentIndex?: { guid?: Guid; position?: string };
79
- type?: string;
80
- name?: string;
81
- description?: string;
82
- componentKey?: string;
83
- componentPropDefs?: ComponentPropDef[];
84
- componentPropAssignments?: unknown[];
85
- componentPropRefs?: unknown[];
86
- annotations?: Annotation[];
87
- isSymbolPublishable?: boolean;
88
- visible?: boolean;
89
- size?: { x: number; y: number };
90
- transform?: {
91
- m00: number;
92
- m01: number;
93
- m02: number;
94
- m10: number;
95
- m11: number;
96
- m12: number;
97
- };
98
- fillPaints?: Paint[];
99
- strokePaints?: Paint[];
100
- // Style references — when present, the actual paint comes from the
101
- // referenced shared-style node's fillPaints/strokePaints rather than the
102
- // stale `fillPaints`/`strokePaints` cached on this node.
103
- styleIdForFill?: {
104
- guid?: Guid;
105
- assetRef?: { key?: string; version?: string };
106
- };
107
- styleIdForStroke?: {
108
- guid?: Guid;
109
- assetRef?: { key?: string; version?: string };
110
- };
111
- styleIdForText?: {
112
- guid?: Guid;
113
- assetRef?: { key?: string; version?: string };
114
- };
115
- // Library style nodes carry their stable key here (matched against
116
- // `styleIdForFill.assetRef.key` etc. on the consuming nodes).
117
- key?: string;
118
- styleType?: string;
119
- strokeWeight?: number;
120
- strokeAlign?: string;
121
- effects?: Effect[];
122
- opacity?: number;
123
- blendMode?: string;
124
- cornerRadius?: number;
125
- rectangleTopLeftCornerRadius?: number;
126
- rectangleTopRightCornerRadius?: number;
127
- rectangleBottomLeftCornerRadius?: number;
128
- rectangleBottomRightCornerRadius?: number;
129
- fontSize?: number;
130
- fontName?: { family?: string; style?: string };
131
- letterSpacing?: { value: number; units?: string };
132
- lineHeight?: { value: number; units?: string };
133
- textAlignHorizontal?: string;
134
- textAlignVertical?: string;
135
- textData?: { characters?: string };
136
- textAutoResize?: string;
137
- symbolData?: {
138
- symbolID?: Guid;
139
- symbolOverrides?: SymbolOverride[];
140
- };
141
- stackMode?: string;
142
- stackPrimaryAlignItems?: string;
143
- stackCounterAlignItems?: string;
144
- stackSpacing?: number;
145
- stackHorizontalPadding?: number;
146
- stackVerticalPadding?: number;
147
- stackPaddingLeft?: number;
148
- stackPaddingRight?: number;
149
- stackPaddingTop?: number;
150
- stackPaddingBottom?: number;
151
- stackPrimarySizing?: string;
152
- stackCounterSizing?: string;
153
- stackChildPrimaryGrow?: number;
154
- stackChildAlignSelf?: string;
155
- resizeToFit?: boolean;
156
- horizontalConstraint?: string;
157
- verticalConstraint?: string;
158
- frameMaskDisabled?: boolean;
159
- internalOnly?: boolean;
160
- // Vector geometry. Each path's `commandsBlob` is an index into the
161
- // document `blobs` array; the bytes there are a Figma path command
162
- // stream (see decodePathCommands).
163
- fillGeometry?: Array<{
164
- commandsBlob?: number;
165
- windingRule?: string;
166
- styleID?: number;
167
- }>;
168
- strokeGeometry?: Array<{
169
- commandsBlob?: number;
170
- windingRule?: string;
171
- styleID?: number;
172
- }>;
173
- strokeJoin?: string;
174
- strokeCap?: string;
175
- strokeDashes?: number[];
176
- vectorData?: {
177
- normalizedSize?: { x: number; y: number };
178
- vectorNetworkBlob?: number;
179
- };
180
- }
181
-
182
- /**
183
- * Split a Figma component master name into a base component name and a
184
- * variant suffix. Figma uses two conventions:
185
- *
186
- * - Slash-separated: "ComponentName/VariantA/VariantB" — everything after
187
- * the first slash is the variant name (this matches the plugin's
188
- * smart-export behavior).
189
- * - Variant-set children: a SYMBOL named like "Style=Action, Size=Large"
190
- * is one variant inside a parent component-set FRAME. In that case the
191
- * SYMBOL name IS the variant key/value list and the real component
192
- * name is the parent FRAME's name (resolved separately by the caller).
193
- */
194
- function isVariantSymbolName(name: string | undefined): boolean {
195
- if (!name) return false;
196
- // Variant SYMBOL naming: comma-separated `Key=Value` pairs.
197
- return /^[^/=]+=[^=]+(,\s*[^/=]+=[^=]+)*$/.test(name);
198
- }
199
-
200
- function splitComponentName(name: string | undefined): {
201
- base: string;
202
- variant: string | null;
203
- } {
204
- if (!name) return { base: "", variant: null };
205
- if (isVariantSymbolName(name)) return { base: "", variant: name };
206
- const i = name.indexOf("/");
207
- if (i < 0) return { base: name, variant: null };
208
- return { base: name.slice(0, i), variant: name.slice(i + 1) };
209
- }
210
-
211
- /**
212
- * Resolve the canonical component name + variant string for a SYMBOL,
213
- * walking up to the parent component-set FRAME when the SYMBOL itself is
214
- * a variant child (e.g. "Style=Action" inside a "Right Element" FRAME).
215
- */
216
- function resolveComponentIdentity(
217
- symbol: FigNode,
218
- ctx: Ctx,
219
- ): { base: string; variant: string | null } {
220
- const ident = splitComponentName(symbol.name);
221
- if (ident.base) return ident;
222
- // Variant SYMBOL — use the parent FRAME (component set) as the base name.
223
- const parentKey = guidKey(symbol.parentIndex?.guid);
224
- const parent = ctx.byGuid.get(parentKey);
225
- const parentName = parent?.name?.trim();
226
- if (parentName) {
227
- return { base: parentName, variant: ident.variant };
228
- }
229
- return { base: symbol.name ?? "", variant: null };
230
- }
231
-
232
- function htmlToPlain(html: string | undefined): string {
233
- if (!html) return "";
234
- return html
235
- .replace(/<br\s*\/?>/gi, "\n")
236
- .replace(/<\/p>\s*<p[^>]*>/gi, "\n\n")
237
- .replace(/<[^>]+>/g, "")
238
- .replace(/&nbsp;/g, " ")
239
- .replace(/&amp;/g, "&")
240
- .replace(/&lt;/g, "<")
241
- .replace(/&gt;/g, ">")
242
- .replace(/&quot;/g, '"')
243
- .replace(/&#39;/g, "'")
244
- .trim();
245
- }
246
-
247
- function extractDocLinks(html: string | undefined): string[] {
248
- if (!html) return [];
249
- const out: string[] = [];
250
- const re = /href="([^"]+)"/gi;
251
- let m: RegExpExecArray | null;
252
- while ((m = re.exec(html)) !== null) out.push(m[1]!);
253
- return out;
254
- }
255
-
256
- export function guidKey(g: Guid | undefined): string {
257
- return g ? `${g.sessionID}:${g.localID}` : "";
258
- }
259
-
260
- /**
261
- * Collect the raw Figma component-prop data on a node into a single object
262
- * suitable for stringifying into a `props="..."` attribute.
263
- *
264
- * - SYMBOL nodes get their `componentPropDefs` (the prop schema)
265
- * - INSTANCE nodes get the `componentPropAssignments` (overrides) plus any
266
- * `componentPropRefs` (per-child wirings) and the master's defs for
267
- * context.
268
- * - Any node may have its own `componentPropRefs` (e.g. an inner layer
269
- * bound to a parent component prop).
270
- */
271
- function collectRawProps(
272
- node: FigNode,
273
- componentSymbol: FigNode | null,
274
- ): Record<string, unknown> | null {
275
- const out: Record<string, unknown> = {};
276
- const sym = componentSymbol ?? (node.type === "SYMBOL" ? node : null);
277
- if (sym?.componentPropDefs?.length) out.defs = sym.componentPropDefs;
278
- if (
279
- node.componentPropAssignments &&
280
- (node.componentPropAssignments as unknown[]).length
281
- )
282
- out.assignments = node.componentPropAssignments;
283
- if (node.componentPropRefs && (node.componentPropRefs as unknown[]).length)
284
- out.refs = node.componentPropRefs;
285
- return Object.keys(out).length > 0 ? out : null;
286
- }
287
-
288
- /**
289
- * A resolved Figma component prop value, normalized across the (legacy)
290
- * `value` and (modern) `varValue` shapes. Only the fields we actually act on
291
- * are extracted: bool (for VISIBLE), text (for TEXT_DATA), and guid (for
292
- * OVERRIDDEN_SYMBOL_ID and SLOT_CONTENT_ID).
293
- */
294
- interface ResolvedPropValue {
295
- bool?: boolean;
296
- text?: string;
297
- guid?: Guid;
298
- }
299
-
300
- function resolvePropAssignment(a: unknown): ResolvedPropValue | null {
301
- const ax = a as {
302
- value?: {
303
- boolValue?: boolean;
304
- textValue?: { characters?: string };
305
- guidValue?: Guid;
306
- };
307
- varValue?: {
308
- value?: {
309
- boolValue?: boolean;
310
- textValue?: { characters?: string };
311
- guidValue?: Guid;
312
- symbolIdValue?: { guid?: Guid };
313
- textIdValue?: { value?: string };
314
- };
315
- };
316
- };
317
- const vv = ax.varValue?.value;
318
- const v = ax.value;
319
- const out: ResolvedPropValue = {};
320
- if (typeof vv?.boolValue === "boolean") out.bool = vv.boolValue;
321
- else if (typeof v?.boolValue === "boolean") out.bool = v.boolValue;
322
- if (vv?.textValue?.characters !== undefined)
323
- out.text = vv.textValue.characters;
324
- else if (v?.textValue?.characters !== undefined)
325
- out.text = v.textValue.characters;
326
- else if (vv?.textIdValue?.value !== undefined)
327
- out.text = vv.textIdValue.value;
328
- if (vv?.symbolIdValue?.guid) out.guid = vv.symbolIdValue.guid;
329
- else if (vv?.guidValue) out.guid = vv.guidValue;
330
- else if (v?.guidValue) out.guid = v.guidValue;
331
- return Object.keys(out).length > 0 ? out : null;
332
- }
333
-
334
- function buildPropEnv(
335
- node: FigNode,
336
- inherited: Map<string, ResolvedPropValue>,
337
- ): Map<string, ResolvedPropValue> {
338
- const assignments = (node.componentPropAssignments ?? []) as Array<{
339
- defID?: Guid;
340
- }>;
341
- if (assignments.length === 0) return inherited;
342
- const next = new Map(inherited);
343
- for (const a of assignments) {
344
- const key = guidKey(a.defID);
345
- if (!key) continue;
346
- const resolved = resolvePropAssignment(a);
347
- if (resolved) next.set(key, resolved);
348
- }
349
- return next;
350
- }
351
-
352
- /**
353
- * Apply parent-instance prop overrides to a node. Returns either the same
354
- * node (no overrides), a shallow-cloned node with `textData` / `symbolData`
355
- * patched, or `null` to indicate the node should be hidden by a VISIBLE
356
- * prop ref resolving to false.
357
- */
358
- function applyPropRefs(
359
- node: FigNode,
360
- env: Map<string, ResolvedPropValue>,
361
- ): FigNode | null {
362
- const refs = (node.componentPropRefs ?? []) as Array<{
363
- defID?: Guid;
364
- componentPropNodeField?: string;
365
- }>;
366
- if (refs.length === 0 || env.size === 0) return node;
367
- let patched = node;
368
- for (const ref of refs) {
369
- const v = env.get(guidKey(ref.defID));
370
- if (!v) continue;
371
- const field = ref.componentPropNodeField;
372
- if (field === "VISIBLE" && v.bool === false) return null;
373
- if (field === "TEXT_DATA" && v.text !== undefined) {
374
- patched = {
375
- ...patched,
376
- textData: { ...(patched.textData ?? {}), characters: v.text },
377
- };
378
- }
379
- if (field === "OVERRIDDEN_SYMBOL_ID" && v.guid) {
380
- patched = {
381
- ...patched,
382
- symbolData: { ...(patched.symbolData ?? {}), symbolID: v.guid },
383
- };
384
- }
385
- }
386
- return patched;
387
- }
388
-
389
- /**
390
- * A raw symbol override entry from `symbolData.symbolOverrides`. It is
391
- * effectively a partial NodeChange targeting a descendant of the master
392
- * symbol via `guidPath`. Any field present (other than `guidPath` and
393
- * `overriddenSymbolID`) is shallow-merged onto the descendant node when
394
- * it's emitted, so layout-affecting overrides like `size`, `textAutoResize`,
395
- * `stackChildAlignSelf`, `stackCounterSizing`, `textAlignVertical`, etc.
396
- * all flow through.
397
- */
398
- interface SymbolOverride extends Partial<FigNode> {
399
- overriddenSymbolID?: Guid;
400
- guidPath?: { guids?: Guid[] };
401
- }
402
-
403
- type OverrideEntry = SymbolOverride;
404
-
405
- /**
406
- * An active override scope contributed by an enclosing INSTANCE. `startIndex`
407
- * is the position in the running guid path at which this instance's master
408
- * tree begins; override keys in `map` are joined-guid paths RELATIVE to that
409
- * point (matching what Figma stores in `symbolOverrides[].guidPath`).
410
- *
411
- * Multiple layers stack: an outer instance's overrides remain valid even
412
- * after we descend through nested inner instances, because the descendant's
413
- * absolute path under the outer instance is still well-defined.
414
- */
415
- interface OverrideLayer {
416
- startIndex: number;
417
- map: Map<string, OverrideEntry>;
418
- }
419
-
420
- function buildSymbolOverrideLayer(node: FigNode): Map<string, OverrideEntry> {
421
- const out = new Map<string, OverrideEntry>();
422
- for (const o of node.symbolData?.symbolOverrides ?? []) {
423
- const guids = o.guidPath?.guids ?? [];
424
- if (guids.length === 0) continue;
425
- const key = guids.map((g) => guidKey(g)).join("/");
426
- // Multiple override entries can share the same guidPath (e.g. one with
427
- // `overriddenSymbolID` for a variant swap and another with layout
428
- // tweaks). Merge them so neither is lost.
429
- const existing = out.get(key);
430
- if (existing) {
431
- out.set(key, { ...existing, ...o });
432
- } else {
433
- out.set(key, o);
434
- }
435
- }
436
- // `derivedSymbolData` carries pre-computed geometry / text layout for
437
- // descendants of this instance whose actual definition lives in a remote
438
- // library (so the local document has only a stub master). Each entry is
439
- // keyed by a guidPath into the library tree — same coordinate space as
440
- // `symbolOverrides[].guidPath` — so we can fold them into the same layer.
441
- // Only fill/stroke geometry are merged; positional fields (`transform`,
442
- // `size`) and `derivedTextData` are intentionally skipped because they
443
- // describe library-resolved layout that would overwrite the (already
444
- // correct) values cached on the local master node.
445
- for (const d of (
446
- node as {
447
- derivedSymbolData?: Array<
448
- Partial<FigNode> & { guidPath?: { guids?: Guid[] } }
449
- >;
450
- }
451
- ).derivedSymbolData ?? []) {
452
- const guids = d.guidPath?.guids ?? [];
453
- if (guids.length === 0) continue;
454
- if (!d.fillGeometry?.length && !d.strokeGeometry?.length) continue;
455
- const key = guids.map((g) => guidKey(g)).join("/");
456
- const patch: SymbolOverride = {};
457
- if (d.fillGeometry?.length) patch.fillGeometry = d.fillGeometry;
458
- if (d.strokeGeometry?.length) patch.strokeGeometry = d.strokeGeometry;
459
- const existing = out.get(key);
460
- out.set(key, existing ? { ...existing, ...patch } : patch);
461
- }
462
- return out;
463
- }
464
-
465
- /**
466
- * Apply any matching override entry from the active override layers to a
467
- * node about to be emitted. Returns `null` if the node is hidden by an
468
- * override; otherwise returns the (possibly patched) node.
469
- */
470
- function applyOverrideLayers(
471
- node: FigNode,
472
- layers: OverrideLayer[],
473
- instancePath: string[],
474
- ): FigNode | null {
475
- if (layers.length === 0) return node;
476
- // The lookup key for THIS node within a layer is the chain of inner
477
- // INSTANCE overrideKeys we've descended into since that layer was pushed,
478
- // followed by this node's own overrideKey. Override paths only grow at
479
- // INSTANCE boundaries — descending through plain frames/groups within the
480
- // same master keeps the path the same length.
481
- const nodeKey = guidKey(node.overrideKey ?? node.guid);
482
- if (!nodeKey) return node;
483
- for (const layer of layers) {
484
- const prefix = instancePath.slice(layer.startIndex);
485
- const relKey =
486
- prefix.length > 0 ? `${prefix.join("/")}/${nodeKey}` : nodeKey;
487
- const entry = layer.map.get(relKey);
488
- if (!entry) continue;
489
- if (entry.visible === false) return null;
490
- // Shallow-merge every field present on the override (except the
491
- // routing fields and `overriddenSymbolID`, which goes into symbolData).
492
- // This applies layout overrides like `size`, `textAutoResize`,
493
- // `stackChildAlignSelf`, `stackCounterSizing`, `textAlignVertical`,
494
- // styling fields, etc., in addition to text/visibility.
495
- const merged: FigNode = { ...node };
496
- for (const [field, value] of Object.entries(entry)) {
497
- if (field === "guidPath" || field === "overriddenSymbolID") continue;
498
- if (value === undefined) continue;
499
- (merged as Record<string, unknown>)[field] = value;
500
- }
501
- if (entry.overriddenSymbolID) {
502
- merged.symbolData = {
503
- ...(merged.symbolData ?? {}),
504
- symbolID: entry.overriddenSymbolID,
505
- };
506
- }
507
- node = merged;
508
- }
509
- return node;
510
- }
511
-
512
- function sanitizeFilename(name: string | undefined, fallback: string): string {
513
- if (!name) return fallback;
514
- const cleaned = name
515
- .replace(/[\\/:*?"<>|]/g, "-")
516
- .replace(/\s+/g, " ")
517
- .trim()
518
- .slice(0, 80);
519
- return cleaned || fallback;
520
- }
521
-
522
- function escapeHtmlText(s: string): string {
523
- return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
524
- }
525
-
526
- function escapeHtmlAttr(s: string): string {
527
- return s
528
- .replace(/&/g, "&amp;")
529
- .replace(/"/g, "&quot;")
530
- .replace(/</g, "&lt;")
531
- .replace(/\n/g, "&#10;");
532
- }
533
-
534
- function kebabCase(prop: string): string {
535
- return prop.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
536
- }
537
-
538
- function colorToCss(c: Color | undefined, alphaMul = 1): string | null {
539
- if (!c) return null;
540
- const r = Math.round(c.r * 255);
541
- const g = Math.round(c.g * 255);
542
- const b = Math.round(c.b * 255);
543
- const a = c.a * alphaMul;
544
- if (a >= 0.999) return `rgb(${r}, ${g}, ${b})`;
545
- return `rgba(${r}, ${g}, ${b}, ${Number(a.toFixed(3))})`;
546
- }
547
-
548
- function num(n: number | undefined): number | null {
549
- if (typeof n !== "number" || !Number.isFinite(n)) return null;
550
- return Math.round(n * 100) / 100;
551
- }
552
-
553
- function tagFor(type: string | undefined): string {
554
- // Everything renders as a real DOM tag rather than a synthetic component.
555
- // TEXT becomes <span> so it inlines nicely; everything else is <div>.
556
- if (type === "TEXT") return "span";
557
- return "div";
558
- }
559
-
560
- const STACK_ALIGN: Record<string, string> = {
561
- MIN: "flex-start",
562
- CENTER: "center",
563
- MAX: "flex-end",
564
- BASELINE: "baseline",
565
- SPACE_BETWEEN: "space-between",
566
- };
567
-
568
- const TEXT_ALIGN: Record<string, string> = {
569
- LEFT: "left",
570
- CENTER: "center",
571
- RIGHT: "right",
572
- JUSTIFIED: "justify",
573
- };
574
-
575
- function fontWeightFromStyle(style: string | undefined): number | null {
576
- if (!style) return null;
577
- const s = style.toLowerCase();
578
- if (s.includes("thin")) return 100;
579
- if (s.includes("extralight") || s.includes("ultralight")) return 200;
580
- if (s.includes("light")) return 300;
581
- if (s.includes("regular") || s === "normal") return 400;
582
- if (s.includes("medium")) return 500;
583
- if (s.includes("semibold") || s.includes("demibold")) return 600;
584
- if (s.includes("extrabold") || s.includes("ultrabold")) return 800;
585
- if (s.includes("black") || s.includes("heavy")) return 900;
586
- if (s.includes("bold")) return 700;
587
- return null;
588
- }
589
-
590
- function lengthFromUnits(
591
- v: { value: number; units?: string } | undefined,
592
- fontSize?: number,
593
- ) {
594
- if (!v) return null;
595
- if (v.units === "PIXELS") return `${num(v.value)}px`;
596
- if (v.units === "PERCENT") {
597
- if (fontSize) return `${num((v.value / 100) * fontSize)}px`;
598
- return `${num(v.value)}%`;
599
- }
600
- if (v.units === "RAW") return num(v.value);
601
- return num(v.value);
602
- }
603
-
604
- /**
605
- * Normalize a Figma image hash into a hex string. The kiwi decoder emits
606
- * the hash as a Uint8Array / number[]; the JSON-roundtripped form is
607
- * already a hex string.
608
- */
609
- function hashToHex(
610
- h: string | Uint8Array | number[] | undefined,
611
- ): string | null {
612
- if (!h) return null;
613
- if (typeof h === "string") return h;
614
- const arr = h instanceof Uint8Array ? Array.from(h) : (h as number[]);
615
- return arr.map((b) => b.toString(16).padStart(2, "0")).join("");
616
- }
617
-
618
- /**
619
- * Resolve an image hash to a usable URL path. Looks up the actual filename
620
- * (which may be `<hash>` or `<hash>.png` depending on whether the source
621
- * was a zip-format or kiwi-format `.fig`) in the ctx imageMap.
622
- */
623
- function imageUrl(hashHex: string, ctx: Ctx): string {
624
- const filename = ctx.imageMap.get(hashHex) ?? hashHex;
625
- const base = ctx.imageRefBase ?? "images";
626
- return `${base}/${filename}`;
627
- }
628
-
629
- /**
630
- * Resolve a style reference (`styleIdForFill` / `styleIdForStroke` /
631
- * `styleIdForText`) to the actual style node. Style refs come in two
632
- * flavors: a local `guid` for in-document styles and an `assetRef.key`
633
- * for library styles. Library style definitions get embedded in the
634
- * document under the same `key`, so we look them up via `ctx.byKey`.
635
- */
636
- function resolveStyleNode(
637
- ref: { guid?: Guid; assetRef?: { key?: string } } | undefined,
638
- ctx: Ctx,
639
- ): FigNode | undefined {
640
- if (!ref) return undefined;
641
- if (ref.guid) {
642
- const n = ctx.byGuid.get(guidKey(ref.guid));
643
- if (n) return n;
644
- }
645
- if (ref.assetRef?.key) {
646
- const n = ctx.byKey.get(ref.assetRef.key);
647
- if (n) return n;
648
- }
649
- return undefined;
650
- }
651
-
652
- /**
653
- * Resolve the effective fill paints for a node. When the node references a
654
- * shared FILL style via `styleIdForFill`, the cached `fillPaints` baked
655
- * into the node may be stale (the design token's actual color can have
656
- * changed since). Prefer the style node's `fillPaints` whenever a fill
657
- * style reference is present.
658
- *
659
- * Do NOT fall back to `styleIdForText` here: a text style carries
660
- * typography (font/size/weight/line-height) and its `fillPaints` is just
661
- * the swatch color used for the style's preview glyphs ("Ag") — typically
662
- * black regardless of where the style is actually applied. The text node's
663
- * own `fillPaints` is the source of truth for color.
664
- */
665
- function effectiveFillPaints(node: FigNode, ctx: Ctx): Paint[] | undefined {
666
- const style = resolveStyleNode(node.styleIdForFill, ctx);
667
- if (style?.fillPaints?.length) return style.fillPaints;
668
- return node.fillPaints;
669
- }
670
-
671
- function effectiveStrokePaints(node: FigNode, ctx: Ctx): Paint[] | undefined {
672
- const style = resolveStyleNode(node.styleIdForStroke, ctx);
673
- if (style?.fillPaints?.length) return style.fillPaints;
674
- if (style?.strokePaints?.length) return style.strokePaints;
675
- return node.strokePaints;
676
- }
677
-
678
- function paintToBackground(p: Paint, _node: FigNode, ctx: Ctx): string | null {
679
- if (p.visible === false) return null;
680
- if (p.type === "SOLID") return colorToCss(p.color, p.opacity ?? 1);
681
- if (p.type?.startsWith("GRADIENT") && Array.isArray(p.stops)) {
682
- const stops = p.stops
683
- .map(
684
- (s) =>
685
- `${colorToCss(s.color, p.opacity ?? 1)} ${num(s.position * 100)}%`,
686
- )
687
- .join(", ");
688
- if (p.type === "GRADIENT_LINEAR") return `linear-gradient(${stops})`;
689
- if (p.type === "GRADIENT_RADIAL") return `radial-gradient(${stops})`;
690
- if (p.type === "GRADIENT_ANGULAR") return `conic-gradient(${stops})`;
691
- if (p.type === "GRADIENT_DIAMOND") return `radial-gradient(${stops})`;
692
- }
693
- if (p.type === "IMAGE") {
694
- const hex = hashToHex(p.image?.hash);
695
- if (hex) return `url("${imageUrl(hex, ctx)}")`;
696
- }
697
- return null;
698
- }
699
-
700
- function backgroundShorthand(
701
- node: FigNode,
702
- ctx: Ctx,
703
- ): {
704
- backgroundColor?: string;
705
- backgroundImage?: string;
706
- backgroundSize?: string;
707
- backgroundPosition?: string;
708
- backgroundRepeat?: string;
709
- } {
710
- const fills = (effectiveFillPaints(node, ctx) ?? []).filter(
711
- (f) => f.visible !== false,
712
- );
713
- if (fills.length === 0) return {};
714
- const result: {
715
- backgroundColor?: string;
716
- backgroundImage?: string;
717
- backgroundSize?: string;
718
- backgroundPosition?: string;
719
- backgroundRepeat?: string;
720
- } = {};
721
- const bgImages: string[] = [];
722
- for (const f of fills) {
723
- if (f.type === "SOLID" && !result.backgroundColor) {
724
- const c = colorToCss(f.color, f.opacity ?? 1);
725
- if (c) result.backgroundColor = c;
726
- continue;
727
- }
728
- const v = paintToBackground(f, node, ctx);
729
- if (v) bgImages.push(v);
730
- if (f.type === "IMAGE") {
731
- if (f.imageScaleMode === "FILL") result.backgroundSize = "cover";
732
- else if (f.imageScaleMode === "FIT") result.backgroundSize = "contain";
733
- else if (f.imageScaleMode === "TILE") {
734
- result.backgroundSize = "auto";
735
- result.backgroundRepeat = "repeat";
736
- } else if (f.imageScaleMode === "STRETCH")
737
- result.backgroundSize = "100% 100%";
738
- // Figma centers image fills by default (CSS defaults to top-left, which
739
- // crops the wrong edges for FILL/FIT). TILE keeps the default origin so
740
- // the tile pattern starts at top-left.
741
- if (f.imageScaleMode !== "TILE") result.backgroundPosition = "center";
742
- }
743
- }
744
- if (bgImages.length > 0) result.backgroundImage = bgImages.join(", ");
745
- return result;
746
- }
747
-
748
- function borderShorthand(
749
- node: FigNode,
750
- ctx: Ctx,
751
- ): { border?: string; outline?: string } {
752
- const strokes = (effectiveStrokePaints(node, ctx) ?? []).filter(
753
- (p) => p.visible !== false,
754
- );
755
- const w = node.strokeWeight ?? 0;
756
- if (strokes.length === 0 || !w) return {};
757
- const first = strokes[0]!;
758
- const color = colorToCss(first.color, first.opacity ?? 1) ?? "rgb(0, 0, 0)";
759
- const decl = `${num(w)}px solid ${color}`;
760
- if (node.strokeAlign === "OUTSIDE") return { outline: decl };
761
- return { border: decl };
762
- }
763
-
764
- function radiusStyles(node: FigNode): Record<string, number | string> {
765
- const out: Record<string, number | string> = {};
766
- const corners = [
767
- node.rectangleTopLeftCornerRadius,
768
- node.rectangleTopRightCornerRadius,
769
- node.rectangleBottomRightCornerRadius,
770
- node.rectangleBottomLeftCornerRadius,
771
- ];
772
- const allEqual =
773
- corners.every((c) => c === corners[0]) &&
774
- typeof corners[0] === "number" &&
775
- corners[0] > 0;
776
- if (allEqual) {
777
- out.borderRadius = `${num(corners[0])}px`;
778
- return out;
779
- }
780
- if (corners.some((c) => typeof c === "number" && c > 0)) {
781
- out.borderTopLeftRadius = `${num(corners[0] ?? 0)}px`;
782
- out.borderTopRightRadius = `${num(corners[1] ?? 0)}px`;
783
- out.borderBottomRightRadius = `${num(corners[2] ?? 0)}px`;
784
- out.borderBottomLeftRadius = `${num(corners[3] ?? 0)}px`;
785
- return out;
786
- }
787
- if (typeof node.cornerRadius === "number" && node.cornerRadius > 0) {
788
- out.borderRadius = `${num(node.cornerRadius)}px`;
789
- }
790
- if (node.type === "ELLIPSE") out.borderRadius = "50%";
791
- return out;
792
- }
793
-
794
- function effectStyles(node: FigNode): Record<string, string> {
795
- const effects = node.effects?.filter((e) => e.visible !== false) ?? [];
796
- if (effects.length === 0) return {};
797
- const shadows: string[] = [];
798
- let blur: string | null = null;
799
- let backdropBlur: string | null = null;
800
- for (const e of effects) {
801
- if (e.type === "DROP_SHADOW") {
802
- const c = colorToCss(e.color) ?? "rgba(0, 0, 0, 0.25)";
803
- shadows.push(
804
- `${num(e.offset?.x ?? 0)}px ${num(e.offset?.y ?? 0)}px ${num(e.radius ?? 0)}px ${num(e.spread ?? 0)}px ${c}`,
805
- );
806
- } else if (e.type === "INNER_SHADOW") {
807
- const c = colorToCss(e.color) ?? "rgba(0, 0, 0, 0.25)";
808
- shadows.push(
809
- `inset ${num(e.offset?.x ?? 0)}px ${num(e.offset?.y ?? 0)}px ${num(e.radius ?? 0)}px ${num(e.spread ?? 0)}px ${c}`,
810
- );
811
- } else if (e.type === "FOREGROUND_BLUR" || e.type === "LAYER_BLUR") {
812
- blur = `blur(${num(e.radius ?? 0)}px)`;
813
- } else if (e.type === "BACKGROUND_BLUR") {
814
- backdropBlur = `blur(${num(e.radius ?? 0)}px)`;
815
- }
816
- }
817
- const out: Record<string, string> = {};
818
- if (shadows.length) out.boxShadow = shadows.join(", ");
819
- if (blur) out.filter = blur;
820
- if (backdropBlur) out.backdropFilter = backdropBlur;
821
- return out;
822
- }
823
-
824
- function transformStyle(node: FigNode): {
825
- transform?: string;
826
- transformOrigin?: string;
827
- } {
828
- const t = node.transform;
829
- if (!t) return {};
830
- // Decompose: rotation = atan2(m10, m00), scale assumed 1.
831
- const angle = Math.atan2(t.m10, t.m00);
832
- const deg = (angle * 180) / Math.PI;
833
- if (Math.abs(deg) < 0.01) return {};
834
- return { transform: `rotate(${num(deg)}deg)`, transformOrigin: "top left" };
835
- }
836
-
837
- function autolayoutStyles(node: FigNode): Record<string, string | number> {
838
- if (!node.stackMode || node.stackMode === "NONE") return {};
839
- const out: Record<string, string | number> = {
840
- display: "flex",
841
- flexDirection: node.stackMode === "VERTICAL" ? "column" : "row",
842
- };
843
- if (node.stackPrimaryAlignItems)
844
- out.justifyContent =
845
- STACK_ALIGN[node.stackPrimaryAlignItems] ?? "flex-start";
846
- if (node.stackCounterAlignItems)
847
- out.alignItems = STACK_ALIGN[node.stackCounterAlignItems] ?? "flex-start";
848
- if (typeof node.stackSpacing === "number")
849
- out.gap = `${num(node.stackSpacing)}px`;
850
- // Padding: prefer per-side; fall back to horizontal/vertical.
851
- const pl = node.stackPaddingLeft ?? node.stackHorizontalPadding;
852
- const pr = node.stackPaddingRight ?? node.stackHorizontalPadding;
853
- const pt = node.stackPaddingTop ?? node.stackVerticalPadding;
854
- const pb = node.stackPaddingBottom ?? node.stackVerticalPadding;
855
- if ([pl, pr, pt, pb].some((v) => typeof v === "number" && v !== 0)) {
856
- out.padding = `${num(pt ?? 0)}px ${num(pr ?? 0)}px ${num(pb ?? 0)}px ${num(pl ?? 0)}px`;
857
- }
858
- return out;
859
- }
860
-
861
- function textStyles(node: FigNode, ctx?: Ctx): Record<string, string | number> {
862
- if (node.type !== "TEXT") return {};
863
- const out: Record<string, string | number> = {};
864
- // A TEXT node may reference a shared text style (`styleIdForText`) whose
865
- // font properties (family, weight, size, line-height, letter-spacing,
866
- // alignment) override the values cached on the node itself. The cached
867
- // values are often stale snapshots of the master and don't reflect the
868
- // current style — prefer the style node when present.
869
- const styleNode = ctx
870
- ? resolveStyleNode(node.styleIdForText, ctx)
871
- : undefined;
872
- const fontName = styleNode?.fontName ?? node.fontName;
873
- const fontSize =
874
- typeof styleNode?.fontSize === "number"
875
- ? styleNode.fontSize
876
- : node.fontSize;
877
- const lineHeight = styleNode?.lineHeight ?? node.lineHeight;
878
- const letterSpacing = styleNode?.letterSpacing ?? node.letterSpacing;
879
- const textAlignHorizontal =
880
- styleNode?.textAlignHorizontal ?? node.textAlignHorizontal;
881
-
882
- if (fontName?.family) {
883
- // Quote families with spaces so the inline style stays valid.
884
- const fam = fontName.family;
885
- out.fontFamily = /\s/.test(fam) ? `"${fam}"` : fam;
886
- }
887
- const weight = fontWeightFromStyle(fontName?.style);
888
- if (weight !== null) out.fontWeight = weight;
889
- // Track this family/weight/italic combo so the frame template can request
890
- // it from Google Fonts in <head>.
891
- if (ctx && fontName?.family) {
892
- const italic = !!(fontName.style && /italic|oblique/i.test(fontName.style));
893
- ctx.fontUsage.add(`${fontName.family}|${weight ?? 400}|${italic ? 1 : 0}`);
894
- }
895
- if (fontName?.style && /italic|oblique/i.test(fontName.style)) {
896
- out.fontStyle = "italic";
897
- }
898
- if (typeof fontSize === "number") out.fontSize = `${num(fontSize)}px`;
899
- const lh = lengthFromUnits(lineHeight, fontSize);
900
- if (lh !== null && lh !== undefined) out.lineHeight = lh;
901
- const ls = lengthFromUnits(letterSpacing, fontSize);
902
- if (ls !== null && ls !== undefined) out.letterSpacing = ls;
903
- if (textAlignHorizontal)
904
- out.textAlign = TEXT_ALIGN[textAlignHorizontal] ?? "left";
905
- // Text color comes from the first SOLID fill paint, dereferenced through
906
- // any `styleIdForFill` shared style (NOT `styleIdForText`, which is
907
- // typography-only — see `effectiveFillPaints`).
908
- if (ctx) {
909
- const solidFill = effectiveFillPaints(node, ctx)?.find(
910
- (f) => f.visible !== false && f.type === "SOLID",
911
- );
912
- if (solidFill) {
913
- const c = colorToCss(solidFill.color, solidFill.opacity ?? 1);
914
- if (c) out.color = c;
915
- }
916
- }
917
- return out;
918
- }
919
-
920
- function blendModeCss(mode: string | undefined): string | null {
921
- if (!mode || mode === "NORMAL" || mode === "PASS_THROUGH") return null;
922
- return mode.toLowerCase().replace(/_/g, "-");
923
- }
924
-
925
- function isAutolayout(parent: FigNode | null): boolean {
926
- return !!(parent && parent.stackMode && parent.stackMode !== "NONE");
927
- }
928
-
929
- /**
930
- * Compose an INSTANCE node with its inlined master's autolayout / padding /
931
- * sizing properties. The master is the source of truth for how children are
932
- * arranged; the instance's cached `stack*` fields can be a stale snapshot of
933
- * a previous variant. Per-axis sizing (`size`) stays on the instance — only
934
- * the layout description is taken from the master.
935
- */
936
- function withMasterLayout(instance: FigNode, master: FigNode): FigNode {
937
- const layoutFields: (keyof FigNode)[] = [
938
- "stackMode",
939
- "stackPrimaryAlignItems",
940
- "stackCounterAlignItems",
941
- "stackSpacing",
942
- "stackPaddingLeft",
943
- "stackPaddingRight",
944
- "stackPaddingTop",
945
- "stackPaddingBottom",
946
- "stackHorizontalPadding",
947
- "stackVerticalPadding",
948
- "stackPrimarySizing",
949
- "stackCounterSizing",
950
- ];
951
- const merged: FigNode = { ...instance };
952
- // If the master defines its own stack direction, the instance's cached
953
- // stack-related fields are stale (they were captured against whatever
954
- // variant the instance originally pointed at). Take ALL layout fields
955
- // from the master wholesale — including `undefined` values — so we don't
956
- // leak e.g. `stackPrimarySizing="FIXED"` from a HORIZONTAL variant onto a
957
- // VERTICAL one whose master leaves it undefined (HUG).
958
- const masterDrivesLayout =
959
- typeof master.stackMode === "string" && master.stackMode !== "NONE";
960
- for (const f of layoutFields) {
961
- const mv = (master as Record<string, unknown>)[f as string];
962
- if (masterDrivesLayout) {
963
- (merged as Record<string, unknown>)[f as string] = mv;
964
- } else if (mv !== undefined) {
965
- (merged as Record<string, unknown>)[f as string] = mv;
966
- }
967
- }
968
- return merged;
969
- }
970
-
971
- /**
972
- * Derive the Figma plugin API's `layoutSizingHorizontal` / `layoutSizingVertical`
973
- * for a node. The kiwi document doesn't store these directly — they're
974
- * computed from the underlying stack/sizing/grow fields the same way
975
- * `figma.currentPage.selection[i].layoutSizingHorizontal` is.
976
- *
977
- * Returns "FIXED" | "HUG" | "FILL" per axis. The cached `node.size` always
978
- * carries a baked pixel value, so callers must consult the derived sizing
979
- * before deciding whether to emit an explicit `width`/`height`.
980
- */
981
- function layoutSizing(
982
- node: FigNode,
983
- parent: FigNode | null,
984
- ): {
985
- horizontal: "FIXED" | "HUG" | "FILL";
986
- vertical: "FIXED" | "HUG" | "FILL";
987
- } {
988
- let horizontal: "FIXED" | "HUG" | "FILL" = "FIXED";
989
- let vertical: "FIXED" | "HUG" | "FILL" = "FIXED";
990
-
991
- // 1) Self auto-layout (this node has its own stack). Kiwi default for an
992
- // omitted `stackPrimarySizing`/`stackCounterSizing` is HUG, not FIXED.
993
- if (node.stackMode && node.stackMode !== "NONE") {
994
- const primaryHug = (node.stackPrimarySizing ?? "RESIZE_TO_FIT") !== "FIXED";
995
- const counterHug = (node.stackCounterSizing ?? "RESIZE_TO_FIT") !== "FIXED";
996
- if (node.stackMode === "HORIZONTAL") {
997
- horizontal = primaryHug ? "HUG" : "FIXED";
998
- vertical = counterHug ? "HUG" : "FIXED";
999
- } else {
1000
- vertical = primaryHug ? "HUG" : "FIXED";
1001
- horizontal = counterHug ? "HUG" : "FIXED";
1002
- }
1003
- }
1004
-
1005
- // 2) Non-autolayout frames can still hug content via `resizeToFit`.
1006
- if (!node.stackMode || node.stackMode === "NONE") {
1007
- if (node.resizeToFit) {
1008
- horizontal = "HUG";
1009
- vertical = "HUG";
1010
- }
1011
- }
1012
-
1013
- // 3) TEXT auto-resize hugs along the indicated axis/axes.
1014
- if (node.type === "TEXT" && node.textAutoResize) {
1015
- if (node.textAutoResize === "WIDTH_AND_HEIGHT") {
1016
- horizontal = "HUG";
1017
- vertical = "HUG";
1018
- } else if (node.textAutoResize === "HEIGHT") {
1019
- vertical = "HUG";
1020
- }
1021
- }
1022
-
1023
- // 4) Auto-layout child of an auto-layout parent: grow/stretch -> FILL.
1024
- if (parent && parent.stackMode && parent.stackMode !== "NONE") {
1025
- const grow = (node.stackChildPrimaryGrow ?? 0) > 0;
1026
- const stretch = node.stackChildAlignSelf === "STRETCH";
1027
- if (parent.stackMode === "HORIZONTAL") {
1028
- if (grow) horizontal = "FILL";
1029
- if (stretch) vertical = "FILL";
1030
- } else {
1031
- if (grow) vertical = "FILL";
1032
- if (stretch) horizontal = "FILL";
1033
- }
1034
- }
1035
-
1036
- return { horizontal, vertical };
1037
- }
1038
-
1039
- function buildCss(
1040
- node: FigNode,
1041
- parent: FigNode | null,
1042
- ctx: Ctx,
1043
- isPositioned: boolean,
1044
- vectorLike = false,
1045
- ): Record<string, unknown> {
1046
- const css: Record<string, unknown> = {};
1047
- const parentFlex = isAutolayout(parent);
1048
-
1049
- // Position / size — mirrors smart-export:
1050
- // parent is auto-layout -> position: relative, no left/top, dimensions
1051
- // may be replaced by flex hints below.
1052
- // parent is not -> position: absolute with left/top/width/height.
1053
- if (isPositioned) {
1054
- css.position = "absolute";
1055
- if (node.transform) {
1056
- const x = num(node.transform.m02);
1057
- const y = num(node.transform.m12);
1058
- if (x !== null) css.left = `${x}px`;
1059
- if (y !== null) css.top = `${y}px`;
1060
- }
1061
- } else if (parentFlex) {
1062
- css.position = "relative";
1063
- }
1064
-
1065
- // Decide whether to emit width/height. The Figma plugin API exposes a
1066
- // unified `layoutSizingHorizontal`/`layoutSizingVertical` derived from the
1067
- // raw stack/grow/textAutoResize fields (kiwi doesn't store those derived
1068
- // values). Only emit a pixel dimension on a FIXED axis — HUG and FILL both
1069
- // mean "let CSS size it" via flex / intrinsic content.
1070
- const sizing = layoutSizing(node, parent);
1071
- const emitWidth = sizing.horizontal === "FIXED";
1072
- const emitHeight = sizing.vertical === "FIXED";
1073
-
1074
- if (node.size) {
1075
- const w = num(node.size.x);
1076
- const h = num(node.size.y);
1077
- if (w !== null && emitWidth) css.width = `${w}px`;
1078
- if (h !== null && emitHeight) css.height = `${h}px`;
1079
- }
1080
-
1081
- // Auto-layout child hints (flex-grow / align-self).
1082
- if (parentFlex) {
1083
- if ((node.stackChildPrimaryGrow ?? 0) > 0) {
1084
- css.flex = "1 0 0";
1085
- }
1086
- if (node.stackChildAlignSelf) {
1087
- const a = STACK_ALIGN[node.stackChildAlignSelf];
1088
- if (a)
1089
- css.alignSelf = node.stackChildAlignSelf === "STRETCH" ? "stretch" : a;
1090
- else if (node.stackChildAlignSelf === "STRETCH")
1091
- css.alignSelf = "stretch";
1092
- }
1093
- }
1094
-
1095
- // Background (TEXT uses fillPaints for color, not background; vector
1096
- // nodes paint via <path fill> inside the <svg>).
1097
- if (node.type !== "TEXT" && !vectorLike) {
1098
- Object.assign(css, backgroundShorthand(node, ctx));
1099
- }
1100
-
1101
- // Border / outline (skipped for vector nodes — strokes go on <path>).
1102
- if (!vectorLike) Object.assign(css, borderShorthand(node, ctx));
1103
- // Radius
1104
- Object.assign(css, radiusStyles(node));
1105
- // Effects (shadows, blurs)
1106
- Object.assign(css, effectStyles(node));
1107
- // Rotation
1108
- Object.assign(css, transformStyle(node));
1109
- // Text styling
1110
- Object.assign(css, textStyles(node, ctx));
1111
- // Autolayout (flex)
1112
- Object.assign(css, autolayoutStyles(node));
1113
-
1114
- // Opacity / blend mode / overflow / visibility
1115
- if (typeof node.opacity === "number" && node.opacity < 0.999)
1116
- css.opacity = node.opacity;
1117
- const bm = blendModeCss(node.blendMode);
1118
- if (bm) css.mixBlendMode = bm;
1119
- if (
1120
- (node.type === "FRAME" || node.type === "INSTANCE") &&
1121
- node.frameMaskDisabled === false
1122
- ) {
1123
- css.overflow = "hidden";
1124
- }
1125
- // (Hidden nodes are dropped entirely in emitNode; no display:none needed.)
1126
-
1127
- return css;
1128
- }
1129
-
1130
- /** Render a css object as a single inline `style` declaration string. */
1131
- function formatStyleString(css: Record<string, unknown>): string {
1132
- return Object.entries(css)
1133
- .map(([k, v]) => `${kebabCase(k)}: ${String(v)}`)
1134
- .join("; ");
1135
- }
1136
-
1137
- interface Ctx {
1138
- byGuid: Map<string, FigNode>;
1139
- // Library style nodes (and other keyed nodes) indexed by their stable
1140
- // `key` so we can resolve `styleIdForFill.assetRef.key` lookups.
1141
- byKey: Map<string, FigNode>;
1142
- childrenOf: Map<string, FigNode[]>;
1143
- symbolByGuid: Map<string, FigNode>;
1144
- imageRefBase?: string;
1145
- /** Raw blob bytes (for path command decoding). Indexed by blob index. */
1146
- blobs: Buffer[];
1147
- /** Hex hash -> on-disk filename (e.g. `<hash>` or `<hash>.png`). */
1148
- imageMap: Map<string, string>;
1149
- /**
1150
- * Set of `family|weight|italic` triples seen while emitting the current
1151
- * frame. We use it to build a Google Fonts <link> in <head> so the custom
1152
- * font families used in the design are actually loaded by the browser.
1153
- */
1154
- fontUsage: Set<string>;
1155
- /** SYMBOLs currently being inlined (cycle guard). */
1156
- inliningStack: Set<string>;
1157
- }
1158
-
1159
- /**
1160
- * Figma's path-command blob format. A stream of:
1161
- * [op:byte] [args:float32 * N]
1162
- * Opcodes (discovered empirically and confirmed against rounded rect /
1163
- * vector / ellipse blobs):
1164
- * 0 = ClosePath (no args)
1165
- * 1 = MoveTo (x, y)
1166
- * 2 = LineTo (x, y)
1167
- * 3 = QuadTo (x1, y1, x, y)
1168
- * 4 = CubicTo (x1, y1, x2, y2, x, y)
1169
- */
1170
- function decodePathCommands(bytes: Buffer | undefined): string {
1171
- if (!bytes || bytes.length === 0) return "";
1172
- const out: string[] = [];
1173
- const fmt = (n: number) => {
1174
- if (!Number.isFinite(n)) return "0";
1175
- const r = Math.round(n * 1000) / 1000;
1176
- return Object.is(r, -0) ? "0" : String(r);
1177
- };
1178
- let i = 0;
1179
- while (i < bytes.length) {
1180
- const op = bytes[i]!;
1181
- let n = 0;
1182
- let letter = "";
1183
- if (op === 0) {
1184
- letter = "Z";
1185
- n = 0;
1186
- } else if (op === 1) {
1187
- letter = "M";
1188
- n = 2;
1189
- } else if (op === 2) {
1190
- letter = "L";
1191
- n = 2;
1192
- } else if (op === 3) {
1193
- letter = "Q";
1194
- n = 4;
1195
- } else if (op === 4) {
1196
- letter = "C";
1197
- n = 6;
1198
- } else {
1199
- // Unknown opcode — stop decoding gracefully so we don't run off
1200
- // the end of the buffer.
1201
- break;
1202
- }
1203
- if (i + 1 + n * 4 > bytes.length) break;
1204
- const args: string[] = [];
1205
- for (let j = 0; j < n; j++)
1206
- args.push(fmt(bytes.readFloatLE(i + 1 + j * 4)));
1207
- out.push(args.length ? `${letter}${args.join(" ")}` : letter);
1208
- i += 1 + n * 4;
1209
- }
1210
- return out.join(" ");
1211
- }
1212
-
1213
- /** SVG paint attribute (fill / stroke) for the first visible solid paint. */
1214
- function paintToSvgFill(
1215
- paints: Paint[] | undefined,
1216
- ): { color: string; opacity?: number } | null {
1217
- const p = paints?.find((x) => x.visible !== false && x.type === "SOLID");
1218
- if (!p || !p.color) return null;
1219
- const c = p.color;
1220
- const r = Math.round(c.r * 255);
1221
- const g = Math.round(c.g * 255);
1222
- const b = Math.round(c.b * 255);
1223
- const opacity = c.a * (p.opacity ?? 1);
1224
- return {
1225
- color: `rgb(${r}, ${g}, ${b})`,
1226
- opacity: opacity < 0.999 ? Number(opacity.toFixed(3)) : undefined,
1227
- };
1228
- }
1229
-
1230
- const VECTOR_LIKE_TYPES = new Set([
1231
- "VECTOR",
1232
- "BOOLEAN_OPERATION",
1233
- "ELLIPSE",
1234
- "BRUSH",
1235
- "STAR",
1236
- "REGULAR_POLYGON",
1237
- "LINE",
1238
- "VECTOR_PATH",
1239
- ]);
1240
-
1241
- function isVectorLike(node: FigNode): boolean {
1242
- if (!node.type || !VECTOR_LIKE_TYPES.has(node.type)) return false;
1243
- if (
1244
- (node.fillGeometry?.length ?? 0) === 0 &&
1245
- (node.strokeGeometry?.length ?? 0) === 0
1246
- ) {
1247
- return false;
1248
- }
1249
- // Nodes with an IMAGE fill render better as a regular <div> with
1250
- // `background-image` (and `background-color` as a fallback) than as an
1251
- // <svg> with a <pattern>. Skip the vector path so backgroundShorthand
1252
- // can stack image + color fills via CSS.
1253
- if (node.fillPaints?.some((p) => p.visible !== false && p.type === "IMAGE")) {
1254
- return false;
1255
- }
1256
- return true;
1257
- }
1258
-
1259
- /**
1260
- * Render a vector-like node as an inline `<svg>`. The element itself keeps
1261
- * the same outer attrs (layer-name, position/size style) as a regular div
1262
- * so it slots into auto-layout / absolute positioning identically; the
1263
- * vector geometry lives inside as `<path>` children.
1264
- */
1265
- function emitSvgBody(
1266
- node: FigNode,
1267
- ctx: Ctx,
1268
- indent: string,
1269
- lines: string[],
1270
- ): void {
1271
- const fillRule =
1272
- node.fillGeometry?.[0]?.windingRule === "ODD" ? "evenodd" : "nonzero";
1273
- const fillPaint = paintToSvgFill(effectiveFillPaints(node, ctx));
1274
- const strokePaint = paintToSvgFill(effectiveStrokePaints(node, ctx));
1275
- const strokeWeight = node.strokeWeight ?? 0;
1276
-
1277
- // Fill paths
1278
- for (const g of node.fillGeometry ?? []) {
1279
- if (typeof g.commandsBlob !== "number") continue;
1280
- const d = decodePathCommands(ctx.blobs[g.commandsBlob]);
1281
- if (!d) continue;
1282
- const attrs = [`d="${d}"`, `fill-rule="${fillRule}"`];
1283
- if (fillPaint) {
1284
- attrs.push(`fill="${fillPaint.color}"`);
1285
- if (fillPaint.opacity !== undefined)
1286
- attrs.push(`fill-opacity="${fillPaint.opacity}"`);
1287
- } else {
1288
- attrs.push(`fill="none"`);
1289
- }
1290
- lines.push(`${indent} <path ${attrs.join(" ")} />`);
1291
- }
1292
- // Stroke paths
1293
- if (strokePaint && strokeWeight > 0) {
1294
- for (const g of node.strokeGeometry ?? node.fillGeometry ?? []) {
1295
- if (typeof g.commandsBlob !== "number") continue;
1296
- const d = decodePathCommands(ctx.blobs[g.commandsBlob]);
1297
- if (!d) continue;
1298
- const attrs = [
1299
- `d="${d}"`,
1300
- `fill="none"`,
1301
- `stroke="${strokePaint.color}"`,
1302
- `stroke-width="${num(strokeWeight)}"`,
1303
- ];
1304
- if (strokePaint.opacity !== undefined)
1305
- attrs.push(`stroke-opacity="${strokePaint.opacity}"`);
1306
- if (node.strokeJoin)
1307
- attrs.push(`stroke-linejoin="${node.strokeJoin.toLowerCase()}"`);
1308
- if (node.strokeCap)
1309
- attrs.push(`stroke-linecap="${node.strokeCap.toLowerCase()}"`);
1310
- lines.push(`${indent} <path ${attrs.join(" ")} />`);
1311
- }
1312
- }
1313
- }
1314
-
1315
- function getChildren(node: FigNode, ctx: Ctx): FigNode[] {
1316
- const kids = ctx.childrenOf.get(guidKey(node.guid)) ?? [];
1317
- return kids.slice().sort((a, b) => {
1318
- const pa = a.parentIndex?.position ?? "";
1319
- const pb = b.parentIndex?.position ?? "";
1320
- return pa < pb ? -1 : pa > pb ? 1 : 0;
1321
- });
1322
- }
1323
-
1324
- function buildAttrs(
1325
- node: FigNode,
1326
- parent: FigNode | null,
1327
- ctx: Ctx,
1328
- isPositioned: boolean,
1329
- componentSymbol: FigNode | null,
1330
- vectorLike = false,
1331
- ): string[] {
1332
- const attrs: string[] = [];
1333
-
1334
- // layer-name: emit whenever the node has a name at all (matches the
1335
- // figma-plugin's smart-export, which always carries the layer name when
1336
- // present).
1337
- if (node.name) attrs.push(`layer-name="${escapeHtmlAttr(node.name)}"`);
1338
-
1339
- // Component metadata: pulled from the SYMBOL master that an INSTANCE renders,
1340
- // or from the SYMBOL itself when emitting a master directly.
1341
- const symbolForMeta =
1342
- componentSymbol ??
1343
- (node.type === "SYMBOL" || node.type === "INSTANCE" ? node : null);
1344
- if (symbolForMeta && symbolForMeta.type === "SYMBOL") {
1345
- const { base, variant } = resolveComponentIdentity(symbolForMeta, ctx);
1346
- if (base) attrs.push(`data-component-name="${escapeHtmlAttr(base)}"`);
1347
- if (variant) attrs.push(`data-variant-name="${escapeHtmlAttr(variant)}"`);
1348
- // Expose individual variant key/value pairs as parsed JSON so consumers
1349
- // can read e.g. `Style=Action` directly without re-parsing the variant
1350
- // string. Mirrors how the figma-plugin surfaces variant props.
1351
- if (variant && /=/.test(variant)) {
1352
- const variantProps: Record<string, string> = {};
1353
- for (const pair of variant.split(/,\s*/)) {
1354
- const [key, val] = pair.split("=");
1355
- if (key && val !== undefined) variantProps[key.trim()] = val.trim();
1356
- }
1357
- if (Object.keys(variantProps).length > 0) {
1358
- const json = JSON.stringify(variantProps).replace(/'/g, "&#39;");
1359
- attrs.push(`data-variant-props='${json}'`);
1360
- }
1361
- }
1362
- if (symbolForMeta.componentKey)
1363
- attrs.push(
1364
- `data-component-key="${escapeHtmlAttr(symbolForMeta.componentKey)}"`,
1365
- );
1366
- const desc = htmlToPlain(symbolForMeta.description);
1367
- if (desc)
1368
- attrs.push(`data-component-description="${escapeHtmlAttr(desc)}"`);
1369
- const links = extractDocLinks(symbolForMeta.description);
1370
- if (links.length > 0)
1371
- attrs.push(`data-component-doc-link="${escapeHtmlAttr(links[0]!)}"`);
1372
- if (links.length > 1)
1373
- attrs.push(
1374
- `data-component-doc-links="${escapeHtmlAttr(links.join(" | "))}"`,
1375
- );
1376
- const propDefNames = (symbolForMeta.componentPropDefs ?? [])
1377
- .map((p) => p.name)
1378
- .filter(Boolean) as string[];
1379
- if (propDefNames.length > 0)
1380
- attrs.push(
1381
- `data-component-props="${escapeHtmlAttr(propDefNames.join(", "))}"`,
1382
- );
1383
- }
1384
-
1385
- // `props`: a stringified JSON object of the raw Figma component props on
1386
- // this node. Includes the prop definitions on a SYMBOL/INSTANCE and the
1387
- // assignments/refs that override them.
1388
- const rawProps = collectRawProps(node, componentSymbol);
1389
- if (rawProps) {
1390
- // Use single-quoted attribute value so the inner JSON's double quotes
1391
- // stay readable (no `&quot;` noise). Escape stray single quotes inside
1392
- // the JSON for safety.
1393
- const json = JSON.stringify(rawProps).replace(/'/g, "&#39;");
1394
- attrs.push(`props='${json}'`);
1395
- }
1396
-
1397
- // Per-node annotations (Figma's annotation feature).
1398
- if (Array.isArray(node.annotations) && node.annotations.length > 0) {
1399
- const labels = node.annotations
1400
- .map((a) => htmlToPlain(a.labelV2 || a.label))
1401
- .filter(Boolean);
1402
- if (labels.length > 0)
1403
- attrs.push(`data-annotations="${escapeHtmlAttr(labels.join(" | "))}"`);
1404
- }
1405
-
1406
- const css = buildCss(node, parent, ctx, isPositioned, vectorLike);
1407
- if (Object.keys(css).length > 0) {
1408
- attrs.push(`style="${escapeHtmlAttr(formatStyleString(css))}"`);
1409
- }
1410
- return attrs;
1411
- }
1412
-
1413
- function emitNode(
1414
- node: FigNode,
1415
- parent: FigNode | null,
1416
- ctx: Ctx,
1417
- depth: number,
1418
- parentIsFlex: boolean,
1419
- lines: string[],
1420
- propEnv: Map<string, ResolvedPropValue> = new Map(),
1421
- /**
1422
- * Stack of active symbol-override scopes contributed by enclosing
1423
- * INSTANCEs. Each layer's keys are descendant guidPaths RELATIVE to where
1424
- * that instance was entered (matching what Figma stores in
1425
- * `symbolOverrides[].guidPath` and `derivedSymbolData[].guidPath`).
1426
- * Lookup uses `instancePath.slice(layer.startIndex)` plus the current
1427
- * node's overrideKey as the leaf segment.
1428
- *
1429
- * Outer layers stay active across nested inner instances so that deep
1430
- * overrides like `[outerInstanceKey, innerNodeKey]` still match.
1431
- */
1432
- overrideLayers: OverrideLayer[] = [],
1433
- /**
1434
- * Stack of INSTANCE overrideKeys we've descended INTO (i.e., crossed the
1435
- * instance->master boundary). Plain frame/group nesting does NOT grow this
1436
- * path. Used together with `overrideLayers` to look up `symbolOverrides` /
1437
- * `derivedSymbolData` entries that target a descendant by library guidPath.
1438
- */
1439
- instancePath: string[] = [],
1440
- ): void {
1441
- // Smart-export skips invisible nodes entirely (rather than emitting them
1442
- // with display:none). Match that so hidden layers don't pollute the
1443
- // generated HTML.
1444
- if (node.visible === false) return;
1445
-
1446
- // Apply enclosing-instance symbol overrides (variant swap, text override,
1447
- // visibility flip) targeted at this node by guidPath.
1448
- const overridden = applyOverrideLayers(node, overrideLayers, instancePath);
1449
- if (overridden === null) return;
1450
- node = overridden;
1451
-
1452
- // Apply parent-instance prop overrides for this node (text/symbol/swap,
1453
- // visibility). May hide the node entirely or rewrite its textData /
1454
- // symbolData before we resolve the inlined symbol below.
1455
- const patched = applyPropRefs(node, propEnv);
1456
- if (patched === null) return;
1457
- node = patched;
1458
-
1459
- const indent = " ".repeat(depth);
1460
-
1461
- // INSTANCE: inline the master SYMBOL's children inside this element so the
1462
- // implementation is self-contained. Cycle guard: don't recursively inline a
1463
- // SYMBOL that's already being inlined further up the chain.
1464
- let inlinedSymbol: FigNode | null = null;
1465
- if (node.type === "INSTANCE" && node.symbolData?.symbolID) {
1466
- const symKey = guidKey(node.symbolData.symbolID);
1467
- if (!ctx.inliningStack.has(symKey)) {
1468
- const sym = ctx.symbolByGuid.get(symKey);
1469
- if (sym) inlinedSymbol = sym;
1470
- }
1471
- }
1472
-
1473
- // When entering an INSTANCE, extend the prop env with its assignments so
1474
- // descendants (whether the instance's own children or the inlined SYMBOL's
1475
- // children) see the override values. Likewise build a fresh
1476
- // symbolOverrides map (overrides scope to a single instance), and reset
1477
- // the current path so descendant guidPaths are evaluated against the new
1478
- // master.
1479
- const childPropEnv =
1480
- node.type === "INSTANCE" ? buildPropEnv(node, propEnv) : propEnv;
1481
- // When entering an INSTANCE that will inline a master, descendants live
1482
- // one level deeper in the instance-path. Push the new override layer with
1483
- // startIndex pointing at that future depth so its keys (relative paths
1484
- // inside this instance's master) are evaluated against an empty prefix at
1485
- // the master's first level. Outer layers stay active so deeper overrides
1486
- // from enclosing instances still apply across nested boundaries.
1487
- const childInstancePath =
1488
- node.type === "INSTANCE" && inlinedSymbol
1489
- ? [...instancePath, guidKey(node.overrideKey ?? node.guid)]
1490
- : instancePath;
1491
- let childOverrideLayers = overrideLayers;
1492
- if (node.type === "INSTANCE") {
1493
- const map = buildSymbolOverrideLayer(node);
1494
- if (map.size > 0) {
1495
- childOverrideLayers = [
1496
- ...overrideLayers,
1497
- { startIndex: childInstancePath.length, map },
1498
- ];
1499
- }
1500
- }
1501
-
1502
- // A node is rendered as an SVG when it has its own vector geometry, OR
1503
- // when it's an INSTANCE of a SYMBOL whose root is itself a vector (e.g.
1504
- // single-shape icon components). For the latter we paint the master's
1505
- // geometry inside the instance element so the icon actually shows up
1506
- // instead of an empty div.
1507
- const selfVector = isVectorLike(node);
1508
- const symbolVector = !!inlinedSymbol && isVectorLike(inlinedSymbol);
1509
- const vectorLike = selfVector || symbolVector;
1510
- const vectorSourceNode = selfVector
1511
- ? node
1512
- : symbolVector
1513
- ? inlinedSymbol!
1514
- : node;
1515
- const tag = vectorLike ? "svg" : tagFor(node.type);
1516
- // Children of a flex (autolayout) parent flow normally; otherwise absolute.
1517
- const isPositioned = !parentIsFlex;
1518
-
1519
- // For INSTANCE nodes with an inlined master, the autolayout / padding /
1520
- // sizing properties cached on the instance reflect the *previous* master
1521
- // and become stale after a variant swap. Use the master's values for the
1522
- // instance's own container styling so the rendered layout matches the
1523
- // currently-resolved variant.
1524
- const layoutNode = inlinedSymbol
1525
- ? withMasterLayout(node, inlinedSymbol)
1526
- : node;
1527
- const attrs = buildAttrs(
1528
- layoutNode,
1529
- parent,
1530
- ctx,
1531
- isPositioned,
1532
- inlinedSymbol,
1533
- vectorLike,
1534
- );
1535
- if (vectorLike) {
1536
- // viewBox prefers the geometry source node's intrinsic size so the
1537
- // SVG draws correctly when the instance is scaled differently from
1538
- // the master.
1539
- const vw = vectorSourceNode.size?.x ?? node.size?.x ?? 0;
1540
- const vh = vectorSourceNode.size?.y ?? node.size?.y ?? 0;
1541
- if (vw > 0 && vh > 0) {
1542
- attrs.push(`viewBox="0 0 ${num(vw)} ${num(vh)}"`);
1543
- }
1544
- attrs.push(`xmlns="http://www.w3.org/2000/svg"`);
1545
- attrs.push(`fill="none"`);
1546
- }
1547
-
1548
- const isFlex = layoutNode.stackMode && layoutNode.stackMode !== "NONE";
1549
-
1550
- // Single HTML comment above the element with component name + description
1551
- // + doc links, when present. (Same metadata is also on data-* attrs.)
1552
- const symbolForMeta = inlinedSymbol ?? (node.type === "SYMBOL" ? node : null);
1553
- if (symbolForMeta) {
1554
- const desc = htmlToPlain(symbolForMeta.description);
1555
- const links = extractDocLinks(symbolForMeta.description);
1556
- if (desc || links.length > 0) {
1557
- const parts = [
1558
- `Component: ${(symbolForMeta.name ?? "<unnamed>").replace(/--/g, "\u2013")}`,
1559
- ];
1560
- // HTML comments must not contain "--" — replace any with an en-dash.
1561
- if (desc) parts.push(desc.replace(/--/g, "\u2013"));
1562
- if (links.length > 0) parts.push(`docs: ${links.join(", ")}`);
1563
- lines.push(`${indent}<!-- ${parts.join(" \u2014 ")} -->`);
1564
- }
1565
- }
1566
-
1567
- if (vectorLike) {
1568
- emitOpenWithChildren(tag, attrs, indent, lines);
1569
- emitSvgBody(vectorSourceNode, ctx, indent, lines);
1570
- lines.push(`${indent}</${tag}>`);
1571
- return;
1572
- }
1573
-
1574
- if (node.type === "TEXT") {
1575
- const chars = node.textData?.characters ?? "";
1576
- if (chars.length === 0) {
1577
- emitOpenWithChildren(tag, attrs, indent, lines);
1578
- lines.push(`${indent}</${tag}>`);
1579
- return;
1580
- }
1581
- emitOpenWithChildren(tag, attrs, indent, lines);
1582
- // Preserve newlines in the source by splitting into <br>-separated lines
1583
- // (HTML otherwise collapses whitespace).
1584
- const escaped = escapeHtmlText(chars).replace(/\n/g, "<br>");
1585
- lines.push(`${indent} ${escaped}`);
1586
- lines.push(`${indent}</${tag}>`);
1587
- return;
1588
- }
1589
-
1590
- // Pick which children to render: the inlined SYMBOL's, or the node's own.
1591
- let children: FigNode[];
1592
- let symKeyForCycle: string | null = null;
1593
- if (inlinedSymbol) {
1594
- symKeyForCycle = guidKey(inlinedSymbol.guid);
1595
- ctx.inliningStack.add(symKeyForCycle);
1596
- children = getChildren(inlinedSymbol, ctx);
1597
- } else {
1598
- children = getChildren(node, ctx);
1599
- }
1600
-
1601
- try {
1602
- if (children.length === 0) {
1603
- emitOpenWithChildren(tag, attrs, indent, lines);
1604
- lines.push(`${indent}</${tag}>`);
1605
- return;
1606
- }
1607
- emitOpenWithChildren(tag, attrs, indent, lines);
1608
- // When inlining a SYMBOL, its child positions are relative to the SYMBOL's
1609
- // own frame, which now coincides with this INSTANCE's frame. So they keep
1610
- // their original transforms.
1611
- const childParentIsFlex = inlinedSymbol
1612
- ? !!(inlinedSymbol.stackMode && inlinedSymbol.stackMode !== "NONE")
1613
- : !!isFlex;
1614
- const childParentNode = inlinedSymbol ?? node;
1615
- for (const child of children) {
1616
- emitNode(
1617
- child,
1618
- childParentNode,
1619
- ctx,
1620
- depth + 1,
1621
- childParentIsFlex,
1622
- lines,
1623
- childPropEnv,
1624
- childOverrideLayers,
1625
- childInstancePath,
1626
- );
1627
- }
1628
- lines.push(`${indent}</${tag}>`);
1629
- } finally {
1630
- if (symKeyForCycle) ctx.inliningStack.delete(symKeyForCycle);
1631
- }
1632
- }
1633
-
1634
- function emitOpenWithChildren(
1635
- tag: string,
1636
- attrs: string[],
1637
- indent: string,
1638
- lines: string[],
1639
- ): void {
1640
- if (attrs.length === 0) {
1641
- lines.push(`${indent}<${tag}>`);
1642
- return;
1643
- }
1644
- // Single-line for short attribute lists; multi-line otherwise.
1645
- const oneLine = `${indent}<${tag} ${attrs.join(" ")}>`;
1646
- if (attrs.length <= 2 && oneLine.length <= 200) {
1647
- lines.push(oneLine);
1648
- return;
1649
- }
1650
- lines.push(`${indent}<${tag}`);
1651
- for (const a of attrs) lines.push(`${indent} ${a}`);
1652
- lines.push(`${indent}>`);
1653
- }
1654
-
1655
- /**
1656
- * Build a Google Fonts CSS2 URL from the set of font family/weight/italic
1657
- * combos collected while emitting a frame. Returns null when no fonts are
1658
- * recorded.
1659
- */
1660
- function buildGoogleFontsUrl(fontUsage: Set<string>): string | null {
1661
- if (fontUsage.size === 0) return null;
1662
- const byFamily = new Map<
1663
- string,
1664
- Array<{ weight: number; italic: boolean }>
1665
- >();
1666
- for (const entry of fontUsage) {
1667
- const [family, weightStr, italicStr] = entry.split("|");
1668
- if (!family) continue;
1669
- const weight = Number(weightStr) || 400;
1670
- const italic = italicStr === "1";
1671
- if (!byFamily.has(family)) byFamily.set(family, []);
1672
- byFamily.get(family)!.push({ weight, italic });
1673
- }
1674
- const families: string[] = [];
1675
- for (const [family, variants] of byFamily) {
1676
- const hasItalic = variants.some((v) => v.italic);
1677
- const weights = Array.from(new Set(variants.map((v) => v.weight))).sort(
1678
- (a, b) => a - b,
1679
- );
1680
- const famParam = family.replace(/\s+/g, "+");
1681
- if (hasItalic) {
1682
- const tuples = variants
1683
- .map((v) => `${v.italic ? 1 : 0},${v.weight}`)
1684
- .sort();
1685
- families.push(
1686
- `family=${famParam}:ital,wght@${Array.from(new Set(tuples)).join(";")}`,
1687
- );
1688
- } else {
1689
- families.push(`family=${famParam}:wght@${weights.join(";")}`);
1690
- }
1691
- }
1692
- return `https://fonts.googleapis.com/css2?${families.join("&")}&display=swap`;
1693
- }
1694
-
1695
- function emitFrameTemplate(frame: FigNode, ctx: Ctx, pageName: string): string {
1696
- // Reset per-frame font usage; emitNode populates it via textStyles.
1697
- ctx.fontUsage.clear();
1698
- const bodyLines: string[] = [];
1699
- emitNode(frame, null, ctx, 1, true, bodyLines, new Map(), [], []);
1700
-
1701
- const lines: string[] = [];
1702
- lines.push("<!doctype html>");
1703
- lines.push(
1704
- `<!-- Auto-generated from Figma. Frame: ${frame.name ?? "<unnamed>"} (page: ${pageName}) -->`,
1705
- );
1706
- lines.push("<html>");
1707
- lines.push("<head>");
1708
- lines.push(' <meta charset="utf-8">');
1709
- lines.push(
1710
- ` <title>${escapeHtmlText(`${pageName} \u2014 ${frame.name ?? "frame"}`)}</title>`,
1711
- );
1712
- // Custom font families used by the frame -> request them from Google
1713
- // Fonts. (Smart-export does the same for design hand-off so the layout
1714
- // renders with the intended typography.)
1715
- const fontsUrl = buildGoogleFontsUrl(ctx.fontUsage);
1716
- if (fontsUrl) {
1717
- lines.push(' <link rel="preconnect" href="https://fonts.googleapis.com">');
1718
- lines.push(
1719
- ' <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>',
1720
- );
1721
- lines.push(` <link rel="stylesheet" href="${escapeHtmlAttr(fontsUrl)}">`);
1722
- }
1723
- lines.push("</head>");
1724
- lines.push("<body>");
1725
- for (const l of bodyLines) lines.push(l);
1726
- lines.push("</body>");
1727
- lines.push("</html>");
1728
- lines.push("");
1729
- return lines.join("\n");
1730
- }
1731
-
1732
- export interface RenderedFrame {
1733
- pageName: string;
1734
- pageDirName: string;
1735
- frameName: string;
1736
- /** Sanitized + de-duplicated filename including the `.html` extension. */
1737
- fileName: string;
1738
- /** Path relative to the render root, e.g. `page-1/login.html`. */
1739
- relativePath: string;
1740
- html: string;
1741
- }
1742
-
1743
- export interface RenderHtmlResult {
1744
- pageCount: number;
1745
- frameCount: number;
1746
- frames: RenderedFrame[];
1747
- }
1748
-
1749
- export interface RenderHtmlOptions {
1750
- /** Optional prefix for image url() references (default: "../images") */
1751
- imageRefBase?: string;
1752
- /** Pre-built `hash -> filename` map for image references. */
1753
- imageMap?: Map<string, string>;
1754
- /*** Optional set of page (CANVAS) and/or frame GUID keys */
1755
- selection?: Set<string>;
1756
- }
1757
-
1758
- const TOP_LEVEL_RENDERABLE_TYPES = new Set(["FRAME", "SYMBOL", "INSTANCE"]);
1759
-
1760
- /**
1761
- * Collect the renderable top-level units on a page. Figma allows SECTION
1762
- * nodes (and nested sections) to wrap frames; sections are organizational
1763
- * containers, not standalone designs, so we recurse THROUGH them and
1764
- * collect the frames inside. Anything that isn't a SECTION or a
1765
- * renderable type is ignored. Children are returned in document order
1766
- * (depth-first across sections).
1767
- */
1768
- export function collectTopLevelFrames(
1769
- parent: FigNode,
1770
- childrenOf: Map<string, FigNode[]>,
1771
- ): FigNode[] {
1772
- const sortChildren = (kids: FigNode[]): FigNode[] =>
1773
- kids.slice().sort((a, b) => {
1774
- const pa = a.parentIndex?.position ?? "";
1775
- const pb = b.parentIndex?.position ?? "";
1776
- return pa < pb ? -1 : pa > pb ? 1 : 0;
1777
- });
1778
- const out: FigNode[] = [];
1779
- const visit = (node: FigNode): void => {
1780
- for (const child of sortChildren(
1781
- childrenOf.get(guidKey(node.guid)) ?? [],
1782
- )) {
1783
- if (!child.type) continue;
1784
- if (child.type === "SECTION") {
1785
- visit(child);
1786
- continue;
1787
- }
1788
- if (TOP_LEVEL_RENDERABLE_TYPES.has(child.type)) {
1789
- out.push(child);
1790
- }
1791
- }
1792
- };
1793
- visit(parent);
1794
- return out;
1795
- }
1796
- export function renderHtmlTemplates(
1797
- document: unknown,
1798
- options: RenderHtmlOptions = {},
1799
- ): RenderHtmlResult {
1800
- const doc = document as {
1801
- nodeChanges?: FigNode[];
1802
- blobs?: Array<{ bytes?: string | Buffer | Uint8Array }>;
1803
- };
1804
- const nodes = doc.nodeChanges ?? [];
1805
-
1806
- // Decode blob bytes once. The kiwi document JSON-serializes blob bytes as
1807
- // hex strings; Buffer / Uint8Array values may also appear depending on how
1808
- // the caller decoded the document.
1809
- const blobs: Buffer[] = (doc.blobs ?? []).map((b) => {
1810
- const v = b?.bytes;
1811
- if (!v) return Buffer.alloc(0);
1812
- if (Buffer.isBuffer(v)) return v;
1813
- if (v instanceof Uint8Array) return Buffer.from(v);
1814
- if (typeof v === "string") return Buffer.from(v, "hex");
1815
- return Buffer.alloc(0);
1816
- });
1817
-
1818
- const byGuid = new Map<string, FigNode>();
1819
- const byKey = new Map<string, FigNode>();
1820
- const childrenOf = new Map<string, FigNode[]>();
1821
- const symbolByGuid = new Map<string, FigNode>();
1822
- for (const n of nodes) {
1823
- byGuid.set(guidKey(n.guid), n);
1824
- if (n.key) byKey.set(n.key, n);
1825
- if (n.type === "SYMBOL") {
1826
- symbolByGuid.set(guidKey(n.guid), n);
1827
- }
1828
- const pk = guidKey(n.parentIndex?.guid);
1829
- if (!pk) continue;
1830
- let arr = childrenOf.get(pk);
1831
- if (!arr) {
1832
- arr = [];
1833
- childrenOf.set(pk, arr);
1834
- }
1835
- arr.push(n);
1836
- }
1837
-
1838
- const ctx: Ctx = {
1839
- byGuid,
1840
- byKey,
1841
- childrenOf,
1842
- symbolByGuid,
1843
- imageRefBase: options.imageRefBase,
1844
- blobs,
1845
- imageMap: options.imageMap ?? new Map<string, string>(),
1846
- fontUsage: new Set(),
1847
- inliningStack: new Set(),
1848
- };
1849
-
1850
- const documentNode = nodes.find((n) => n.type === "DOCUMENT");
1851
- if (!documentNode) return { pageCount: 0, frameCount: 0, frames: [] };
1852
-
1853
- const allPages = (childrenOf.get(guidKey(documentNode.guid)) ?? []).filter(
1854
- (n) => n.type === "CANVAS" && !n.internalOnly,
1855
- );
1856
-
1857
- const selection =
1858
- options.selection && options.selection.size > 0 ? options.selection : null;
1859
-
1860
- const pages = selection
1861
- ? allPages.filter((page) => {
1862
- if (selection.has(guidKey(page.guid))) return true;
1863
- const children = childrenOf.get(guidKey(page.guid)) ?? [];
1864
- return children.some((c) => selection.has(guidKey(c.guid)));
1865
- })
1866
- : allPages;
1867
-
1868
- const frames: RenderedFrame[] = [];
1869
- for (let pageIdx = 0; pageIdx < pages.length; pageIdx++) {
1870
- const page = pages[pageIdx]!;
1871
- const pageDirName = sanitizeFilename(page.name, `page-${pageIdx + 1}`);
1872
- const pageSelected = selection?.has(guidKey(page.guid)) ?? false;
1873
- const pageFrames = collectTopLevelFrames(page, ctx.childrenOf).filter(
1874
- (c) => {
1875
- if (!selection || pageSelected) return true;
1876
- return selection.has(guidKey(c.guid));
1877
- },
1878
- );
1879
-
1880
- const seen = new Map<string, number>();
1881
- for (let frameIdx = 0; frameIdx < pageFrames.length; frameIdx++) {
1882
- const frame = pageFrames[frameIdx]!;
1883
- const baseFile = sanitizeFilename(frame.name, `frame-${frameIdx + 1}`);
1884
- const dupeIdx = seen.get(baseFile) ?? 0;
1885
- seen.set(baseFile, dupeIdx + 1);
1886
- const fileName =
1887
- dupeIdx === 0 ? `${baseFile}.html` : `${baseFile}-${dupeIdx + 1}.html`;
1888
- const pageName = page.name ?? `page-${pageIdx + 1}`;
1889
- const html = emitFrameTemplate(frame, ctx, pageName);
1890
- frames.push({
1891
- pageName,
1892
- pageDirName,
1893
- frameName: frame.name ?? `frame-${frameIdx + 1}`,
1894
- fileName,
1895
- relativePath: path.posix.join(pageDirName, fileName),
1896
- html,
1897
- });
1898
- }
1899
- }
1900
-
1901
- return {
1902
- pageCount: pages.length,
1903
- frameCount: frames.length,
1904
- frames,
1905
- };
1906
- }