@vanillaskyai/video 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/LICENSE +201 -0
  3. package/PUBLIC-API.md +276 -0
  4. package/README.md +152 -0
  5. package/SECURITY.md +22 -0
  6. package/SUPPORT.md +28 -0
  7. package/bin/vanillasky.js +3 -0
  8. package/dist/bg-confetti-WNQXS7ZS.js +89 -0
  9. package/dist/bg-emoji-ETI47GLS.js +150 -0
  10. package/dist/bg-media-SVUZAMGX.js +99 -0
  11. package/dist/brand-message-F3RD4P3P.js +253 -0
  12. package/dist/builtin-server-F7YXRVCH.js +8 -0
  13. package/dist/catalog-types-BIhSpOWK.d.ts +74 -0
  14. package/dist/chart-bar-CNSC7BNK.js +304 -0
  15. package/dist/chart-counter-MCRHKN77.js +299 -0
  16. package/dist/chart-progress-ring-RMI4A7ZK.js +296 -0
  17. package/dist/check-runtime.d.ts +15 -0
  18. package/dist/check-runtime.js +102 -0
  19. package/dist/chunk-2E6T633S.js +27 -0
  20. package/dist/chunk-352ZZCET.js +83 -0
  21. package/dist/chunk-73NTSFFI.js +81 -0
  22. package/dist/chunk-A2X45FET.js +46 -0
  23. package/dist/chunk-ABPKM4GK.js +187 -0
  24. package/dist/chunk-ABZACD4G.js +216 -0
  25. package/dist/chunk-BCRUUJ6A.js +756 -0
  26. package/dist/chunk-CHLGW22F.js +3551 -0
  27. package/dist/chunk-CJ7F2CE6.js +104 -0
  28. package/dist/chunk-CR7FE7BW.js +109 -0
  29. package/dist/chunk-E7CL7UPB.js +109 -0
  30. package/dist/chunk-EE6PK6XC.js +18 -0
  31. package/dist/chunk-ERY4S6QV.js +385 -0
  32. package/dist/chunk-EVG2ZYIY.js +125 -0
  33. package/dist/chunk-FNAEQ7QO.js +155 -0
  34. package/dist/chunk-FQ47WXAJ.js +38 -0
  35. package/dist/chunk-FSG2PYWG.js +336 -0
  36. package/dist/chunk-GHJEAP4O.js +504 -0
  37. package/dist/chunk-GRMUV7QY.js +262 -0
  38. package/dist/chunk-IFOW65Z6.js +205 -0
  39. package/dist/chunk-IXCUY3B3.js +786 -0
  40. package/dist/chunk-L5BTTCZV.js +97 -0
  41. package/dist/chunk-LMG3GHLL.js +107 -0
  42. package/dist/chunk-OOPIETLW.js +101 -0
  43. package/dist/chunk-P22HHFDK.js +43 -0
  44. package/dist/chunk-QAAO7OAY.js +19 -0
  45. package/dist/chunk-S7HFLYNN.js +35 -0
  46. package/dist/chunk-SPVTJH3F.js +24 -0
  47. package/dist/chunk-W2XJKG6C.js +3177 -0
  48. package/dist/chunk-XB7LH4J2.js +301 -0
  49. package/dist/chunk-XGRA2MUV.js +242 -0
  50. package/dist/chunk-XTOXFMLM.js +105 -0
  51. package/dist/chunk-YC5MFXA5.js +132 -0
  52. package/dist/cli.d.ts +1 -0
  53. package/dist/cli.js +1681 -0
  54. package/dist/compose-video-CN3VSWST.js +13 -0
  55. package/dist/cta-logo-SVA5GP2A.js +209 -0
  56. package/dist/cta-media-E7VLLK42.js +215 -0
  57. package/dist/events-_wfjbmEp.d.ts +81 -0
  58. package/dist/incoming-call-62MFZL3Z.js +320 -0
  59. package/dist/index.d.ts +15 -0
  60. package/dist/index.js +14 -0
  61. package/dist/infographic-before-after-AXCDAWND.js +460 -0
  62. package/dist/infographic-feature-list-GW5GUE6O.js +266 -0
  63. package/dist/infographic-problem-solution-7NURJANA.js +340 -0
  64. package/dist/infographic-stat-row-J7IZR6ZN.js +241 -0
  65. package/dist/infographic-steps-VSZM6F5M.js +400 -0
  66. package/dist/kit-BMNcHqa9.d.ts +79 -0
  67. package/dist/prompt-input-LOUCRXCY.js +236 -0
  68. package/dist/react.d.ts +81 -0
  69. package/dist/react.js +835 -0
  70. package/dist/reaction-QG4CYZLQ.js +119 -0
  71. package/dist/server.d.ts +141 -0
  72. package/dist/server.js +498 -0
  73. package/dist/showcase-code-RUTFZR3H.js +351 -0
  74. package/dist/showcase-phone-6CP6XEU5.js +272 -0
  75. package/dist/showcase-terminal-MGAEQWPR.js +306 -0
  76. package/dist/showcase-web-Y4W2HVRJ.js +390 -0
  77. package/dist/social-conversation-75SD2637.js +695 -0
  78. package/dist/social-milestone-XI2QE5BO.js +292 -0
  79. package/dist/social-notification-2UOHQCUY.js +244 -0
  80. package/dist/social-review-stack-FDYZGZTJ.js +239 -0
  81. package/dist/social-testimonial-OQ7N52GJ.js +284 -0
  82. package/dist/social-tweet-5OLCNPPC.js +295 -0
  83. package/dist/state-DZcKuS32.d.ts +3 -0
  84. package/dist/system-prompt-A6UXNTPK.js +8 -0
  85. package/dist/template-catalog.d.ts +24 -0
  86. package/dist/template-catalog.js +6 -0
  87. package/dist/templates.d.ts +25 -0
  88. package/dist/templates.js +19 -0
  89. package/dist/test.d.ts +149 -0
  90. package/dist/test.js +272 -0
  91. package/dist/text-stream-6XHC7J47.js +10 -0
  92. package/dist/types-B-PZR6G_.d.ts +208 -0
  93. package/dist/validate-T7GBU2YF.js +8 -0
  94. package/docs/agent-integration.md +39 -0
  95. package/docs/architecture.md +84 -0
  96. package/docs/branding-and-personalization.md +87 -0
  97. package/docs/concepts.md +106 -0
  98. package/docs/custom-templates.md +329 -0
  99. package/docs/customization.md +141 -0
  100. package/docs/errors.md +70 -0
  101. package/docs/getting-started.md +111 -0
  102. package/docs/input-and-first-scene.md +41 -0
  103. package/docs/integrate-nextjs.md +79 -0
  104. package/docs/media-and-audio.md +69 -0
  105. package/docs/motion-and-effects.md +107 -0
  106. package/docs/persistence.md +95 -0
  107. package/docs/production.md +122 -0
  108. package/docs/prompt-and-input.md +185 -0
  109. package/docs/provider-integration.md +115 -0
  110. package/docs/reference/protocol.md +96 -0
  111. package/docs/reference/provider-adapters.md +158 -0
  112. package/docs/responsive-orientation.md +37 -0
  113. package/docs/security.md +38 -0
  114. package/docs/streaming-protocol.md +15 -0
  115. package/docs/testing.md +137 -0
  116. package/docs/use-cases.md +59 -0
  117. package/examples/custom-template/README.md +19 -0
  118. package/examples/custom-template/minimal-text.tsx +82 -0
  119. package/examples/custom-template/structured-data.tsx +104 -0
  120. package/examples/custom-template/supplied-media.tsx +92 -0
  121. package/examples/nextjs-quickstart/.env.example +2 -0
  122. package/examples/nextjs-quickstart/README.md +22 -0
  123. package/examples/nextjs-quickstart/next-env.d.ts +4 -0
  124. package/examples/nextjs-quickstart/package.json +24 -0
  125. package/examples/nextjs-quickstart/src/app/api/video/route.ts +22 -0
  126. package/examples/nextjs-quickstart/src/app/layout.tsx +5 -0
  127. package/examples/nextjs-quickstart/src/app/page.tsx +31 -0
  128. package/examples/nextjs-quickstart/tsconfig.json +26 -0
  129. package/package.json +167 -0
  130. package/registry/items/backgrounds.json +52 -0
  131. package/registry/items/barChart.json +237 -0
  132. package/registry/items/beforeAfter.json +180 -0
  133. package/registry/items/bigNumber.json +225 -0
  134. package/registry/items/brandMessage.json +158 -0
  135. package/registry/items/cardList.json +206 -0
  136. package/registry/items/chatMessenger.json +151 -0
  137. package/registry/items/chatWhatsapp.json +151 -0
  138. package/registry/items/codeEditor.json +184 -0
  139. package/registry/items/confetti.json +107 -0
  140. package/registry/items/ctaLogo.json +160 -0
  141. package/registry/items/ctaMedia.json +193 -0
  142. package/registry/items/emojiBurst.json +101 -0
  143. package/registry/items/incomingCall.json +170 -0
  144. package/registry/items/media.json +179 -0
  145. package/registry/items/milestone.json +205 -0
  146. package/registry/items/motion.json +45 -0
  147. package/registry/items/notification.json +182 -0
  148. package/registry/items/phoneMockup.json +254 -0
  149. package/registry/items/problemSolution.json +186 -0
  150. package/registry/items/progressRing.json +199 -0
  151. package/registry/items/promptInput.json +148 -0
  152. package/registry/items/reaction.json +170 -0
  153. package/registry/items/reviewStack.json +224 -0
  154. package/registry/items/steps.json +207 -0
  155. package/registry/items/template-context.json +31 -0
  156. package/registry/items/terminal.json +212 -0
  157. package/registry/items/testimonial.json +164 -0
  158. package/registry/items/theme.json +47 -0
  159. package/registry/items/tripleStats.json +228 -0
  160. package/registry/items/tweet.json +203 -0
  161. package/registry/items/typography.json +47 -0
  162. package/registry/items/webMockup.json +273 -0
@@ -0,0 +1,151 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
+ "name": "chatWhatsapp",
4
+ "type": "registry:block",
5
+ "title": "WhatsApp chat",
6
+ "description": "A staggered WhatsApp-style conversation with three to five message bubbles.",
7
+ "dependencies": [
8
+ "react"
9
+ ],
10
+ "registryDependencies": [
11
+ "@vanillasky/motion",
12
+ "@vanillasky/theme",
13
+ "@vanillasky/typography",
14
+ "@vanillasky/template-context"
15
+ ],
16
+ "files": [
17
+ {
18
+ "path": "src/visual-system/scene-templates/social-conversation.tsx",
19
+ "type": "registry:component",
20
+ "target": "vanillasky/scene-templates/social-conversation.tsx",
21
+ "content": "/**\n * chatMessenger + chatWhatsapp — themed conversation scenes.\n *\n * ConversationThread owns bubble chrome, typing, receipts, chips, timing,\n * orientation, and export-safe emoji rendering. This template translates the\n * editable msg1..msg5 fields into the primitive's message collection.\n */\n\nimport * as React from \"react\";\nimport type { SceneTemplateProps } from \"./types\";\nimport { normalizeTextVar } from \"./normalize-var\";\nimport { ConversationThread } from \"../primitives/social/ConversationThread\";\n\nconst DEFAULT_SIDES: Record<number, \"left\" | \"right\"> = {\n 1: \"left\",\n 2: \"right\",\n 3: \"left\",\n 4: \"right\",\n 5: \"right\",\n};\n\nexport function buildConversationMessages(variables: Record<string, unknown>) {\n const messages: Array<{ author: string; text: string; side: \"left\" | \"right\" }> = [];\n for (let index = 1; index <= 5; index += 1) {\n let text = normalizeTextVar(variables[`msg${index}`]).trim();\n if (!text) continue;\n let side = DEFAULT_SIDES[index] ?? (index % 2 === 1 ? \"left\" : \"right\");\n if (text.endsWith(\"|in\")) {\n side = \"left\";\n text = text.slice(0, -3).trim();\n } else if (text.endsWith(\"|out\")) {\n side = \"right\";\n text = text.slice(0, -4).trim();\n }\n messages.push({ author: side === \"left\" ? \"Customer\" : \"You\", text, side });\n }\n return messages;\n}\n\nexport const SocialConversationTemplate: React.FC<SceneTemplateProps> = ({\n variables,\n progress,\n beatIntensity,\n width,\n height,\n sceneDuration,\n safeZone,\n}) => {\n const theme = String(variables.theme || \"messenger\").toLowerCase() === \"whatsapp\"\n ? \"whatsapp\"\n : \"messenger\";\n\n return (\n <div style={{ width, height, position: \"relative\", overflow: \"hidden\", backgroundColor: theme === \"whatsapp\" ? \"#EFE7DC\" : \"#ffffff\" }}>\n {/* [slot: hero] ConversationThread includes the theme-specific canvas. */}\n <ConversationThread\n progress={progress}\n width={width}\n height={height}\n sceneDuration={sceneDuration ?? 8}\n messages={buildConversationMessages(variables)}\n theme={theme}\n dateChip1={String(variables.dateChip1 || \"\")}\n dateChip2={String(variables.dateChip2 || \"\")}\n safeZoneTop={Math.max(safeZone.top, height * 0.08)}\n beatIntensity={beatIntensity}\n />\n </div>\n );\n};\n"
22
+ },
23
+ {
24
+ "path": "src/visual-system/primitives/social/ConversationThread.tsx",
25
+ "type": "registry:component",
26
+ "target": "vanillasky/primitives/social/ConversationThread.tsx",
27
+ "content": "/**\n * ConversationThread — multi-bubble chat thread with staggered reveal,\n * typing indicators, and (for WhatsApp) animated read receipts.\n *\n * Lifted from `social-conversation.tsx`. The primitive owns:\n * - the centered chat column (full-width portrait / ~72% landscape)\n * - per-message typing → bubble pop sequence\n * - WhatsApp tick state progression (clock → sent → delivered → read)\n * - optional date chips inserted between specific messages\n * - the WhatsApp compose bar (decorative — drawn 1:1 from the source)\n *\n * It does NOT own a SceneBackground gradient/media or a headline overlay.\n * The primitive fills its own backdrop with the theme background color so\n * the bubbles always have correct contrast; if a caller wants the scene\n * gradient to show through, drop this primitive on top of a SceneBackground.\n *\n * The source template parses messages from `msg1..msg5` variables plus a\n * `|in`/`|out` suffix override. This primitive accepts the already-parsed\n * `messages` array so callers can pre-split however they like.\n *\n * Local helpers (`easeOutBack`, `tickStateAt`, `timingForCount`) are\n * inlined because the source defined them locally; they are not exported.\n *\n * Props:\n * - progress — scene progress 0..1\n * - width / height — frame dimensions\n * - sceneDuration — seconds; drives the 1.5 Hz typing-dot ripple in real time\n * - messages — array of `{ author, text, side }`. `author` is\n * decorative (not rendered in either theme today) but\n * accepted so callers don't lose data when round-tripping.\n * - theme — \"whatsapp\" or \"messenger\" (iMessage). Default \"whatsapp\".\n * - safeZoneTop — top inset to clear the social overlay UI. Default 8% of height.\n * - accent — brand accent (kept for parity; today's chrome is locked\n * to WhatsApp/iMessage native palettes for realism)\n * - beatIntensity — accepted for parity; not currently applied\n */\n\nimport * as React from \"react\";\nimport { interpolate } from \"../../motion\";\nimport { stripPipe } from \"../../typography\";\nimport { renderWithEmoji } from \"../../emoji/emoji-text\";\n\nconst CLAMP = {\n extrapolateLeft: \"clamp\" as const,\n extrapolateRight: \"clamp\" as const,\n};\n\n/* Reference timeline length — every reveal time is a fraction of this. */\nconst REF_DURATION = 16;\n\n/* easeOutBack — same overshoot curve the source uses for pop-ins. */\nfunction easeOutBack(t: number): number {\n const c1 = 1.70158;\n const c3 = c1 + 1;\n return 1 + c3 * Math.pow(t - 1, 3) + c1 * Math.pow(t - 1, 2);\n}\n\n/* WhatsApp palette */\nconst WA = {\n bg: \"#EFE7DC\",\n incomingBubble: \"#FFFFFF\",\n outgoingBubble: \"#D9F4C7\",\n text: \"#0E0E0E\",\n textMuted: \"#6E6E73\",\n accent: \"#0A8F76\",\n chipBg: \"#F1E9D8\",\n chipText: \"#3C342A\",\n navBg: \"#F1E9DA\",\n inputBg: \"#FFFFFF\",\n inputBorder: \"rgba(0,0,0,0.06)\",\n outgoingTime: \"#5C6B4E\",\n};\n\n/* iMessage palette */\nconst IM = {\n bg: \"#ffffff\",\n bubbleOut: \"#007AFF\",\n bubbleIn: \"#E9E9EB\",\n textOut: \"#ffffff\",\n textIn: \"#000000\",\n dotsColor: \"#8E8E93\",\n};\n\ninterface InternalMessage {\n side: \"left\" | \"right\";\n text: string;\n author: string;\n typingStart: number;\n bubbleStart: number;\n time: string;\n}\n\n/* WhatsApp reference timing — mirrors source 5-message cadence. */\nconst WA_TIMING_5: Array<{ typingStart: number; bubbleStart: number; time: string }> = [\n { typingStart: 0.6, bubbleStart: 1.4, time: \"21:54\" },\n { typingStart: 2.2, bubbleStart: 3.0, time: \"21:55\" },\n { typingStart: 3.8, bubbleStart: 4.8, time: \"21:56\" },\n { typingStart: 6.2, bubbleStart: 7.2, time: \"12:35\" },\n { typingStart: 10.0, bubbleStart: 11.0, time: \"11:17\" },\n];\n\nfunction timingForCount(count: number): Array<{ typingStart: number; bubbleStart: number; time: string }> {\n if (count >= 5) return WA_TIMING_5.slice(0, count);\n const slot = 12 / count;\n const out: Array<{ typingStart: number; bubbleStart: number; time: string }> = [];\n for (let i = 0; i < count; i++) {\n const start = 0.6 + i * slot;\n out.push({\n typingStart: start,\n bubbleStart: start + slot * 0.5,\n time: WA_TIMING_5[Math.min(i, 4)].time,\n });\n }\n return out;\n}\n\n/* Read-receipt phases (WhatsApp). */\ntype TickState = \"clock\" | \"sent\" | \"delivered\" | \"read\";\n\nfunction tickStateAt(refTimeSinceSent: number): TickState {\n if (refTimeSinceSent < 0.5) return \"clock\";\n if (refTimeSinceSent < 1.1) return \"sent\";\n if (refTimeSinceSent < 1.8) return \"delivered\";\n return \"read\";\n}\n\nconst ClockIcon: React.FC<{ s: number }> = ({ s }) => (\n <svg width={12 * s} height={12 * s} viewBox=\"0 0 12 12\" style={{ marginLeft: 4 * s }}>\n <circle cx=\"6\" cy=\"6\" r=\"5\" fill=\"none\" stroke=\"#8C8C92\" strokeWidth=\"1.2\" />\n <path d=\"M6 3 v3.5 l2 1\" stroke=\"#8C8C92\" strokeWidth=\"1.2\" fill=\"none\" strokeLinecap=\"round\" />\n </svg>\n);\n\nconst Ticks: React.FC<{ state: TickState; s: number }> = ({ state, s }) => {\n if (state === \"clock\") return <ClockIcon s={s} />;\n const color = state === \"read\" ? \"#53BDEB\" : \"#8C8C92\";\n return (\n <svg width={16 * s} height={11 * s} viewBox=\"0 0 16 11\" style={{ marginLeft: 4 * s }}>\n <path\n d=\"M1 6 l3 3 l6 -7\"\n stroke={color}\n strokeWidth={1.3}\n fill=\"none\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n opacity={state === \"sent\" ? 0 : 1}\n />\n <path\n d=\"M5 6 l3 3 l7 -8\"\n stroke={color}\n strokeWidth={1.3}\n fill=\"none\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n </svg>\n );\n};\n\nconst ComposeBar: React.FC<{ s: number }> = ({ s }) => {\n const stroke = \"#1A1A1A\";\n return (\n <div\n style={{\n background: WA.navBg,\n borderTop: \"1px solid rgba(0,0,0,0.05)\",\n padding: `${10 * s}px ${14 * s}px ${12 * s}px`,\n display: \"flex\",\n alignItems: \"center\",\n gap: 14 * s,\n }}\n >\n <svg width={30 * s} height={30 * s} viewBox=\"0 0 30 30\" style={{ flexShrink: 0 }}>\n <path d=\"M15 5 v20 M5 15 h20\" stroke={stroke} strokeWidth=\"1.8\" strokeLinecap=\"round\" />\n </svg>\n <div\n style={{\n flex: 1,\n height: 40 * s,\n background: WA.inputBg,\n borderRadius: 22 * s,\n position: \"relative\",\n border: `0.5px solid ${WA.inputBorder}`,\n }}\n >\n <div\n style={{\n position: \"absolute\",\n right: 12 * s,\n top: \"50%\",\n transform: \"translateY(-50%)\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n }}\n >\n <svg width={28 * s} height={28 * s} viewBox=\"0 0 24 24\" fill=\"none\" style={{ display: \"block\" }}>\n <path\n d=\"M3 5 a2 2 0 0 1 2 -2 h10 a2 2 0 0 1 2 2 v6 l-6 6 h-6 a2 2 0 0 1 -2 -2 z M17 11 a4 4 0 0 0 -4 4 v2\"\n stroke=\"#555\"\n strokeWidth=\"1.5\"\n fill=\"none\"\n strokeLinejoin=\"round\"\n strokeLinecap=\"round\"\n />\n </svg>\n </div>\n </div>\n <svg width={28 * s} height={24 * s} viewBox=\"0 0 28 24\" fill=\"none\" style={{ flexShrink: 0 }}>\n <path\n d=\"M3 6 h5 l2 -3 h8 l2 3 h5 a1 1 0 0 1 1 1 v14 a1 1 0 0 1 -1 1 h-22 a1 1 0 0 1 -1 -1 v-14 a1 1 0 0 1 1 -1 z\"\n stroke={stroke}\n strokeWidth=\"1.6\"\n fill=\"none\"\n strokeLinejoin=\"round\"\n />\n <circle cx=\"14\" cy=\"14\" r=\"4.5\" stroke={stroke} strokeWidth=\"1.6\" fill=\"none\" />\n </svg>\n <svg width={20 * s} height={26 * s} viewBox=\"0 0 20 26\" fill=\"none\" style={{ flexShrink: 0 }}>\n <rect x=\"7\" y=\"2\" width=\"6\" height=\"13\" rx=\"3\" stroke={stroke} strokeWidth=\"1.6\" fill=\"none\" />\n <path\n d=\"M3 12 a7 7 0 0 0 14 0 M10 19 v4 M7 23 h6\"\n stroke={stroke}\n strokeWidth=\"1.6\"\n fill=\"none\"\n strokeLinecap=\"round\"\n />\n </svg>\n </div>\n );\n};\n\nconst TypingBubble: React.FC<{\n side: \"left\" | \"right\";\n pop: number;\n realTimeSeconds: number;\n s: number;\n theme: \"whatsapp\" | \"messenger\";\n}> = ({ side, pop, realTimeSeconds, s, theme }) => {\n if (pop <= 0) return null;\n const isOut = side === \"right\";\n const isWA = theme === \"whatsapp\";\n const dotColor = isWA ? (isOut ? \"#6B8A55\" : \"#8C8C92\") : IM.dotsColor;\n const bg = isWA\n ? isOut\n ? WA.outgoingBubble\n : WA.incomingBubble\n : isOut\n ? IM.bubbleOut\n : IM.bubbleIn;\n\n return (\n <div\n style={{\n display: \"flex\",\n justifyContent: isOut ? \"flex-end\" : \"flex-start\",\n padding: `${2 * s}px ${(isWA ? 10 : 14) * s}px`,\n opacity: pop,\n transform: `scale(${0.9 + 0.1 * pop})`,\n transformOrigin: isOut ? \"right bottom\" : \"left bottom\",\n }}\n >\n <div\n style={{\n background: bg,\n borderRadius: (isWA ? 14 : 18) * s,\n ...(isWA\n ? {\n borderTopLeftRadius: isOut ? 14 * s : 2 * s,\n borderTopRightRadius: isOut ? 2 * s : 14 * s,\n }\n : {}),\n padding: `${(isWA ? 10 : 12) * s}px ${(isWA ? 12 : 16) * s}px`,\n display: \"flex\",\n gap: 5 * s,\n alignItems: \"center\",\n ...(isWA\n ? { boxShadow: `0 ${1 * s}px ${1 * s}px rgba(0,0,0,0.06)` }\n : {}),\n }}\n >\n {[0, 1, 2].map((i) => {\n const phase = (realTimeSeconds * 1.6 + i * 0.2) % 1;\n const y = Math.sin(phase * Math.PI * 2) * 2.5 * s;\n const op = 0.45 + 0.55 * Math.max(0, Math.sin(phase * Math.PI));\n const dotSize = isWA ? 6 * s : 7 * s;\n return (\n <div\n key={i}\n style={{\n width: dotSize,\n height: dotSize,\n borderRadius: dotSize / 2,\n background: dotColor,\n transform: `translateY(${-y}px)`,\n opacity: op,\n }}\n />\n );\n })}\n </div>\n </div>\n );\n};\n\nconst DateChip: React.FC<{ label: string; chipProgress: number; s: number }> = ({\n label,\n chipProgress,\n s,\n}) => {\n if (chipProgress <= 0) return null;\n return (\n <div\n style={{\n display: \"flex\",\n justifyContent: \"center\",\n margin: `${12 * s}px 0 ${8 * s}px`,\n opacity: chipProgress,\n transform: `scale(${0.88 + 0.12 * chipProgress})`,\n }}\n >\n <div\n style={{\n background: WA.chipBg,\n color: WA.chipText,\n padding: `${7 * s}px ${16 * s}px`,\n borderRadius: 9 * s,\n fontSize: 17 * s,\n fontWeight: 600,\n boxShadow: `0 ${1 * s}px ${1.5 * s}px rgba(0,0,0,0.05)`,\n }}\n >\n {label}\n </div>\n </div>\n );\n};\n\nconst IncomingBubble: React.FC<{\n children: React.ReactNode;\n time: string;\n pop: number;\n s: number;\n}> = ({ children, time, pop, s }) => (\n <div\n style={{\n display: \"flex\",\n justifyContent: \"flex-start\",\n padding: `${2 * s}px ${10 * s}px`,\n opacity: pop,\n transform: `translateY(${(1 - pop) * 6 * s}px) scale(${0.97 + 0.03 * pop})`,\n transformOrigin: \"left bottom\",\n }}\n >\n <div\n style={{\n maxWidth: \"82%\",\n background: WA.incomingBubble,\n borderRadius: 10 * s,\n borderTopLeftRadius: 2 * s,\n padding: `${12 * s}px ${16 * s}px ${11 * s}px`,\n fontSize: 23 * s,\n lineHeight: `${29 * s}px`,\n color: WA.text,\n boxShadow: `0 ${1 * s}px ${1 * s}px rgba(0,0,0,0.06)`,\n position: \"relative\",\n }}\n >\n <div style={{ paddingRight: 64 * s }}>{children}</div>\n <div\n style={{\n position: \"absolute\",\n right: 14 * s,\n bottom: 8 * s,\n fontSize: 15 * s,\n color: WA.textMuted,\n }}\n >\n {time}\n </div>\n </div>\n </div>\n);\n\nconst OutgoingBubble: React.FC<{\n children: React.ReactNode;\n time: string;\n tickState: TickState;\n pop: number;\n s: number;\n}> = ({ children, time, tickState, pop, s }) => (\n <div\n style={{\n display: \"flex\",\n justifyContent: \"flex-end\",\n padding: `${2 * s}px ${10 * s}px`,\n opacity: pop,\n transform: `translateY(${(1 - pop) * 8 * s}px) scale(${0.96 + 0.04 * pop})`,\n transformOrigin: \"right bottom\",\n }}\n >\n <div\n style={{\n maxWidth: \"82%\",\n background: WA.outgoingBubble,\n borderRadius: 10 * s,\n borderTopRightRadius: 2 * s,\n padding: `${12 * s}px ${16 * s}px ${11 * s}px`,\n fontSize: 23 * s,\n lineHeight: `${29 * s}px`,\n color: WA.text,\n boxShadow: `0 ${1 * s}px ${1 * s}px rgba(0,0,0,0.06)`,\n position: \"relative\",\n }}\n >\n <div style={{ paddingRight: 88 * s }}>{children}</div>\n <div\n style={{\n position: \"absolute\",\n right: 14 * s,\n bottom: 8 * s,\n fontSize: 15 * s,\n color: WA.outgoingTime,\n display: \"flex\",\n alignItems: \"center\",\n }}\n >\n {time}\n <Ticks state={tickState} s={s} />\n </div>\n </div>\n </div>\n);\n\nconst CHIP_TIMING = {\n monday: { start: 5.8, end: 6.2 },\n yesterday: { start: 9.6, end: 10.0 },\n};\n\nexport interface ConversationThreadProps {\n progress: number;\n width: number;\n height: number;\n sceneDuration: number;\n messages: Array<{ author: string; text: string; side: \"left\" | \"right\" }>;\n theme?: \"whatsapp\" | \"messenger\";\n /** Optional date chips inserted before specific message indices.\n * Default behavior matches the source: chip1 before message 4 (index 3),\n * chip2 before message 5 (index 4). Leave blank to suppress. */\n dateChip1?: string;\n dateChip2?: string;\n safeZoneTop?: number;\n accent?: string;\n beatIntensity?: number;\n}\n\nexport const ConversationThread: React.FC<ConversationThreadProps> = ({\n progress,\n width,\n height,\n sceneDuration,\n messages: rawMessages,\n theme = \"whatsapp\",\n dateChip1 = \"\",\n dateChip2 = \"\",\n safeZoneTop,\n}) => {\n const isLandscape = width > height;\n const colWidth = isLandscape ? width * 0.72 : width;\n const colLeft = (width - colWidth) / 2;\n const s = Math.min(width, height) / 534;\n const isWhatsApp = theme === \"whatsapp\";\n\n // Apply stripPipe + attach timing\n const sanitized = rawMessages\n .map((m) => ({ ...m, text: stripPipe(m.text || \"\").trim() }))\n .filter((m) => m.text.length > 0);\n const timing = timingForCount(Math.max(1, sanitized.length));\n const messages: InternalMessage[] = sanitized.map((m, i) => ({\n side: m.side,\n text: m.text,\n author: m.author,\n typingStart: timing[i].typingStart,\n bubbleStart: timing[i].bubbleStart,\n time: timing[i].time,\n }));\n\n const realTimeSeconds = progress * sceneDuration;\n const refT = progress * REF_DURATION;\n const topPad = safeZoneTop != null ? safeZoneTop : height * 0.08;\n\n const chip1Label = stripPipe(dateChip1 || \"\").trim();\n const chip2Label = stripPipe(dateChip2 || \"\").trim();\n\n const popIn = (t: number, start: number, dur = 0.4): number => {\n if (t <= start) return 0;\n if (t >= start + dur) return 1;\n return easeOutBack((t - start) / dur);\n };\n\n const ramp = (t: number, start: number, end: number): number => {\n if (t <= start) return 0;\n if (t >= end) return 1;\n return (t - start) / (end - start);\n };\n\n if (isWhatsApp) {\n return (\n <div\n style={{\n position: \"absolute\",\n inset: 0,\n background: WA.bg,\n overflow: \"hidden\",\n fontFamily: '-apple-system, \"SF Pro Text\", system-ui',\n }}\n >\n <div\n style={{\n position: \"absolute\",\n left: colLeft,\n width: colWidth,\n top: 0,\n height,\n display: \"flex\",\n flexDirection: \"column\",\n }}\n >\n <div style={{ flex: 1, position: \"relative\", overflow: \"hidden\" }}>\n <div\n style={{\n position: \"absolute\",\n left: 0,\n right: 0,\n top: 0,\n display: \"flex\",\n flexDirection: \"column\",\n gap: 2 * s,\n padding: `${topPad}px 0 ${10 * s}px`,\n }}\n >\n {messages.map((msg, i) => {\n const typingPop = popIn(refT, msg.typingStart, 0.25);\n const typingFade = interpolate(\n refT,\n [msg.bubbleStart - 0.1, msg.bubbleStart],\n [1, 0],\n CLAMP,\n );\n const showTyping = refT >= msg.typingStart && refT < msg.bubbleStart;\n const bubblePop = popIn(refT, msg.bubbleStart, 0.4);\n const showBubble = refT >= msg.bubbleStart;\n const isOut = msg.side === \"right\";\n\n const refSinceSent = refT - msg.bubbleStart - 0.4;\n const tickState = isOut ? tickStateAt(Math.max(0, refSinceSent)) : \"read\";\n\n const chipBeforeThis: { label: string; progress: number } | null = (() => {\n if (i === 3 && chip1Label) {\n return {\n label: chip1Label,\n progress: ramp(refT, CHIP_TIMING.monday.start, CHIP_TIMING.monday.end),\n };\n }\n if (i === 4 && chip2Label) {\n return {\n label: chip2Label,\n progress: ramp(refT, CHIP_TIMING.yesterday.start, CHIP_TIMING.yesterday.end),\n };\n }\n return null;\n })();\n\n return (\n <React.Fragment key={i}>\n {chipBeforeThis && (\n <DateChip\n label={chipBeforeThis.label}\n chipProgress={chipBeforeThis.progress}\n s={s}\n />\n )}\n\n {showTyping && (\n <div style={{ opacity: typingPop * typingFade }}>\n <TypingBubble\n side={msg.side}\n pop={typingPop}\n realTimeSeconds={realTimeSeconds}\n s={s}\n theme=\"whatsapp\"\n />\n </div>\n )}\n\n {showBubble &&\n (isOut ? (\n <OutgoingBubble pop={bubblePop} time={msg.time} tickState={tickState} s={s}>\n {renderWithEmoji(msg.text, 23 * s)}\n </OutgoingBubble>\n ) : (\n <IncomingBubble pop={bubblePop} time={msg.time} s={s}>\n {renderWithEmoji(msg.text, 23 * s)}\n </IncomingBubble>\n ))}\n </React.Fragment>\n );\n })}\n\n <div style={{ height: 12 * s }} />\n </div>\n </div>\n\n <ComposeBar s={s} />\n </div>\n </div>\n );\n }\n\n // iMessage render\n return (\n <div\n style={{\n position: \"absolute\",\n inset: 0,\n background: IM.bg,\n overflow: \"hidden\",\n fontFamily: \"-apple-system, 'SF Pro', 'Helvetica Neue', Helvetica, Arial, sans-serif\",\n }}\n >\n <div\n style={{\n position: \"absolute\",\n left: colLeft,\n width: colWidth,\n top: 0,\n height,\n padding: `${topPad}px 0 ${20 * s}px`,\n display: \"flex\",\n flexDirection: \"column\",\n gap: 4 * s,\n }}\n >\n {messages.map((msg, i) => {\n const typingPop = popIn(refT, msg.typingStart, 0.25);\n const typingFade = interpolate(\n refT,\n [msg.bubbleStart - 0.1, msg.bubbleStart],\n [1, 0],\n CLAMP,\n );\n const showTyping = refT >= msg.typingStart && refT < msg.bubbleStart;\n const bubblePop = popIn(refT, msg.bubbleStart, 0.4);\n const showBubble = refT >= msg.bubbleStart;\n const isOut = msg.side === \"right\";\n\n return (\n <React.Fragment key={i}>\n {showTyping && (\n <div style={{ opacity: typingPop * typingFade }}>\n <TypingBubble\n side={msg.side}\n pop={typingPop}\n realTimeSeconds={realTimeSeconds}\n s={s}\n theme=\"messenger\"\n />\n </div>\n )}\n\n {showBubble && (\n <div\n style={{\n display: \"flex\",\n justifyContent: isOut ? \"flex-end\" : \"flex-start\",\n padding: `${2 * s}px ${14 * s}px`,\n opacity: bubblePop,\n transform: `translateY(${(1 - bubblePop) * 8 * s}px) scale(${0.96 + 0.04 * bubblePop})`,\n transformOrigin: isOut ? \"right bottom\" : \"left bottom\",\n }}\n >\n <div\n style={{\n maxWidth: \"75%\",\n background: isOut ? IM.bubbleOut : IM.bubbleIn,\n color: isOut ? IM.textOut : IM.textIn,\n borderRadius: 22 * s,\n padding: `${12 * s}px ${18 * s}px`,\n fontSize: 23 * s,\n lineHeight: `${29 * s}px`,\n }}\n >\n {renderWithEmoji(msg.text, 23 * s)}\n </div>\n </div>\n )}\n </React.Fragment>\n );\n })}\n </div>\n </div>\n );\n};\n"
28
+ },
29
+ {
30
+ "path": "src/visual-system/emoji/emoji-text.tsx",
31
+ "type": "registry:component",
32
+ "target": "vanillasky/emoji/emoji-text.tsx",
33
+ "content": "/**\n * EmojiText / renderWithEmoji — split a string into text runs + emoji runs,\n * rendering each emoji with the viewer's native emoji font while leaving\n * everything else as plain text.\n *\n * Segmentation: grapheme clusters via Intl.Segmenter so ZWJ sequences\n * (👩‍💻) and skin-tone modifiers (👍🏽) stay single units. Adjacent emoji\n * clusters each render as their own span in sequence.\n */\n\nimport * as React from \"react\";\nimport { Emoji, isNativeEmoji } from \"./index\";\n\n/** Split text into grapheme clusters (ZWJ + skin-tone safe). */\nfunction toGraphemes(text: string): string[] {\n const Seg = (Intl as unknown as { Segmenter?: typeof Intl.Segmenter }).Segmenter;\n if (Seg) {\n const seg = new Seg(undefined, { granularity: \"grapheme\" });\n const out: string[] = [];\n for (const { segment } of seg.segment(text)) out.push(segment);\n return out;\n }\n // Fallback: code-point spread. Won't keep ZWJ/skin-tone as single units, so\n // those land as separate clusters. Modern browsers all have Segmenter.\n return Array.from(text);\n}\n\nexport interface RenderWithEmojiOptions {\n /** vertical-align passed to each <Emoji>. */\n verticalAlign?: React.CSSProperties[\"verticalAlign\"];\n /** Extra style merged onto each emoji span. */\n emojiStyle?: React.CSSProperties;\n}\n\n/**\n * Split `text` into an array of React nodes — plain-text strings interleaved\n * with <Emoji> spans for every emoji cluster. Returns a single-element\n * `[text]` fast-path when there are no emoji (the common case), so\n * non-emoji text pays ~one regex test.\n *\n * @param text the string to render\n * @param fontSizePx surrounding font size in px (emoji box = this size)\n */\nexport function renderWithEmoji(\n text: string,\n fontSizePx: number,\n opts?: RenderWithEmojiOptions,\n): React.ReactNode[] {\n if (!text) return [text];\n // Cheap bail-out: if the whole string has no emoji-range codepoint, return\n // it untouched (no segmentation, no array churn) — the hot path for the vast\n // majority of titles/bodies.\n if (!isNativeEmoji(text)) return [text];\n\n const clusters = toGraphemes(text);\n const nodes: React.ReactNode[] = [];\n let textBuf = \"\";\n let key = 0;\n\n const flushText = () => {\n if (textBuf) {\n nodes.push(textBuf);\n textBuf = \"\";\n }\n };\n\n for (const cluster of clusters) {\n if (isNativeEmoji(cluster)) {\n flushText();\n nodes.push(\n <Emoji\n key={`e${key++}`}\n char={cluster}\n size={fontSizePx}\n verticalAlign={opts?.verticalAlign}\n style={opts?.emojiStyle}\n />,\n );\n } else {\n textBuf += cluster;\n }\n }\n flushText();\n return nodes;\n}\n\n/**\n * Per-code-unit emoji plan for the typewriter archetype, which reveals text\n * one UTF-16 code unit at a time and indexes by `text.length`. We can't just\n * call renderWithEmoji there (it would re-segment and desync the visibleChars\n * counter), so this maps each cluster's START code-unit index to the full emoji\n * and marks the cluster's CONTINUATION indices as covered (render nothing for\n * them — the start index's span already contains the whole cluster).\n *\n * Returns null when the text contains no emoji (the common case),\n * so the typewriter render keeps its plain per-char path.\n */\nexport interface EmojiTypewriterPlan {\n /** code-unit index → full emoji cluster char (cluster start). */\n starts: Map<number, string>;\n /** code-unit indices that are continuations of a cluster (render nothing). */\n covered: Set<number>;\n}\n\nexport function planTypewriterEmoji(text: string): EmojiTypewriterPlan | null {\n if (!text || !isNativeEmoji(text)) return null;\n const starts = new Map<number, string>();\n const covered = new Set<number>();\n let idx = 0;\n let found = false;\n for (const cluster of toGraphemes(text)) {\n const len = cluster.length; // UTF-16 code units\n if (isNativeEmoji(cluster)) {\n found = true;\n // Store the WHOLE cluster char (not just the start unit) so callers can\n // pass it straight to <Emoji> without splitting a grapheme cluster.\n starts.set(idx, cluster);\n for (let k = 1; k < len; k++) covered.add(idx + k);\n }\n idx += len;\n }\n return found ? { starts, covered } : null;\n}\n\nexport interface EmojiTextProps {\n /** The text to render with emoji in the native operating-system font. */\n children: string;\n /** Surrounding font size in px — sizes each emoji to match a glyph. */\n fontSize: number;\n verticalAlign?: React.CSSProperties[\"verticalAlign\"];\n emojiStyle?: React.CSSProperties;\n}\n\n/**\n * Inline wrapper around renderWithEmoji. Renders a React.Fragment of text +\n * emoji spans. Use where a component currently renders a raw `{text}`\n * child and you have the surrounding font size in px.\n */\nexport const EmojiText: React.FC<EmojiTextProps> = ({\n children,\n fontSize,\n verticalAlign,\n emojiStyle,\n}) => {\n const text = typeof children === \"string\" ? children : \"\";\n return <>{renderWithEmoji(text, fontSize, { verticalAlign, emojiStyle })}</>;\n};\n"
34
+ },
35
+ {
36
+ "path": "src/visual-system/emoji/index.tsx",
37
+ "type": "registry:component",
38
+ "target": "vanillasky/emoji/index.tsx",
39
+ "content": "import * as React from \"react\";\n\nconst NATIVE_EMOJI_FONT = \"Apple Color Emoji,Segoe UI Emoji,Noto Color Emoji,sans-serif\";\nconst NATIVE_EMOJI = /\\p{Emoji_Presentation}|\\p{Regional_Indicator}|\\u{FE0F}|\\u{20E3}/u;\n\n/** True for emoji-presentation graphemes, not plain symbols such as ★ or ✓. */\nexport function isNativeEmoji(char: string): boolean {\n return NATIVE_EMOJI.test(char);\n}\n\nexport interface EmojiProps {\n /** The emoji character or grapheme cluster, e.g. \"🎉\" or \"👩‍💻\". */\n char: string;\n /** Font size in px. */\n size: number;\n /** vertical-align for inline flow. Defaults to a glyph-like baseline nudge. */\n verticalAlign?: React.CSSProperties[\"verticalAlign\"];\n /** Extra styles merged onto the native emoji span. */\n style?: React.CSSProperties;\n}\n\n/** Render emoji with the viewer's OS font while preserving text-style symbols. */\nexport const Emoji: React.FC<EmojiProps> = ({ char, size, verticalAlign = \"-0.15em\", style }) => {\n const nativeEmoji = isNativeEmoji(char);\n return (\n <span\n role={nativeEmoji ? \"img\" : undefined}\n aria-label={nativeEmoji ? char : undefined}\n style={{\n ...(nativeEmoji ? { fontFamily: NATIVE_EMOJI_FONT } : {}),\n fontSize: size,\n lineHeight: 1,\n display: \"inline-block\",\n verticalAlign,\n ...style,\n }}\n >\n {char}\n </span>\n );\n};\n"
40
+ },
41
+ {
42
+ "path": "src/visual-system/scene-templates/normalize-var.ts",
43
+ "type": "registry:lib",
44
+ "target": "vanillasky/scene-templates/normalize-var.ts",
45
+ "content": "/**\n * normalize-var — Defensive parsing for structured template variables.\n *\n * LLMs may pass variables as colon-separated strings (expected), JSON strings,\n * or raw objects. These helpers normalize any format to the colon-separated\n * string that existing template parsers expect.\n */\n\n/**\n * Normalize a structured variable (e.g. notif1, transaction1) to a colon-separated string.\n *\n * Accepts:\n * - Colon-separated string: \"🔔:App:Hello:1m\" → passed through\n * - JSON string: '{\"emoji\":\"🔔\",\"app\":\"App\"}' → parsed and mapped\n * - Object: {emoji: \"🔔\", app: \"App\"} → mapped to colon-separated\n *\n * @param raw - The variable value (string, object, or unknown)\n * @param keyAliases - Array of alias arrays, one per field position.\n * e.g. [[\"emoji\"], [\"app\", \"title\", \"appName\"], [\"message\", \"body\", \"text\"], [\"time\"]]\n */\nexport function normalizeStructuredVar(\n raw: unknown,\n keyAliases: string[][],\n): string {\n if (typeof raw === \"string\") {\n const trimmed = raw.trim();\n if (trimmed.startsWith(\"{\")) {\n try {\n const obj = JSON.parse(trimmed);\n if (typeof obj === \"object\" && obj !== null) {\n return extractFromObject(obj, keyAliases);\n }\n } catch {\n // Not valid JSON — pass through as regular string\n }\n }\n return raw;\n }\n\n if (typeof raw === \"object\" && raw !== null) {\n return extractFromObject(raw as Record<string, unknown>, keyAliases);\n }\n\n return String(raw || \"\");\n}\n\nfunction extractFromObject(\n obj: Record<string, unknown>,\n keyAliases: string[][],\n): string {\n return keyAliases\n .map((aliases) => {\n for (const key of aliases) {\n if (obj[key] !== undefined && obj[key] !== null && obj[key] !== \"\") {\n return String(obj[key]);\n }\n }\n return \"\";\n })\n .join(\":\");\n}\n\n/**\n * Normalize a simple text variable for chat templates (msg1-msg4).\n *\n * Accepts:\n * - Plain string: \"Hello\" → passed through\n * - String with side: \"Hello|in\" → passed through\n * - JSON string: '{\"text\":\"Hello\",\"side\":\"in\"}' → \"Hello|in\"\n * - Object: {text: \"Hello\", side: \"in\"} → \"Hello|in\"\n */\nexport function normalizeTextVar(raw: unknown): string {\n if (typeof raw === \"string\") {\n const trimmed = raw.trim();\n if (trimmed.startsWith(\"{\")) {\n try {\n const obj = JSON.parse(trimmed);\n if (typeof obj === \"object\" && obj !== null) {\n return extractTextFromObject(obj);\n }\n } catch {\n // Not valid JSON\n }\n }\n return raw;\n }\n\n if (typeof raw === \"object\" && raw !== null) {\n return extractTextFromObject(raw as Record<string, unknown>);\n }\n\n return String(raw || \"\");\n}\n\nfunction extractTextFromObject(obj: Record<string, unknown>): string {\n const text = String(\n obj.text || obj.message || obj.body || obj.content || \"\",\n );\n const side = String(obj.side || obj.direction || \"\").toLowerCase();\n if (\n side === \"in\" ||\n side === \"left\" ||\n side === \"incoming\" ||\n side === \"received\"\n ) {\n return text + \"|in\";\n }\n if (\n side === \"out\" ||\n side === \"right\" ||\n side === \"outgoing\" ||\n side === \"sent\"\n ) {\n return text + \"|out\";\n }\n return text;\n}\n"
46
+ },
47
+ {
48
+ "path": "src/visual-system/scene-templates/types.ts",
49
+ "type": "registry:lib",
50
+ "target": "vanillasky/scene-templates/types.ts",
51
+ "content": "/**\n * Scene template types.\n *\n * A template is a reusable React component that defines how a scene looks.\n * It declares the variables an editor or model may provide\n * and receives universal settings as props.\n *\n * Templates are searchable by AI via description, category, jobs, register,\n * and useWhen guidance.\n * The variable schema enables any LLM to fill in template variables via JSON.\n */\n\nimport type { ResolvedTokens } from \"../theme\";\nimport type { SafeZone, TemplateStyle } from \"../template-context\";\n\n/**\n * Props passed to every scene template component.\n *\n * All animation must be driven by `progress` (0→1). No CSS animations,\n * no Framer Motion, no requestAnimationFrame. Use interpolate/spring\n * from animation-utils.ts.\n *\n * Scale factor: use `Math.min(width, height) / 1080` — normalizes to\n * the short edge so visuals are consistent across portrait and landscape.\n */\nexport interface SceneTemplateProps {\n variables: Record<string, unknown>;\n style: TemplateStyle;\n /** 0→1 through the scene's duration */\n progress: number;\n /** Presentation clock. Active templates receive the same complete 0→1 timeline as progress. */\n motionProgress?: number;\n /** 0→1 beat pulse intensity */\n beatIntensity: number;\n /** 1080 (portrait) or 1920 (landscape) */\n width: number;\n /** 1920 (portrait) or 1080 (landscape) */\n height: number;\n /** Video-level default text effect (for templates that opt in via usesGlobalTextEffect) */\n textArchetype?: string;\n /** How text leaves the scene (fade / shrink / pop / blur-scale). Falls back to a sensible default per textArchetype when undefined. */\n /** Video-level default background effect (for templates that opt in via usesGlobalBackgroundEffect) */\n backgroundEffect?: string;\n /** Platform-aware safe zone insets in pixels — use for text placement */\n safeZone: SafeZone;\n /** Scene duration in seconds — use for time-based (not progress-based) animations */\n sceneDuration?: number;\n /**\n * Brand tokens already resolved from `style`. Built-in templates import\n * resolveTokens directly; an ejected `custom_*` scene can't import anything,\n * so without this it has no way to reach the same values and ends up\n * hardcoding white, black and shadows — the body then looks generic next to\n * a frame that IS using the brand.\n */\n tokens?: ResolvedTokens;\n /**\n * True when the preview player is actively advancing progress; false when paused.\n * Templates that play HTML5 <video> elements should pause them when this is false.\n * Undefined (export capture path) is treated as true.\n */\n isPlaying?: boolean;\n}\n"
52
+ }
53
+ ],
54
+ "meta": {
55
+ "vanillasky": {
56
+ "layer": "template",
57
+ "tier": "free",
58
+ "register": "mockup-led",
59
+ "jobs": [
60
+ "setup",
61
+ "proof"
62
+ ],
63
+ "useWhen": "A grounded customer-service or personal back-and-forth is naturally associated with WhatsApp.",
64
+ "textCanvas": "tight",
65
+ "minDuration": 5,
66
+ "preferredDuration": 8,
67
+ "schema": {
68
+ "type": "object",
69
+ "properties": {
70
+ "msg1": {
71
+ "type": "string",
72
+ "title": "Message 1 (received)",
73
+ "description": "First message — left/received by default. Append |in or |out to override side. Aim for 3-4 messages total; use 5 with date chips only for a real time gap in a 10s+ scene.",
74
+ "default": "Have you tried it yet?"
75
+ },
76
+ "msg2": {
77
+ "type": "string",
78
+ "title": "Message 2 (sent)",
79
+ "description": "Second message — right/sent by default via |out. Replace the suffix with |in only when the grounded exchange requires it.",
80
+ "default": "Yes — it saves me hours|out"
81
+ },
82
+ "msg3": {
83
+ "type": "string",
84
+ "title": "Message 3 (received)",
85
+ "description": "Third message — left/received by default. Leave blank for a two-message exchange.",
86
+ "default": "Okay, send me the link"
87
+ },
88
+ "msg4": {
89
+ "type": "string",
90
+ "title": "Message 4 (sent)",
91
+ "description": "Fourth message — right/sent by default. Optional; most chats end here.",
92
+ "examples": [
93
+ "Sounds great — sharing access now"
94
+ ],
95
+ "default": ""
96
+ },
97
+ "dateChip1": {
98
+ "type": "string",
99
+ "title": "Date chip 1",
100
+ "description": "Optional date label before message 4. Use only for a real time gap.",
101
+ "default": ""
102
+ },
103
+ "dateChip2": {
104
+ "type": "string",
105
+ "title": "Date chip 2",
106
+ "description": "Optional date label before message 5. Use only for a real time gap.",
107
+ "default": ""
108
+ },
109
+ "msg5": {
110
+ "type": "string",
111
+ "title": "Message 5 (sent)",
112
+ "description": "Optional fifth message — right/sent by default.",
113
+ "default": ""
114
+ },
115
+ "theme": {
116
+ "type": "string",
117
+ "title": "Conversation theme",
118
+ "enum": [
119
+ "messenger",
120
+ "whatsapp"
121
+ ],
122
+ "default": "whatsapp"
123
+ }
124
+ },
125
+ "required": [
126
+ "msg1",
127
+ "msg2",
128
+ "msg3"
129
+ ],
130
+ "additionalProperties": false
131
+ },
132
+ "label": "WhatsApp chat",
133
+ "description": "A staggered WhatsApp-style conversation with three to five message bubbles.",
134
+ "family": "Social & messaging",
135
+ "avoidWhen": "The source is not conversational, fewer than three meaningful messages exist, or pacing must be brief.",
136
+ "usesGlobalTextEffect": false,
137
+ "usesGlobalTransition": false,
138
+ "usesGlobalBackgroundEffect": false,
139
+ "timing": {
140
+ "contentFields": [
141
+ "msg1",
142
+ "msg2",
143
+ "msg3",
144
+ "msg4",
145
+ "msg5"
146
+ ],
147
+ "contentUnit": "words"
148
+ }
149
+ }
150
+ }
151
+ }
@@ -0,0 +1,184 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
+ "name": "codeEditor",
4
+ "type": "registry:block",
5
+ "title": "Code editor",
6
+ "description": "A syntax-styled editor window reveals a short code sample beneath a headline.",
7
+ "dependencies": [
8
+ "react"
9
+ ],
10
+ "registryDependencies": [
11
+ "@vanillasky/backgrounds",
12
+ "@vanillasky/motion",
13
+ "@vanillasky/theme",
14
+ "@vanillasky/typography",
15
+ "@vanillasky/template-context"
16
+ ],
17
+ "files": [
18
+ {
19
+ "path": "src/visual-system/scene-templates/showcase-code.tsx",
20
+ "type": "registry:component",
21
+ "target": "vanillasky/scene-templates/showcase-code.tsx",
22
+ "content": "/**\n * showcase-code — code editor window with syntax-highlighted snippet.\n *\n * macOS-style editor frame with traffic-light dots and filename in\n * the title bar. Code lines appear with staggered fade-in. Simple\n * syntax coloring for keywords, strings, comments, and numbers.\n * Same frame style as showcase-terminal.\n *\n * The editor frame itself lives in the CodeEditor primitive\n * (src/visual-system/primitives/devices/CodeEditor.tsx) — shared with custom\n * scenes. It owns shrink-to-fit + ellipsis for long lines so code never\n * clips mid-token at the frame edge.\n */\n\nimport React from \"react\";\nimport type { SceneTemplateProps } from \"./types\";\nimport { resolveTokens } from \"../theme\";\nimport { TemplateText } from \"./template-text\";\nimport { CodeEditor } from \"../primitives/devices/CodeEditor\";\nimport { SceneBackground, getMediaBackgroundProps } from \"./scene-background\";\n\nexport const ShowcaseCodeTemplate: React.FC<SceneTemplateProps> = ({\n variables,\n style,\n progress,\n motionProgress = progress,\n beatIntensity,\n width,\n height,\n safeZone,\n sceneDuration,\n backgroundEffect,\n isPlaying = true,\n}) => {\n const { primary, foreground, font } = resolveTokens(style);\n const textColor = foreground;\n const textsRaw = String(variables.texts || \"\");\n\n return (\n <div\n style={{\n width,\n height,\n backgroundColor: \"#000\",\n position: \"relative\",\n overflow: \"hidden\",\n fontFamily: font,\n }}\n >\n {/* [slot: background] */}\n <SceneBackground\n style={style}\n progress={progress}\n sceneDuration={sceneDuration}\n width={width}\n height={height}\n {...getMediaBackgroundProps(variables)}\n backgroundEffect={backgroundEffect}\n seed={textsRaw}\n isPlaying={isPlaying}\n beatIntensity={beatIntensity}\n />\n\n {/* [slot: caption] */}\n <TemplateText\n motionProgress={motionProgress}\n typeTreatment={resolveTokens(style).preset.type}\n archetype=\"subtle\"\n text={String(variables.texts ?? \"\")}\n progress={progress}\n sceneDuration={sceneDuration ?? 3}\n width={width}\n height={height}\n position=\"top\"\n sizeRole=\"headline\"\n safeZone={safeZone}\n font={font}\n color={textColor}\n beatIntensity={beatIntensity}\n />\n\n {/* [slot: hero] */}\n <CodeEditor\n progress={progress}\n code={String(variables.code || \"\")}\n filename={String(variables.filename || \"app.ts\")}\n width={width}\n height={height}\n accent={primary}\n beatIntensity={beatIntensity}\n />\n </div>\n );\n};\n"
23
+ },
24
+ {
25
+ "path": "src/visual-system/scene-templates/scene-background.tsx",
26
+ "type": "registry:component",
27
+ "target": "vanillasky/scene-templates/scene-background.tsx",
28
+ "content": "/**\n * SceneBackground — shared backdrop component for any scene template that\n * wants to support both a brand-color gradient and stock media (Pexels\n * photo / video) as an alternate atmosphere.\n *\n * Usage:\n * <SceneBackground\n * style={style}\n * progress={progress}\n * sceneDuration={sceneDuration}\n * width={width}\n * height={height}\n * mediaUrl={String(variables.mediaUrl || \"\")}\n * mediaType={String(variables.mediaType || \"auto\")}\n * seed={String(variables.texts || \"\")}\n * isPlaying={isPlaying}\n * />\n * ... template's content layered on top\n *\n * Behavior:\n * - Brand gradient is the always-on backdrop (uses BrandGradientOverlay).\n * - When mediaUrl is set and mediaType isn't \"gradient\", the photo/video\n * covers the gradient. Vignette + bottom-half darken give the content\n * contrast against busy footage.\n * - mediaType=\"gradient\" deliberately ignores mediaUrl and renders only\n * the brand gradient. First-class atmospheric mode.\n * - When mediaUrl is empty / 404s / Pexels search returned nothing,\n * gradient shows through cleanly (matches every other gradient-backed\n * template).\n *\n * Extracted from bg-media.tsx so any template can compose it. bg-media\n * now uses this component too — its \"media is the scene\" identity comes\n * from how it positions the title (centered, full-frame), not from\n * duplicated render logic.\n */\n\nimport React, { useEffect, useRef } from \"react\";\nimport type { TemplateStyle } from \"../template-context\";\nimport { BrandGradientOverlay } from \"../backgrounds\";\nimport { getBackgroundTransform } from \"../backgrounds\";\n\nconst VIDEO_EXTENSIONS = [\".mp4\", \".webm\", \".mov\", \".m4v\", \".avi\"];\n\nfunction isVideoUrl(url: string): boolean {\n try {\n const pathname = new URL(url).pathname.toLowerCase();\n return VIDEO_EXTENSIONS.some((ext) => pathname.endsWith(ext));\n } catch {\n const lower = url.toLowerCase();\n return VIDEO_EXTENSIONS.some((ext) => lower.endsWith(ext));\n }\n}\n\nexport type ResolvedMediaType = \"photo\" | \"video\" | \"gradient\";\n\nexport type MediaPosition = \"center\" | \"top\" | \"bottom\" | \"left\" | \"right\";\nexport type MediaTreatment = \"subtle\" | \"cinematic\" | \"text-safe\";\n\nconst MEDIA_POSITIONS: Record<MediaPosition, string> = {\n center: \"center center\",\n top: \"center top\",\n bottom: \"center bottom\",\n left: \"left center\",\n right: \"right center\",\n};\n\nexport function resolveMediaPosition(value: string): string {\n return MEDIA_POSITIONS[value as MediaPosition] ?? MEDIA_POSITIONS.center;\n}\n\nexport function resolveMediaTreatment(value: string): MediaTreatment {\n return value === \"subtle\" || value === \"text-safe\" ? value : \"cinematic\";\n}\n\nexport interface MediaTreatmentLayer {\n id: \"vignette\" | \"full-wash\" | \"center-scrim\" | \"bottom-scrim\";\n background: string;\n style?: React.CSSProperties;\n}\n\n/** Export-safe contrast recipes. Overlays only: SVG capture cannot rely on CSS filters. */\nexport function getMediaTreatmentLayers(value: string): MediaTreatmentLayer[] {\n const treatment = resolveMediaTreatment(value);\n const vignette: MediaTreatmentLayer = {\n id: \"vignette\",\n background:\n treatment === \"subtle\"\n ? \"radial-gradient(ellipse at center, transparent 45%, rgba(0,0,0,0.28) 100%)\"\n : \"radial-gradient(ellipse at center, transparent 30%, rgba(0,0,0,0.55) 80%, rgba(0,0,0,0.75) 100%)\",\n };\n if (treatment === \"subtle\") return [vignette];\n\n const cinematic: MediaTreatmentLayer[] = [\n vignette,\n {\n id: \"center-scrim\",\n background:\n treatment === \"text-safe\"\n ? \"radial-gradient(ellipse 90% 56% at 50% 50%, rgba(0,0,0,0.36) 0%, rgba(0,0,0,0.18) 55%, transparent 84%)\"\n : \"radial-gradient(ellipse 85% 50% at 50% 50%, rgba(0,0,0,0.22) 0%, rgba(0,0,0,0.10) 50%, transparent 80%)\",\n },\n {\n id: \"bottom-scrim\",\n background:\n treatment === \"text-safe\"\n ? \"linear-gradient(to top, rgba(0,0,0,0.68) 0%, transparent 100%)\"\n : \"linear-gradient(to top, rgba(0,0,0,0.5) 0%, transparent 100%)\",\n style: { top: \"55%\" },\n },\n ];\n\n if (treatment === \"text-safe\") {\n cinematic.splice(1, 0, {\n id: \"full-wash\",\n background: \"rgba(0,0,0,0.30)\",\n });\n }\n return cinematic;\n}\n\nexport function resolveMediaType(\n mediaType: string,\n mediaUrl: string,\n): ResolvedMediaType {\n if (mediaType === \"gradient\") return \"gradient\";\n if (mediaType === \"video\") return \"video\";\n if (mediaType === \"photo\") return \"photo\";\n // \"auto\" — detect from URL extension\n return mediaUrl && isVideoUrl(mediaUrl) ? \"video\" : \"photo\";\n}\n\nexport function getMediaBackgroundProps(variables: Record<string, unknown>) {\n return {\n mediaUrl: String(variables.mediaUrl || \"\"),\n mediaType: String(variables.mediaType || \"auto\"),\n mediaPoster: String(variables.mediaPoster || \"\"),\n mediaPosition: String(variables.mediaPosition || \"center\"),\n mediaTreatment: String(variables.mediaTreatment || \"cinematic\"),\n };\n}\n\nexport interface SceneBackgroundProps {\n style: TemplateStyle;\n progress: number;\n sceneDuration?: number;\n width: number;\n height: number;\n mediaUrl?: string;\n mediaType?: string;\n /** Still image URL shown while the <video> backdrop decodes its first\n * frame. Without it the element renders transparent during the\n * ~50–400ms decode window and the gradient flashes through. */\n mediaPoster?: string;\n /** Cover-crop focal anchor. Keeps the important edge/subject visible. */\n mediaPosition?: string;\n /** Overlay recipe: subtle, cinematic, or stronger text-safe contrast. */\n mediaTreatment?: string;\n /** Background motion effect (drift / pulse / Ken Burns). Applied to the photo/video. */\n backgroundEffect?: string;\n /** Stable seed for the gradient breathing animation. Pass the scene's\n * text content (or any stable string) — it's hashed deterministically. */\n seed?: number | string;\n /** Pause video when preview is paused. Defaults to true (export path). */\n isPlaying?: boolean;\n beatIntensity?: number;\n}\n\nexport const SceneBackground: React.FC<SceneBackgroundProps> = ({\n style,\n progress,\n sceneDuration,\n width: _width, // accepted for symmetry; not currently used in render\n height: _height,\n mediaUrl = \"\",\n mediaType = \"auto\",\n mediaPoster,\n mediaPosition = \"center\",\n mediaTreatment = \"cinematic\",\n backgroundEffect,\n seed,\n isPlaying = true,\n beatIntensity = 0,\n}) => {\n void _width;\n void _height;\n const resolved = resolveMediaType(mediaType, mediaUrl);\n const showMedia = resolved !== \"gradient\" && !!mediaUrl;\n const resolvedPosition = resolveMediaPosition(mediaPosition);\n const resolvedTreatment = resolveMediaTreatment(mediaTreatment);\n const treatmentLayers = getMediaTreatmentLayers(resolvedTreatment);\n\n const gradSeed =\n typeof seed === \"number\"\n ? seed\n : typeof seed === \"string\"\n ? seed.split(\"\").reduce((acc, c) => acc + c.charCodeAt(0), 0)\n : 0;\n\n const bgTransform = getBackgroundTransform(\n backgroundEffect,\n progress,\n beatIntensity,\n );\n\n // Video playback control — same pause/seek logic bg-media used pre-extract.\n const videoRef = useRef<HTMLVideoElement>(null);\n const lastProgress = useRef(progress);\n const videoStarted = useRef(false);\n\n useEffect(() => {\n const vid = videoRef.current;\n if (!vid) return;\n if (!isPlaying) {\n vid.pause();\n videoStarted.current = false;\n return;\n }\n const progressChanged = Math.abs(progress - lastProgress.current) > 0.001;\n lastProgress.current = progress;\n if (progressChanged && !videoStarted.current) {\n vid.playbackRate = 1;\n vid.currentTime = 0;\n vid.play().catch(() => {});\n videoStarted.current = true;\n } else if (!progressChanged && videoStarted.current) {\n vid.pause();\n videoStarted.current = false;\n }\n }, [progress, isPlaying]);\n\n // Release the decoder on unmount. Without this, iOS Safari keeps the\n // video's decoder buffer alive after the React node is gone — each\n // scene transition (or play/pause/play cycle that remounts the active\n // scene) leaks one decoder, eventually crossing the renderer's memory\n // ceiling and triggering \"A problem repeatedly occurred.\" Same recipe\n // as #409's CanvasPreview preload cleanup: pause → clear src → load().\n // Capture the ref at mount-time so the cleanup uses the same node we\n // mounted (the ref's .current is stale by unmount).\n useEffect(() => {\n const vid = videoRef.current;\n return () => {\n if (!vid) return;\n vid.pause();\n vid.removeAttribute(\"src\");\n vid.load();\n };\n }, []);\n\n return (\n <>\n <BrandGradientOverlay\n style={style}\n progress={progress}\n sceneDuration={sceneDuration}\n seed={gradSeed}\n />\n\n {showMedia &&\n (resolved === \"video\" ? (\n <video\n ref={videoRef}\n src={mediaUrl}\n // Poster paints during the decode window so the user sees the\n // (still) first frame instead of a transparent <video> letting\n // the brand gradient show through. Pexels returns a thumbnail\n // image alongside each video; fillPexelsUrls stores it in\n // `variables.mediaPoster`. Layered defense alongside preload=\"auto\"\n // below: on desktop the byte preloader makes decode fast, on\n // mobile (where the preloader skips video pre-mounting to dodge\n // the iOS Safari memory crash) the poster is the primary shield.\n poster={mediaPoster || undefined}\n muted\n loop\n playsInline\n // preload=\"auto\" — without it, browsers default to \"metadata\":\n // they only load the container/dimensions, not the byte stream\n // needed to decode frames. The element then renders transparent\n // until the first decoded frame arrives, letting the brand\n // gradient flash through whenever a scene mid-playback transitions\n // to a media backdrop. The parent preloader caches the bytes, but\n // decoder state is per-element, so the active mount still has to\n // decode the first frame; \"auto\" kicks that work off the instant\n // the element mounts.\n preload=\"auto\"\n data-media-position={mediaPosition}\n style={{\n position: \"absolute\",\n inset: 0,\n width: \"100%\",\n height: \"100%\",\n objectFit: \"cover\",\n objectPosition: resolvedPosition,\n transform: bgTransform.transform,\n transformOrigin: bgTransform.transformOrigin,\n }}\n />\n ) : (\n <div\n data-media-position={mediaPosition}\n style={{\n position: \"absolute\",\n inset: 0,\n transform: bgTransform.transform,\n transformOrigin: bgTransform.transformOrigin,\n backgroundImage: `url(${mediaUrl})`,\n backgroundSize: \"cover\",\n backgroundPosition: resolvedPosition,\n }}\n />\n ))}\n\n {showMedia &&\n treatmentLayers.map((layer) => (\n <div\n key={layer.id}\n data-media-treatment={resolvedTreatment}\n data-media-overlay={layer.id}\n style={{\n position: \"absolute\",\n inset: 0,\n background: layer.background,\n pointerEvents: \"none\",\n ...layer.style,\n }}\n />\n ))}\n </>\n );\n};\n"
29
+ },
30
+ {
31
+ "path": "src/visual-system/primitives/devices/CodeEditor.tsx",
32
+ "type": "registry:component",
33
+ "target": "vanillasky/primitives/devices/CodeEditor.tsx",
34
+ "content": "/**\n * CodeEditor\n *\n * macOS-style code editor window with traffic-light dots, filename in\n * the title bar, and a syntax-highlighted snippet that fades in line by\n * line. Simple syntax coloring (keywords, strings, comments, numbers) —\n * good enough for a 6-10s video.\n *\n * showcase-code.tsx is the source; this primitive lifts the focal\n * editor frame so custom scenes can compose code reveals cleanly.\n *\n * Prop API:\n * - progress : scene progress 0→1 (required)\n * - code : raw code string; supports literal \"\\n\" sequences (required)\n * - filename : title-bar filename, e.g. \"app.ts\" (default \"app.ts\")\n * - width : frame width (required)\n * - height : frame height (required)\n * - accent : reserved brand accent — not currently used inside the\n * editor (syntax palette is fixed Catppuccin-style);\n * kept for API parity with sibling device primitives\n * - beatIntensity: beat pulse 0→1 (default 0)\n */\n\nimport * as React from \"react\";\nimport { interpolate, spring, type SpringConfig } from \"../../motion\";\nimport { stripPipe, fitTextSize } from \"../../typography\";\n\nconst SPRING_EDITOR: SpringConfig = { damping: 20, stiffness: 100 };\nconst CLAMP = { extrapolateLeft: \"clamp\" as const, extrapolateRight: \"clamp\" as const };\n\n// Monospace advance width ≈ 0.60em (Menlo/SF Mono/Fira Code) + ~5% slack for\n// the SVG export path, which shapes text slightly wider than the iframe.\nconst MONO_CHAR_RATIO = 0.63;\n// Shrink-to-fit floor — below this we ellipsize instead of shrinking further.\nconst MONO_MIN_SCALE = 0.68;\n// Fira Code first: index.html loads it deliberately for code/terminal\n// templates; OS monospace fallbacks keep export close to preview.\nconst MONO_FONT = \"'Fira Code', 'SF Mono', 'Cascadia Code', Menlo, monospace\";\nconst CHROME_FONT = \"'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif\";\n\n// ── Simple syntax highlighting (inlined verbatim from showcase-code.tsx) ──\n\ninterface CodeToken {\n text: string;\n color: string;\n}\n\nconst KEYWORDS = new Set([\n \"const\", \"let\", \"var\", \"function\", \"return\", \"import\", \"export\",\n \"from\", \"async\", \"await\", \"if\", \"else\", \"for\", \"while\", \"class\",\n \"new\", \"this\", \"true\", \"false\", \"null\", \"undefined\", \"def\", \"self\",\n \"print\", \"in\", \"not\", \"and\", \"or\", \"try\", \"catch\", \"throw\",\n]);\n\nfunction tokenizeLine(\n line: string,\n keywordColor: string,\n stringColor: string,\n commentColor: string,\n numberColor: string,\n defaultColor: string,\n): CodeToken[] {\n const tokens: CodeToken[] = [];\n\n // Comment check (// or #)\n const commentMatch = line.match(/^(.*?)(\\/\\/.*|#.*)$/);\n if (commentMatch) {\n tokens.push(...tokenizeCode(commentMatch[1], keywordColor, stringColor, numberColor, defaultColor));\n tokens.push({ text: commentMatch[2], color: commentColor });\n return tokens;\n }\n\n return tokenizeCode(line, keywordColor, stringColor, numberColor, defaultColor);\n}\n\nfunction tokenizeCode(\n code: string,\n keywordColor: string,\n stringColor: string,\n numberColor: string,\n defaultColor: string,\n): CodeToken[] {\n const tokens: CodeToken[] = [];\n // Match strings, numbers, words, or other characters\n const regex = /(\"[^\"]*\"|'[^']*'|`[^`]*`|\\b\\d+\\.?\\d*\\b|\\b\\w+\\b|[^\\s]|\\s+)/g;\n let match: RegExpExecArray | null;\n\n while ((match = regex.exec(code)) !== null) {\n const t = match[0];\n if ((t.startsWith('\"') || t.startsWith(\"'\") || t.startsWith(\"`\"))) {\n tokens.push({ text: t, color: stringColor });\n } else if (/^\\d+\\.?\\d*$/.test(t)) {\n tokens.push({ text: t, color: numberColor });\n } else if (KEYWORDS.has(t)) {\n tokens.push({ text: t, color: keywordColor });\n } else {\n tokens.push({ text: t, color: defaultColor });\n }\n }\n\n return tokens;\n}\n\n// ─── Typed component ────────────────────────────────────────────\n\nexport interface CodeEditorProps {\n /** Scene progress 0→1 */\n progress: number;\n /** Code snippet — literal \"\\n\" sequences are expanded to real newlines */\n code: string;\n /** Filename shown in the title bar (default \"app.ts\") */\n filename?: string;\n /** Frame width */\n width: number;\n /** Frame height */\n height: number;\n /** Reserved brand accent (not used in the syntax palette today). Defaults to \"#00e5a0\". */\n accent?: string;\n /** Beat pulse 0→1 */\n beatIntensity?: number;\n}\n\nexport const CodeEditor: React.FC<CodeEditorProps> = ({\n progress,\n code,\n filename = \"app.ts\",\n width,\n height,\n\n beatIntensity = 0,\n}) => {\n const s = Math.min(width, height) / 1080;\n\n // NOTE: no stripPipe on the code itself — code legitimately contains `|`\n // (logical OR, shell pipes); truncating at the first pipe corrupted\n // snippets. Filename keeps the shared pipe-segment guard.\n const codeRaw = String(code || \"\").replace(/\\\\n/g, \"\\n\");\n const filenameClean = stripPipe(String(filename || \"app.ts\"));\n const codeLines = codeRaw.split(\"\\n\");\n\n // ── Editor dimensions — fit in both orientations ──────────────\n const editorWidth = Math.min(width * 0.88, height * 0.55 * (16 / 9));\n const chromeHeight = 44 * s;\n const contentHeight = editorWidth * (9 / 16);\n const editorHeight = chromeHeight + contentHeight;\n const borderRadius = 12 * s;\n\n // ── Editor colors (Catppuccin-inspired) ───────────────────────\n const editorBg = \"#1e1e2e\";\n const chromeBg = \"#313244\";\n const codeDefault = \"#cdd6f4\";\n const keywordColor = \"#cba6f7\"; // purple\n const stringColor = \"#a6e3a1\"; // green\n const commentColor = \"#6c7086\"; // gray\n const numberColor = \"#fab387\"; // peach\n const lineNumColor = \"#45475a\"; // dim\n\n // ── Font sizes — shrink-to-fit long lines, then ellipsize ─────\n // Long AI-generated lines used to clip mid-token at the frame edge.\n // fitTextSize shrinks the whole block so the longest line fits; if even\n // the floor size can't hold a line, that line is ellipsized explicitly.\n const lineNumWidth = 40 * s;\n const codeAvailWidth = editorWidth - lineNumWidth - 16 * s;\n const baseFontSize = Math.max(16, 22 * s);\n const longestLineChars = codeLines.reduce((m, l) => Math.max(m, l.length), 1);\n const fontSize = fitTextSize(\"M\".repeat(longestLineChars), baseFontSize, codeAvailWidth, {\n minScale: MONO_MIN_SCALE,\n charWidthRatio: MONO_CHAR_RATIO,\n });\n // Not at the floor → fitTextSize guarantees every line fits; skip ellipsis\n // so exact-fit lines aren't truncated by float rounding.\n const atFloor = fontSize <= baseFontSize * MONO_MIN_SCALE + 0.01;\n const maxLineChars = atFloor\n ? Math.max(4, Math.floor(codeAvailWidth / (fontSize * MONO_CHAR_RATIO)))\n : Infinity;\n const displayLines = codeLines.map((l) =>\n l.length > maxLineChars ? `${l.slice(0, maxLineChars - 1).trimEnd()}…` : l,\n );\n const lineHeight = fontSize * 1.7;\n\n // ── Slide-up animation ────────────────────────────────────────\n const slideProgress = interpolate(progress, [0.02, 0.15], [0, 1], CLAMP);\n const springVal = spring(slideProgress, SPRING_EDITOR);\n const editorY = (1 - springVal) * 200 * s;\n const editorOpacity = interpolate(slideProgress, [0, 0.08], [0, 1], CLAMP);\n\n // ── Code line stagger (15%–80%) ───────────────────────────────\n const lineStaggerStart = 0.15;\n const lineStaggerEnd = 0.80;\n const lineSlice = codeLines.length > 0\n ? (lineStaggerEnd - lineStaggerStart) / codeLines.length\n : 0;\n\n const beatScale = 1 + beatIntensity * 0.01;\n\n // ── Traffic light dot sizes ───────────────────────────────────\n const dotSize = 12 * s;\n const dotGap = 8 * s;\n\n return (\n <div\n style={{\n position: \"absolute\",\n top: height * 0.35,\n left: (width - editorWidth) / 2,\n width: editorWidth,\n height: editorHeight,\n transform: `translateY(${editorY}px) scale(${beatScale})`,\n opacity: editorOpacity,\n }}\n >\n <div\n style={{\n width: editorWidth,\n height: editorHeight,\n borderRadius,\n overflow: \"hidden\",\n position: \"relative\",\n boxShadow: `0 ${20 * s}px ${60 * s}px rgba(0,0,0,0.35)`,\n }}\n >\n {/* Chrome bar */}\n <div\n style={{\n width: \"100%\",\n height: chromeHeight,\n backgroundColor: chromeBg,\n display: \"flex\",\n alignItems: \"center\",\n paddingLeft: 16 * s,\n paddingRight: 16 * s,\n }}\n >\n {/* Traffic light dots */}\n <div style={{ display: \"flex\", gap: dotGap, flexShrink: 0 }}>\n <div style={{ width: dotSize, height: dotSize, borderRadius: \"50%\", backgroundColor: \"#ff5f57\" }} />\n <div style={{ width: dotSize, height: dotSize, borderRadius: \"50%\", backgroundColor: \"#febc2e\" }} />\n <div style={{ width: dotSize, height: dotSize, borderRadius: \"50%\", backgroundColor: \"#28c840\" }} />\n </div>\n\n {/* Filename */}\n <div\n style={{\n flex: 1,\n textAlign: \"center\",\n fontSize: 13 * s,\n fontFamily: CHROME_FONT,\n color: \"#a6adc8\",\n whiteSpace: \"nowrap\",\n }}\n >\n {filenameClean}\n </div>\n\n {/* Spacer to balance dots */}\n <div style={{ width: dotSize * 3 + dotGap * 2, flexShrink: 0 }} />\n </div>\n\n {/* Code content */}\n <div\n style={{\n width: \"100%\",\n height: contentHeight,\n backgroundColor: editorBg,\n padding: `${16 * s}px 0`,\n overflow: \"hidden\",\n }}\n >\n {displayLines.map((line, i) => {\n const lineStart = lineStaggerStart + i * lineSlice;\n const lineOpacity = interpolate(progress, [lineStart, lineStart + 0.04], [0, 1], CLAMP);\n const lineSlideX = interpolate(progress, [lineStart, lineStart + 0.06], [12 * s, 0], CLAMP);\n\n const tokens = line.trim() === \"\"\n ? [{ text: \" \", color: codeDefault }]\n : tokenizeLine(line, keywordColor, stringColor, commentColor, numberColor, codeDefault);\n\n return (\n <div\n key={i}\n style={{\n display: \"flex\",\n alignItems: \"baseline\",\n height: lineHeight,\n opacity: lineOpacity,\n transform: `translateX(${lineSlideX}px)`,\n }}\n >\n {/* Line number */}\n <div\n style={{\n width: lineNumWidth,\n textAlign: \"right\",\n paddingRight: 12 * s,\n fontSize,\n fontFamily: MONO_FONT,\n color: lineNumColor,\n lineHeight: `${lineHeight}px`,\n flexShrink: 0,\n userSelect: \"none\",\n }}\n >\n {i + 1}\n </div>\n\n {/* Code tokens */}\n <div\n style={{\n fontSize,\n fontFamily: MONO_FONT,\n lineHeight: `${lineHeight}px`,\n whiteSpace: \"pre\",\n }}\n >\n {tokens.map((token, j) => (\n <span key={j} style={{ color: token.color }}>\n {token.text}\n </span>\n ))}\n </div>\n </div>\n );\n })}\n </div>\n </div>\n </div>\n );\n};\n"
35
+ },
36
+ {
37
+ "path": "src/visual-system/scene-templates/template-text.tsx",
38
+ "type": "registry:component",
39
+ "target": "vanillasky/scene-templates/template-text.tsx",
40
+ "content": "/**\n * TemplateText — unified text component for scene templates.\n *\n * Replaces the per-template hand-rolled text rendering with a single component\n * that owns: archetype motion lifecycle (entrance + hold + exit), font sizing,\n * position, beat pulse, and safe zone.\n *\n * Each template declares its constraints (position + sizeRole) at the call site;\n * the user/AI picks the archetype. Templates that can only show text at the top\n * just always pass position=\"top\".\n *\n * Example — a data template (caption above a chart):\n *\n * <TemplateText\n * archetype={textArchetype}\n * text={variables.title}\n * progress={progress}\n * sceneDuration={sceneDuration}\n * width={width}\n * height={height}\n * position=\"top\"\n * sizeRole=\"caption\"\n * />\n *\n * Example — a media template (full-frame headline):\n *\n * <TemplateText\n * archetype={textArchetype}\n * text={variables.headline}\n * progress={progress}\n * sceneDuration={sceneDuration}\n * width={width}\n * height={height}\n * position=\"center\"\n * sizeRole=\"headline\"\n * beatIntensity={beatIntensity}\n * />\n *\n * Note: `textArchetype` is destructured from props (a scene-level\n * field on `SceneTemplateProps`), NOT read from `variables`. Copying\n * the wrong pattern silently no-ops — the executor routes\n * `setSceneVariable(\"textArchetype\", ...)` to the scene-level field,\n * never into variables, so `variables.textArchetype` is always\n * undefined.\n */\n\nimport {\n renderArchetype,\n normalizeArchetype,\n type TextArchetype,\n type ArchetypeRender,\n} from \"../typography\";\nimport type { TypeTreatment } from \"../theme\";\nimport { renderWithEmoji, planTypewriterEmoji } from \"../emoji/emoji-text\";\nimport { Emoji } from \"../emoji\";\n\nexport type TextPosition = \"top\" | \"center\" | \"bottom\";\nexport type TextSizeRole = \"headline\" | \"caption\" | \"label\";\n\nexport interface SafeZone {\n top: number;\n right: number;\n bottom: number;\n left: number;\n}\n\nexport interface TemplateTextProps {\n archetype: TextArchetype;\n text: string;\n /** Scene progress 0→1. */\n progress: number;\n /** Presentation clock; VideoFrame keeps it on the complete scene timeline. */\n motionProgress?: number;\n /** Scene duration in seconds — drives entrance/exit phase scaling. */\n sceneDuration: number;\n /** Frame width in pixels (1080 in production, smaller in previews). */\n width: number;\n /** Frame height in pixels (1920 in production). */\n height: number;\n /** Where the text box sits in the frame. Templates declare this. */\n position?: TextPosition;\n /** Size envelope. Templates declare this. */\n sizeRole?: TextSizeRole;\n /** Preset type treatment — weight/tracking/size/case shift from style.preset. */\n typeTreatment?: TypeTreatment;\n /** Padding from frame edges. Defaults to a 24px box. */\n safeZone?: SafeZone;\n /** Font family. */\n font?: string;\n /** Fill color. */\n color?: string;\n /** Beat intensity 0→1 (currently unused — kept for forward compat). */\n beatIntensity?: number;\n}\n\nconst DEFAULT_SAFE_ZONE: SafeZone = { top: 24, right: 24, bottom: 24, left: 24 };\nconst DEFAULT_FONT =\n \"ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif\";\n\n// ─── Typography constants ───────────────────────────────────────\n// All em-based so they scale with font size and behave consistently across\n// font families. Values from print/motion-design conventions:\n//\n// - Big text (display/headline) gets TIGHTER tracking and TIGHTER leading.\n// -0.022em (≈ -2.2%) is the sweet spot for 48–88px headlines on most\n// sans-serifs (Inter, Helvetica, SF Pro, Manrope, Geist).\n// - Word-spacing kept subtle (≤0.08em). CSS word-spacing is ADDITIVE on\n// top of the natural space char, so what looks like \"a touch of\n// rhythm\" in print becomes a visible double-gap on 80px motion\n// headlines (especially under wordStagger, where each word renders\n// as an inline-block and the gap between them is preserved). Old\n// values (0.16/0.18/0.22 em) added ~13–18px per gap on display\n// type — the \"too much space between words\" symptom.\n// - Line-height 1.1 for headlines, 1.5 for body — Bringhurst-aligned ratios.\n// - kern + liga always on so any font's pair-kerning and ligatures fire\n// consistently (works across Inter, Manrope, SF, IBM Plex, etc.).\nconst TYPO = {\n headline: {\n letterSpacing: \"-0.022em\",\n wordSpacing: \"0.04em\",\n lineHeight: 1.1,\n },\n caption: {\n letterSpacing: \"-0.012em\",\n wordSpacing: \"0.06em\",\n lineHeight: 1.25,\n },\n label: {\n letterSpacing: \"-0.005em\",\n wordSpacing: \"0.10em\",\n lineHeight: 1.4,\n },\n};\nconst FONT_FEATURES = '\"kern\" 1, \"liga\" 1';\n\n// Drop shadow tuned to give crisp edges on retina without muddying text on\n// saturated gradients. Earlier two-layer shadow (1px tight + 16px wide) cast\n// dark halos that made gradient-backed text look smudged. A single barely-\n// there shadow is enough for edge definition; bg-media adds its own dark\n// scrim for legibility over photos, so we don't need to compensate here.\nfunction dropShadowFor(textColor: string): string {\n const dark = isLikelyDark(textColor);\n const tone = dark ? \"rgba(255,255,255,0.15)\" : \"rgba(0,0,0,0.2)\";\n return `0 1px 2px ${tone}`;\n}\n\nfunction isLikelyDark(color: string): boolean {\n // Crude luminance check — handles #rrggbb and #rgb. Anything we can't parse\n // (named colors, rgb()) defaults to \"not dark\" so the heavier shadow shows.\n const m = color.replace(\"#\", \"\");\n if (m.length === 3) {\n const r = parseInt(m[0] + m[0], 16);\n const g = parseInt(m[1] + m[1], 16);\n const b = parseInt(m[2] + m[2], 16);\n return (r * 299 + g * 587 + b * 114) / 1000 < 128;\n }\n if (m.length === 6) {\n const r = parseInt(m.slice(0, 2), 16);\n const g = parseInt(m.slice(2, 4), 16);\n const b = parseInt(m.slice(4, 6), 16);\n return (r * 299 + g * 587 + b * 114) / 1000 < 128;\n }\n return false;\n}\n// ─── Font sizing matrix ─────────────────────────────────────────\n// Mirrors what production templates actually render today, ported from:\n// - text-overlay.tsx (headline: 80/64/48 × s_min by char count)\n// - infographic-steps.tsx (caption: ~44 × s_min capped by layout)\n\n/**\n * Compute heroWord font size for a single word. Each active word fills its\n * own moment — trailer convention. Center can go large (480ref cap); top\n * stays inside the top zone height so it doesn't crash into the animation\n * or data viz below.\n */\nfunction computeHeroFontSize(\n wordChars: number,\n position: TextPosition,\n width: number,\n height: number,\n safeZone: SafeZone,\n): number {\n const chars = Math.max(wordChars, 1);\n const s_min = Math.min(width, height) / 1080;\n const widthBudget = (width - safeZone.left - safeZone.right) * 0.92;\n const pxPerChar = 0.58; // bold sans-serif approximation\n const widthCap = widthBudget / (chars * pxPerChar);\n\n if (position === \"center\") {\n return Math.min(480 * s_min, widthCap);\n }\n\n // Top/bottom: keep the word inside its zone (~28% of frame height) with\n // 80% headroom for entrance overshoot + breathe. Reference target 220ref\n // so even short words stay big without overflowing the zone.\n const heightCap = height * 0.28 * 0.8;\n return Math.min(220 * s_min, widthCap, heightCap);\n}\n\n/**\n * Smooth interpolation between max and min font size based on character count.\n * Avoids the visible \"jump\" you get from bucket boundaries when copy length\n * crosses a threshold (e.g., 25→26 chars dropping headline from 80px to 64px).\n *\n * Exported so templates that lay out their own text can match the headline\n * curve instead of inventing their own bucketed scaling.\n *\n * Returns size at 1080-reference scale; caller multiplies by s_min.\n */\nexport function smoothSize(chars: number, maxChars: number, max: number, min: number): number {\n const t = Math.max(0, Math.min(1, chars / maxChars));\n // Slight curve so short text stays at maxSize longer before scaling down.\n const eased = t * t;\n return max - (max - min) * eased;\n}\n\nfunction computeFontSize(\n archetype: TextArchetype,\n text: string,\n role: TextSizeRole,\n position: TextPosition,\n width: number,\n height: number,\n safeZone: SafeZone,\n): { fontSize: number; fontWeight: number } {\n const s_min = Math.min(width, height) / 1080;\n\n // heroWord container fontSize uses the longest word as a safe fallback. The\n // ACTIVE-word size is recomputed per-render in the \"hero\" render branch\n // (via computeHeroFontSize) so each word fills its own moment optimally —\n // trailer convention.\n if (archetype === \"heroWord\") {\n const longestChars = text\n .split(/\\s+/)\n .filter(Boolean)\n .reduce((m, w) => Math.max(m, w.length), 1);\n return {\n fontSize: computeHeroFontSize(longestChars, position, width, height, safeZone),\n fontWeight: 800,\n };\n }\n\n const chars = text.length;\n\n // Smooth scaling, minimums set so even long copy stays readable in production\n // (1080 reference). Numbers tuned to match — but improve on — the previous\n // bucketed system.\n if (role === \"headline\") {\n // Floor 60 (was 48) — matches the typography guideline \"Titles/headlines\n // 60-86px at 1080\" and lifts long-copy headlines off the body-text floor\n // that left ProblemSolution-shaped statements feeling small. Max held at\n // 88 so short, punchy headlines still fill the frame.\n const refSize = smoothSize(chars, /* maxChars */ 70, /* max */ 88, /* min */ 60);\n return { fontSize: refSize * s_min, fontWeight: 700 };\n }\n\n if (role === \"caption\") {\n const refSize = smoothSize(chars, 80, 48, 32);\n return { fontSize: refSize * s_min, fontWeight: 600 };\n }\n\n // label\n const refSize = smoothSize(chars, 80, 34, 24);\n return { fontSize: refSize * s_min, fontWeight: 500 };\n}\n\n// ─── Positioning ───────────────────────────────────────────────\n\nfunction positionStyle(\n position: TextPosition,\n height: number,\n safeZone: SafeZone,\n): React.CSSProperties {\n switch (position) {\n case \"top\":\n return {\n top: safeZone.top + height * 0.06,\n height: height * 0.28,\n alignItems: \"flex-start\",\n };\n case \"bottom\":\n return {\n bottom: safeZone.bottom + height * 0.06,\n height: height * 0.28,\n alignItems: \"flex-end\",\n };\n case \"center\":\n default:\n return {\n top: 0,\n bottom: 0,\n alignItems: \"center\",\n };\n }\n}\n\n// ─── Component ─────────────────────────────────────────────────\n\nexport const TemplateText: React.FC<TemplateTextProps> = ({\n archetype: archetypeRaw,\n text: textRaw,\n progress,\n motionProgress = progress,\n sceneDuration,\n width,\n height,\n position = \"center\",\n sizeRole = \"headline\",\n typeTreatment,\n safeZone = DEFAULT_SAFE_ZONE,\n font = DEFAULT_FONT,\n color = \"#FFFFFF\",\n beatIntensity = 0,\n}) => {\n // Defensive coerce: TemplateText is downstream of ~16 templates that pass\n // their own `variables.X` strings. If any one of them passes undefined\n // (missing variable on a freshly added scene, stale saved config, custom\n // template not setting a field), the unguarded `.split` / `.length` calls\n // below crash the entire preview. Treat undefined/non-string as\n // empty so a single bad scene doesn't take everything down. Warn in dev\n // so the upstream gap still surfaces.\n const textSafe = typeof textRaw === \"string\" ? textRaw : \"\";\n const isDevelopment = (import.meta as ImportMeta & { env?: { DEV?: boolean } }).env?.DEV;\n if (textRaw !== undefined && typeof textRaw !== \"string\" && isDevelopment) {\n console.warn(\"[TemplateText] received non-string text:\", textRaw);\n }\n // `|` is the AI's explicit line-break convention for headline copy\n // (\"Built for speed.|Designed for you.\"). Convert centrally so EVERY\n // template that renders text through TemplateText honors it — bg-media\n // used to convert locally while confetti/emojiBurst/etc. rendered the\n // pipe literally. Whitespace around the pipe is trimmed so spaced and\n // unspaced pipes produce identical output. The container's\n // `white-space: pre-line` renders the resulting `\\n` as a hard break.\n // Templates that legitimately render pipes (code, terminal commands)\n // don't flow through TemplateText, so they're unaffected.\n const text = textSafe.replace(/\\s*\\|\\s*/g, \"\\n\");\n // Normalize the archetype prop so unknown names fall back safely.\n const archetype = normalizeArchetype(archetypeRaw);\n const scale = Math.min(width, height) / 1080;\n // Motion pacing applies at every size role — a calm video should ease its\n // captions in too, not just its headlines. (The rest of the treatment is\n // headline-only; see `tt` below.)\n const result: ArchetypeRender = renderArchetype(\n archetype,\n progress,\n scale,\n text,\n sceneDuration,\n typeTreatment?.phaseScale ?? 1,\n motionProgress,\n );\n const { fontSize, fontWeight } = computeFontSize(\n archetype,\n text,\n sizeRole,\n position,\n width,\n height,\n safeZone,\n );\n\n // beatIntensity reserved for future use; currently a no-op on text body.\n void beatIntensity;\n\n const baseTypo = TYPO[sizeRole];\n // Preset type treatment. Absent (or the default preset's zero-deltas) leaves\n // every value exactly as it was, so unpresetted configs are unaffected.\n const tt = sizeRole === \"headline\" ? typeTreatment : undefined;\n // Only rewrite a value the preset actually changes — reformatting\n // letterSpacing with a zero delta would alter the emitted string (and every\n // stability snapshot) without changing the render.\n const typo = tt\n ? {\n ...baseTypo,\n ...(tt.trackingDeltaEm !== 0\n ? {\n letterSpacing: `${Number(\n (parseFloat(baseTypo.letterSpacing) + tt.trackingDeltaEm).toFixed(4),\n )}em`,\n }\n : {}),\n ...(tt.transform ? { textTransform: tt.transform } : {}),\n }\n : baseTypo;\n const presetWeight = tt ? Math.min(900, Math.max(100, fontWeight + tt.weightDelta)) : fontWeight;\n const presetSize = tt ? fontSize * tt.sizeScale : fontSize;\n const textShadow = dropShadowFor(color);\n\n const containerStyle: React.CSSProperties = {\n position: \"absolute\",\n left: 0,\n right: 0,\n display: \"flex\",\n justifyContent: \"center\",\n padding: `0 ${safeZone.right}px 0 ${safeZone.left}px`,\n color,\n fontFamily: font,\n fontWeight: presetWeight,\n fontSize: presetSize,\n textAlign: \"center\",\n pointerEvents: \"none\",\n fontFeatureSettings: FONT_FEATURES,\n textRendering: \"optimizeLegibility\",\n WebkitFontSmoothing: \"antialiased\",\n MozOsxFontSmoothing: \"grayscale\",\n // Respect explicit newlines — the centralized `|` → `\\n` conversion\n // above (and callers passing real newlines) rely on this. Multiple\n // spaces still collapse normally; only `\\n` and CRLF break.\n whiteSpace: \"pre-line\",\n ...(textShadow ? { textShadow } : {}),\n ...typo,\n ...positionStyle(position, height, safeZone),\n };\n\n if (result.kind === \"block\") {\n return (\n <div style={containerStyle}>\n <div\n style={{\n opacity: result.block.opacity,\n transform: `${result.block.transform}`,\n // Inherit letter-spacing from the container's typography defaults\n // unless the archetype explicitly overrides (e.g., for animated tracking).\n ...(result.block.letterSpacing ? { letterSpacing: result.block.letterSpacing } : {}),\n ...(result.block.willChange ? { willChange: result.block.willChange } : {}),\n maxWidth: \"85%\",\n }}\n >\n {renderWithEmoji(result.text, fontSize)}\n </div>\n </div>\n );\n }\n\n if (result.kind === \"typewriter\") {\n // Render every character as its own span so the FULL TEXT always sets the\n // layout — wrapping is decided by the complete string, not the typed\n // prefix. The cursor is overlaid with position:absolute from the last\n // typed char so it doesn't break the word it's inside.\n const chars = text.split(\"\");\n // Map cluster-start code-unit indices → full emoji graphemes so emoji use\n // the native font even in the per-char typewriter reveal. Indexing\n // stays on text.length (UTF-16 units) so result.visibleChars / charExits\n // line up exactly; continuation units of a cluster render nothing.\n const emojiPlan = planTypewriterEmoji(text);\n const cursorBar = {\n position: \"absolute\" as const,\n width: \"0.08em\",\n height: \"0.88em\",\n background: \"currentColor\",\n borderRadius: \"0.01em\",\n pointerEvents: \"none\" as const,\n };\n return (\n <div style={containerStyle}>\n <div\n style={{\n opacity: result.opacity,\n maxWidth: \"85%\",\n whiteSpace: \"pre-wrap\",\n position: \"relative\",\n }}\n >\n {chars.map((ch, i) => {\n const isTyped = i < result.visibleChars;\n const isLastTyped = i === result.visibleChars - 1;\n const anchorCursor = isLastTyped && result.cursor;\n const charExit = result.charExits?.[i];\n const baseOpacity = isTyped ? 1 : 0;\n const finalOpacity = baseOpacity * (charExit?.opacity ?? 1);\n // During exit the per-char span needs inline-block so translateX\n // takes effect; whiteSpace: pre keeps space chars from collapsing.\n const exitStyle = charExit\n ? {\n display: \"inline-block\" as const,\n transform: `translateX(${charExit.translateX}px)`,\n whiteSpace: \"pre\" as const,\n }\n : null;\n // Emoji handling: a cluster-start unit renders the full grapheme;\n // its continuation units render nothing.\n const emojiChar = emojiPlan?.starts.get(i);\n if (emojiPlan?.covered.has(i)) return null;\n return (\n <span\n key={i}\n style={{\n opacity: finalOpacity,\n position: anchorCursor ? \"relative\" : \"static\",\n ...(exitStyle ?? {}),\n }}\n >\n {emojiChar ? <Emoji char={emojiChar} size={fontSize} /> : ch}\n {anchorCursor && (\n <span\n aria-hidden\n style={{\n ...cursorBar,\n left: \"100%\",\n top: \"0.08em\",\n marginLeft: \"0.12em\",\n }}\n />\n )}\n </span>\n );\n })}\n {result.visibleChars === 0 && result.cursor && (\n <span\n aria-hidden\n style={{\n ...cursorBar,\n left: 0,\n top: \"0.08em\",\n }}\n />\n )}\n </div>\n </div>\n );\n }\n\n if (result.kind === \"words\") {\n // Render words inline-block with REAL space chars between them — word\n // spacing inherits from the container's typography defaults, matching\n // every other archetype's wrap behavior.\n return (\n <div style={containerStyle}>\n <div\n style={{\n opacity: result.blockOpacity,\n transform: `${result.blockTransform} `,\n maxWidth: \"85%\",\n }}\n >\n {result.words.map((w, i) => (\n <span key={i}>\n <span\n style={{\n display: \"inline-block\",\n opacity: w.style.opacity,\n transform: w.style.transform,\n }}\n >\n {renderWithEmoji(w.text, fontSize)}\n </span>\n {i < result.words.length - 1 ? \" \" : \"\"}\n </span>\n ))}\n </div>\n </div>\n );\n }\n\n if (result.kind === \"hero\") {\n // Per-word sizing: each active word fills its own moment optimally.\n const perWordFontSize = computeHeroFontSize(\n result.word.length,\n position,\n width,\n height,\n safeZone,\n );\n // Fixed-height slot so words of different sizes don't jump vertically.\n // Slot is the max possible hero size for this position; lineHeight: 1 on\n // the inner word locks the glyph box to the font height so flex-center\n // lands the glyph at the same Y for every word.\n const slotHeight =\n position === \"center\" ? 480 * scale : Math.min(220 * scale, height * 0.28 * 0.8);\n return (\n <div style={{ ...containerStyle, fontSize: perWordFontSize }}>\n <div\n style={{\n height: slotHeight,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n }}\n >\n <div\n style={{\n opacity: result.opacity,\n transform: `${result.transform} `,\n lineHeight: 1,\n ...(result.letterSpacing ? { letterSpacing: result.letterSpacing } : {}),\n }}\n >\n {renderWithEmoji(result.word, perWordFontSize)}\n </div>\n </div>\n </div>\n );\n }\n\n return null;\n};\n"
41
+ },
42
+ {
43
+ "path": "src/visual-system/emoji/index.tsx",
44
+ "type": "registry:component",
45
+ "target": "vanillasky/emoji/index.tsx",
46
+ "content": "import * as React from \"react\";\n\nconst NATIVE_EMOJI_FONT = \"Apple Color Emoji,Segoe UI Emoji,Noto Color Emoji,sans-serif\";\nconst NATIVE_EMOJI = /\\p{Emoji_Presentation}|\\p{Regional_Indicator}|\\u{FE0F}|\\u{20E3}/u;\n\n/** True for emoji-presentation graphemes, not plain symbols such as ★ or ✓. */\nexport function isNativeEmoji(char: string): boolean {\n return NATIVE_EMOJI.test(char);\n}\n\nexport interface EmojiProps {\n /** The emoji character or grapheme cluster, e.g. \"🎉\" or \"👩‍💻\". */\n char: string;\n /** Font size in px. */\n size: number;\n /** vertical-align for inline flow. Defaults to a glyph-like baseline nudge. */\n verticalAlign?: React.CSSProperties[\"verticalAlign\"];\n /** Extra styles merged onto the native emoji span. */\n style?: React.CSSProperties;\n}\n\n/** Render emoji with the viewer's OS font while preserving text-style symbols. */\nexport const Emoji: React.FC<EmojiProps> = ({ char, size, verticalAlign = \"-0.15em\", style }) => {\n const nativeEmoji = isNativeEmoji(char);\n return (\n <span\n role={nativeEmoji ? \"img\" : undefined}\n aria-label={nativeEmoji ? char : undefined}\n style={{\n ...(nativeEmoji ? { fontFamily: NATIVE_EMOJI_FONT } : {}),\n fontSize: size,\n lineHeight: 1,\n display: \"inline-block\",\n verticalAlign,\n ...style,\n }}\n >\n {char}\n </span>\n );\n};\n"
47
+ },
48
+ {
49
+ "path": "src/visual-system/emoji/emoji-text.tsx",
50
+ "type": "registry:component",
51
+ "target": "vanillasky/emoji/emoji-text.tsx",
52
+ "content": "/**\n * EmojiText / renderWithEmoji — split a string into text runs + emoji runs,\n * rendering each emoji with the viewer's native emoji font while leaving\n * everything else as plain text.\n *\n * Segmentation: grapheme clusters via Intl.Segmenter so ZWJ sequences\n * (👩‍💻) and skin-tone modifiers (👍🏽) stay single units. Adjacent emoji\n * clusters each render as their own span in sequence.\n */\n\nimport * as React from \"react\";\nimport { Emoji, isNativeEmoji } from \"./index\";\n\n/** Split text into grapheme clusters (ZWJ + skin-tone safe). */\nfunction toGraphemes(text: string): string[] {\n const Seg = (Intl as unknown as { Segmenter?: typeof Intl.Segmenter }).Segmenter;\n if (Seg) {\n const seg = new Seg(undefined, { granularity: \"grapheme\" });\n const out: string[] = [];\n for (const { segment } of seg.segment(text)) out.push(segment);\n return out;\n }\n // Fallback: code-point spread. Won't keep ZWJ/skin-tone as single units, so\n // those land as separate clusters. Modern browsers all have Segmenter.\n return Array.from(text);\n}\n\nexport interface RenderWithEmojiOptions {\n /** vertical-align passed to each <Emoji>. */\n verticalAlign?: React.CSSProperties[\"verticalAlign\"];\n /** Extra style merged onto each emoji span. */\n emojiStyle?: React.CSSProperties;\n}\n\n/**\n * Split `text` into an array of React nodes — plain-text strings interleaved\n * with <Emoji> spans for every emoji cluster. Returns a single-element\n * `[text]` fast-path when there are no emoji (the common case), so\n * non-emoji text pays ~one regex test.\n *\n * @param text the string to render\n * @param fontSizePx surrounding font size in px (emoji box = this size)\n */\nexport function renderWithEmoji(\n text: string,\n fontSizePx: number,\n opts?: RenderWithEmojiOptions,\n): React.ReactNode[] {\n if (!text) return [text];\n // Cheap bail-out: if the whole string has no emoji-range codepoint, return\n // it untouched (no segmentation, no array churn) — the hot path for the vast\n // majority of titles/bodies.\n if (!isNativeEmoji(text)) return [text];\n\n const clusters = toGraphemes(text);\n const nodes: React.ReactNode[] = [];\n let textBuf = \"\";\n let key = 0;\n\n const flushText = () => {\n if (textBuf) {\n nodes.push(textBuf);\n textBuf = \"\";\n }\n };\n\n for (const cluster of clusters) {\n if (isNativeEmoji(cluster)) {\n flushText();\n nodes.push(\n <Emoji\n key={`e${key++}`}\n char={cluster}\n size={fontSizePx}\n verticalAlign={opts?.verticalAlign}\n style={opts?.emojiStyle}\n />,\n );\n } else {\n textBuf += cluster;\n }\n }\n flushText();\n return nodes;\n}\n\n/**\n * Per-code-unit emoji plan for the typewriter archetype, which reveals text\n * one UTF-16 code unit at a time and indexes by `text.length`. We can't just\n * call renderWithEmoji there (it would re-segment and desync the visibleChars\n * counter), so this maps each cluster's START code-unit index to the full emoji\n * and marks the cluster's CONTINUATION indices as covered (render nothing for\n * them — the start index's span already contains the whole cluster).\n *\n * Returns null when the text contains no emoji (the common case),\n * so the typewriter render keeps its plain per-char path.\n */\nexport interface EmojiTypewriterPlan {\n /** code-unit index → full emoji cluster char (cluster start). */\n starts: Map<number, string>;\n /** code-unit indices that are continuations of a cluster (render nothing). */\n covered: Set<number>;\n}\n\nexport function planTypewriterEmoji(text: string): EmojiTypewriterPlan | null {\n if (!text || !isNativeEmoji(text)) return null;\n const starts = new Map<number, string>();\n const covered = new Set<number>();\n let idx = 0;\n let found = false;\n for (const cluster of toGraphemes(text)) {\n const len = cluster.length; // UTF-16 code units\n if (isNativeEmoji(cluster)) {\n found = true;\n // Store the WHOLE cluster char (not just the start unit) so callers can\n // pass it straight to <Emoji> without splitting a grapheme cluster.\n starts.set(idx, cluster);\n for (let k = 1; k < len; k++) covered.add(idx + k);\n }\n idx += len;\n }\n return found ? { starts, covered } : null;\n}\n\nexport interface EmojiTextProps {\n /** The text to render with emoji in the native operating-system font. */\n children: string;\n /** Surrounding font size in px — sizes each emoji to match a glyph. */\n fontSize: number;\n verticalAlign?: React.CSSProperties[\"verticalAlign\"];\n emojiStyle?: React.CSSProperties;\n}\n\n/**\n * Inline wrapper around renderWithEmoji. Renders a React.Fragment of text +\n * emoji spans. Use where a component currently renders a raw `{text}`\n * child and you have the surrounding font size in px.\n */\nexport const EmojiText: React.FC<EmojiTextProps> = ({\n children,\n fontSize,\n verticalAlign,\n emojiStyle,\n}) => {\n const text = typeof children === \"string\" ? children : \"\";\n return <>{renderWithEmoji(text, fontSize, { verticalAlign, emojiStyle })}</>;\n};\n"
53
+ },
54
+ {
55
+ "path": "src/visual-system/scene-templates/types.ts",
56
+ "type": "registry:lib",
57
+ "target": "vanillasky/scene-templates/types.ts",
58
+ "content": "/**\n * Scene template types.\n *\n * A template is a reusable React component that defines how a scene looks.\n * It declares the variables an editor or model may provide\n * and receives universal settings as props.\n *\n * Templates are searchable by AI via description, category, jobs, register,\n * and useWhen guidance.\n * The variable schema enables any LLM to fill in template variables via JSON.\n */\n\nimport type { ResolvedTokens } from \"../theme\";\nimport type { SafeZone, TemplateStyle } from \"../template-context\";\n\n/**\n * Props passed to every scene template component.\n *\n * All animation must be driven by `progress` (0→1). No CSS animations,\n * no Framer Motion, no requestAnimationFrame. Use interpolate/spring\n * from animation-utils.ts.\n *\n * Scale factor: use `Math.min(width, height) / 1080` — normalizes to\n * the short edge so visuals are consistent across portrait and landscape.\n */\nexport interface SceneTemplateProps {\n variables: Record<string, unknown>;\n style: TemplateStyle;\n /** 0→1 through the scene's duration */\n progress: number;\n /** Presentation clock. Active templates receive the same complete 0→1 timeline as progress. */\n motionProgress?: number;\n /** 0→1 beat pulse intensity */\n beatIntensity: number;\n /** 1080 (portrait) or 1920 (landscape) */\n width: number;\n /** 1920 (portrait) or 1080 (landscape) */\n height: number;\n /** Video-level default text effect (for templates that opt in via usesGlobalTextEffect) */\n textArchetype?: string;\n /** How text leaves the scene (fade / shrink / pop / blur-scale). Falls back to a sensible default per textArchetype when undefined. */\n /** Video-level default background effect (for templates that opt in via usesGlobalBackgroundEffect) */\n backgroundEffect?: string;\n /** Platform-aware safe zone insets in pixels — use for text placement */\n safeZone: SafeZone;\n /** Scene duration in seconds — use for time-based (not progress-based) animations */\n sceneDuration?: number;\n /**\n * Brand tokens already resolved from `style`. Built-in templates import\n * resolveTokens directly; an ejected `custom_*` scene can't import anything,\n * so without this it has no way to reach the same values and ends up\n * hardcoding white, black and shadows — the body then looks generic next to\n * a frame that IS using the brand.\n */\n tokens?: ResolvedTokens;\n /**\n * True when the preview player is actively advancing progress; false when paused.\n * Templates that play HTML5 <video> elements should pause them when this is false.\n * Undefined (export capture path) is treated as true.\n */\n isPlaying?: boolean;\n}\n"
59
+ }
60
+ ],
61
+ "meta": {
62
+ "vanillasky": {
63
+ "layer": "template",
64
+ "tier": "free",
65
+ "register": "device-led",
66
+ "jobs": [
67
+ "proof"
68
+ ],
69
+ "useWhen": "Code, configuration, an API, or an SDK mechanism is central to understanding the product.",
70
+ "textCanvas": "tight",
71
+ "minDuration": 2,
72
+ "preferredDuration": 3,
73
+ "schema": {
74
+ "type": "object",
75
+ "properties": {
76
+ "texts": {
77
+ "type": "string",
78
+ "title": "Text",
79
+ "description": "Concise title shown above the editor (48 characters maximum).",
80
+ "minLength": 1,
81
+ "maxLength": 48,
82
+ "default": "Simple as this."
83
+ },
84
+ "code": {
85
+ "type": "string",
86
+ "title": "Code",
87
+ "description": "Code snippet — use \\n for line breaks",
88
+ "default": "import { getVideoDuration } from \"@vanillaskyai/video\";\nimport type { Video } from \"@vanillaskyai/video\";\n\nexport function duration(video: Video) {\n return getVideoDuration(video);\n}"
89
+ },
90
+ "filename": {
91
+ "type": "string",
92
+ "title": "Filename",
93
+ "description": "Filename shown in the editor title bar (32 characters maximum).",
94
+ "maxLength": 32,
95
+ "default": "app.ts"
96
+ },
97
+ "mediaUrl": {
98
+ "type": "string",
99
+ "title": "Background media",
100
+ "description": "Optional photo or video URL behind this scene. When set, replaces the brand gradient.",
101
+ "format": "uri",
102
+ "default": ""
103
+ },
104
+ "mediaKeyword": {
105
+ "type": "string",
106
+ "title": "Background search keyword",
107
+ "description": "2-4 word English term for Pexels stock-footage search (auto-fills mediaUrl).",
108
+ "format": "stock-media-keyword",
109
+ "default": ""
110
+ },
111
+ "mediaType": {
112
+ "type": "string",
113
+ "title": "Background media type",
114
+ "description": "auto detects photo/video from URL. 'gradient' is a deliberate mode — atmospheric brand-color scene with no stock footage.",
115
+ "enum": [
116
+ "auto",
117
+ "photo",
118
+ "video",
119
+ "gradient"
120
+ ],
121
+ "default": "auto"
122
+ },
123
+ "mediaPoster": {
124
+ "type": "string",
125
+ "title": "Background poster image",
126
+ "description": "Still image URL shown while a video backdrop is decoding its first frame. Auto-filled from Pexels' thumbnail when fillPexelsUrls sets a video mediaUrl. Hides the gradient flash that would otherwise appear in the ~50–400ms gap between a <video> mounting and decoding its first frame.",
127
+ "format": "uri",
128
+ "default": ""
129
+ },
130
+ "mediaPosition": {
131
+ "type": "string",
132
+ "title": "Background focal position",
133
+ "description": "Controls which part of a photo or video stays visible when cover-cropped. Pick the subject's side or vertical anchor after inspecting the frame.",
134
+ "enum": [
135
+ "center",
136
+ "top",
137
+ "bottom",
138
+ "left",
139
+ "right"
140
+ ],
141
+ "default": "center"
142
+ },
143
+ "mediaTreatment": {
144
+ "type": "string",
145
+ "title": "Background contrast treatment",
146
+ "description": "subtle preserves a visual hero; cinematic adds balanced contrast; text-safe adds a stronger wash for copy-heavy scenes.",
147
+ "enum": [
148
+ "subtle",
149
+ "cinematic",
150
+ "text-safe"
151
+ ],
152
+ "default": "cinematic"
153
+ }
154
+ },
155
+ "required": [
156
+ "texts",
157
+ "code"
158
+ ],
159
+ "additionalProperties": false,
160
+ "x-vanillasky": {
161
+ "allowsStockMedia": true
162
+ }
163
+ },
164
+ "label": "Code editor",
165
+ "description": "A syntax-styled editor window reveals a short code sample beneath a headline.",
166
+ "family": "Product showcase",
167
+ "avoidWhen": "The source has no grounded technical detail or a shell command communicates the workflow better.",
168
+ "usesGlobalTextEffect": false,
169
+ "usesGlobalTransition": true,
170
+ "usesGlobalBackgroundEffect": true,
171
+ "timing": {
172
+ "contentFields": [
173
+ "texts",
174
+ "code"
175
+ ],
176
+ "contentUnit": "characters"
177
+ },
178
+ "transitionTiming": {
179
+ "entryReadyProgress": 0.2,
180
+ "holdProgress": 0.7
181
+ }
182
+ }
183
+ }
184
+ }