@snowcone-app/canvas 0.21.2 → 0.22.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 (47) hide show
  1. package/STYLING_CONTRACT.md +31 -7
  2. package/dist/{CanvasRenderer-B0szG0Us.js → CanvasRenderer-6_HhR4-q.js} +170 -189
  3. package/dist/CanvasRenderer-6_HhR4-q.js.map +1 -0
  4. package/dist/{ContextualToolbars-BYnovWnN.js → ContextualToolbars-BDEt9ND0.js} +1619 -1846
  5. package/dist/ContextualToolbars-BDEt9ND0.js.map +1 -0
  6. package/dist/{EditorCanvasImpl-BmLHjXe7.js → EditorCanvasImpl-BH_bKy-F.js} +5 -5
  7. package/dist/{EditorCanvasImpl-BmLHjXe7.js.map → EditorCanvasImpl-BH_bKy-F.js.map} +1 -1
  8. package/dist/ImagePanel-BwqFDKvW.js +951 -0
  9. package/dist/ImagePanel-BwqFDKvW.js.map +1 -0
  10. package/dist/{SnowconeCanvas-Bj2773ym.js → SnowconeCanvas-Cx7nXlBI.js} +19 -18
  11. package/dist/{SnowconeCanvas-Bj2773ym.js.map → SnowconeCanvas-Cx7nXlBI.js.map} +1 -1
  12. package/dist/{UnifiedFontService-C8gaspRD.js → UnifiedFontService-CC3CSmH5.js} +1042 -984
  13. package/dist/UnifiedFontService-CC3CSmH5.js.map +1 -0
  14. package/dist/advanced.mjs +97 -96
  15. package/dist/advanced.mjs.map +1 -1
  16. package/dist/api/embed.d.ts +3 -1
  17. package/dist/components/editor/EditorCanvas.d.ts +9 -0
  18. package/dist/components/editor/EditorRoot.d.ts +11 -0
  19. package/dist/components/editor/LazyImageBrowser.d.ts +7 -0
  20. package/dist/components/editor/commerceStore.d.ts +13 -0
  21. package/dist/components/embed-realtime/validateEmbed.d.ts +10 -4
  22. package/dist/custom-icons-BW6hqmkL.js +236 -0
  23. package/dist/custom-icons-BW6hqmkL.js.map +1 -0
  24. package/dist/design/product-config.d.ts +48 -0
  25. package/dist/editorErrors-B2mb1sVN.js.map +1 -1
  26. package/dist/{embed-pM7ZkFuz.js → embed-8ecUMMH-.js} +550 -441
  27. package/dist/embed-8ecUMMH-.js.map +1 -0
  28. package/dist/embed.mjs +30 -29
  29. package/dist/errors/editorError.d.ts +3 -0
  30. package/dist/guards-8rkFAMBs.js +24 -0
  31. package/dist/guards-8rkFAMBs.js.map +1 -0
  32. package/dist/index.mjs +5 -5
  33. package/dist/internals.mjs +1 -1
  34. package/dist/style.css +1 -1
  35. package/dist/{template-fields-BsnHMf1i.js → template-fields-C2pSfMBh.js} +57 -39
  36. package/dist/template-fields-C2pSfMBh.js.map +1 -0
  37. package/dist/validation-C9Fe9ahK.js +8367 -0
  38. package/dist/validation-C9Fe9ahK.js.map +1 -0
  39. package/example/package.json +1 -1
  40. package/package.json +1 -1
  41. package/dist/CanvasRenderer-B0szG0Us.js.map +0 -1
  42. package/dist/ContextualToolbars-BYnovWnN.js.map +0 -1
  43. package/dist/UnifiedFontService-C8gaspRD.js.map +0 -1
  44. package/dist/embed-pM7ZkFuz.js.map +0 -1
  45. package/dist/template-fields-BsnHMf1i.js.map +0 -1
  46. package/dist/validation-DdVeWnlo.js +0 -9308
  47. package/dist/validation-DdVeWnlo.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"embed-pM7ZkFuz.js","sources":["../src/components/embed-realtime/context.ts","../src/components/embed-realtime/validateEmbed.ts","../src/components/editor/EditorRoot.tsx","../src/components/editor/EditorCanvas.tsx","../src/components/editor/EditorPreview.tsx","../src/components/editor/EditorTextField.tsx","../src/components/editor/EditorBuy.tsx","../src/components/editor/EditorControls.tsx","../src/components/editor/useProductSelection.ts","../src/components/editor/index.ts","../src/components/embed-realtime/RealtimeEmbed.tsx","../src/components/embed-realtime/RealtimeCanvas.tsx","../src/components/embed-realtime/RealtimeMockup.tsx","../src/components/embed-realtime/useRealtimeMockups.ts","../src/default-editor/SnowconeEditor.tsx","../src/api/embed.ts"],"sourcesContent":["'use client';\n\n/**\n * Shared context for the realtime embed primitives. `<RealtimeEmbed>` owns the\n * single {@link RenderSession} and the live mockup state; `<RealtimeCanvas>` and\n * `<RealtimeMockup>` read it from here so the editor and the preview can be laid\n * out freely yet can never desync (they share one session, one design, one\n * placement).\n */\n\nimport { createContext, useContext } from 'react';\nimport type { RenderSession, RenderProduct, RenderState, MockupResult } from '@snowcone-app/sdk';\nimport type { AnyDesign } from '../../design/design-builder.js';\nimport type { PieceGuidesConfig } from '../embed/SnowconeCanvas.js';\nimport type { DesignStateStore } from '../editor/designStateStore.js';\n\nexport interface EmbedContextValue {\n /** The single session the editor pushes renders to. `null` if the session\n * failed to construct (a config fail-fast, surfaced via `error`). Escape\n * hatch for advanced use. */\n session: RenderSession | null;\n /** The design the embed was seeded with — single source of truth for both the\n * canvas seed and the seed render. */\n design: AnyDesign;\n /** The placement name (= the design's artboard name). Both the canvas artboard\n * and every `renderState` call use this; derived once so it can't drift. */\n placement: string;\n /** The product being rendered against. */\n product: RenderProduct;\n /** Latest mockups from the session. Reactive — updates re-render consumers. */\n mockups: MockupResult[];\n /** True between a render dispatch and the next mockup / error. */\n isRendering: boolean;\n /** Last render error message, or null. */\n error: string | null;\n /** Default edit→render throttle (ms). */\n throttleMs: number;\n /**\n * The product's printable-area guides (dead zones, safe areas) — fetched by\n * `<RealtimeEmbed>` and already gated on the design's artboard matching the\n * print-file frame they were authored in. `null` when the product has none,\n * the fetch failed, or the dims don't line up. `<RealtimeCanvas>` forwards\n * this to the editor so embedders get the same overlay snowcone.app shows.\n */\n pieceGuides: PieceGuidesConfig | null;\n /** Dispatch a server render for the embed's placement. Sets `isRendering`. */\n pushRender: (state: RenderState, throttleMs?: number) => void;\n /**\n * The ONE live design state under this Root (ADR-0085 §3 / T2): seeded from\n * `design`, updated by every canvas change and every `Editor.TextField`\n * write, last-write-wins. Commerce parts read THIS, never the seed. Stable\n * identity; subscribe for updates (`useSyncExternalStore`-shaped).\n *\n * Stable since ADR-0085 P4; additive-only from here.\n */\n stateStore: DesignStateStore;\n}\n\nexport const EmbedContext = createContext<EmbedContextValue | undefined>(undefined);\n\n/**\n * Read the embed context. Throws a clear error when called outside\n * `<RealtimeEmbed>` — the most common wiring mistake.\n */\nexport function useEmbedContext(): EmbedContextValue {\n const ctx = useContext(EmbedContext);\n if (!ctx) {\n throw new Error(\n 'useRealtimeMockups / <RealtimeCanvas> / <RealtimeMockup> must be rendered ' +\n 'inside <RealtimeEmbed>. Wrap them: ' +\n '<RealtimeEmbed shop=… product=… design=… grantUrl=…>…</RealtimeEmbed>'\n );\n }\n return ctx;\n}\n","'use client';\n\n/**\n * Mount-time assertions for the realtime embed. Catches the silent-break wiring\n * mistakes that otherwise produce a blank canvas or a mockup that never renders:\n *\n * - no grant source (the session can't authorize → silent hang)\n * - a variant product with no `variantId` (→ ~30s render hang), AND the\n * can't-even-tell case: neither `variantId` nor `options` passed\n * - empty `mockupIds` (nothing to render)\n * - the design's placement isn't one of the product's placements (renderState\n * targets an artboard the product doesn't have → silent blank mockup)\n * - a multi-placement product (the embed renders ONE placement, so the server\n * waits on the rest and the render times out ~15s in — needs the eject path)\n * - duplicate layer names (binding hooks resolve to the wrong element)\n *\n * Two consumption modes (ADR-0085 / F3):\n * - `validateEmbed` — the legacy advisory API: logs `console.warn` /\n * `console.error` and never throws, so a partly-wired `<RealtimeEmbed>`\n * still mounts and renders what it can. Dev-only at the call site.\n * - `collectEmbedIssues` — the structured list; `Editor.Root` THROWS on the\n * error-severity issues (console.error is invisible to headless agents).\n */\n\nimport { assertVariantSelected, type RenderProduct } from '@snowcone-app/sdk';\nimport type { AnyDesign } from '../../design/design-builder.js';\n\nexport interface ValidateEmbedInput {\n shop: string;\n product: RenderProduct;\n design: AnyDesign;\n hasGrant: boolean;\n}\n\n/** One wiring problem found at mount. `error`-severity issues break the embed\n * (no render will ever arrive / it targets the wrong thing); `warn`-severity\n * issues are advisory. */\nexport interface EmbedIssue {\n severity: 'error' | 'warn';\n /** Stable issue key, carried into `EditorError.data.issue` in throw mode. */\n issue:\n | 'missing-shop'\n | 'missing-grant'\n | 'empty-mockup-ids'\n | 'variant-required'\n | 'multi-placement'\n | 'placement-mismatch'\n | 'duplicate-layer-names';\n message: string;\n}\n\nconst TAG = '[RealtimeEmbed]';\n\n/**\n * The placement labels this product demands a canvas_state for. Prefers the\n * catalog's `requiredPlacements` contract; variant-auto-filled (color)\n * placements don't count — `variantId` satisfies them (the missing-variantId\n * case has its own guard above). Falls back to the bare `placements` label\n * list ONLY when the product has no variant in play: a label list can't say\n * which entries are auto-filled colors, but without a variant none are.\n */\nfunction requiredPlacementLabels(product: RenderProduct): string[] {\n if (product?.requiredPlacements?.length) {\n return product.requiredPlacements.filter((p) => !p.autoFilledByVariant).map((p) => p.label);\n }\n const variantIds = new Set(\n (product?.options?.combinations ?? [])\n .map((c) => c.variantId)\n .filter((id): id is string => typeof id === 'string' && id !== '')\n );\n const hasVariantAxis = Boolean(product?.variantId) || variantIds.size > 1;\n return hasVariantAxis ? [] : (product?.placements ?? []);\n}\n\n/** Find every wiring problem. Pure — no logging, no throwing. */\nexport function collectEmbedIssues({ shop, product, design, hasGrant }: ValidateEmbedInput): EmbedIssue[] {\n const issues: EmbedIssue[] = [];\n\n if (!shop) {\n issues.push({\n severity: 'error',\n issue: 'missing-shop',\n message: '`shop` is required (your publishable shop id).',\n });\n }\n\n if (!hasGrant) {\n issues.push({\n severity: 'error',\n issue: 'missing-grant',\n message:\n 'no grant source — pass `grantUrl` (a proxy to mintRealtimeGrant) ' +\n 'or `grant`. Without it the session can never authorize and no mockup renders.',\n });\n }\n\n if (!product?.mockupIds?.length) {\n issues.push({\n severity: 'error',\n issue: 'empty-mockup-ids',\n message:\n 'product.mockupIds is empty — pass the catalog scene codes ' +\n '(product.mockups[].id) you want rendered, e.g. [\"FV1qjO\"].',\n });\n }\n\n // Variant axis: a product with a color/size option REQUIRES a variantId or the\n // render hangs ~30s waiting for a color blob that never comes. When `options`\n // (the catalog combinations) is passed we can detect the axis and fail fast\n // before the session's constructor throws. When `options` is NOT passed we\n // can't see the axis — so we DON'T warn here (a no-`options` product might\n // genuinely have no variants; warning would false-fire on every valid\n // single-variant embed). That stall is instead caught at runtime by\n // the embed's slow-render backstop (`slowRenderHint`), which fires only\n // when a render actually hangs — no false positives, and it covers every\n // silent-hang cause, not just this one.\n if (product?.options) {\n try {\n assertVariantSelected(product);\n } catch (err) {\n issues.push({\n severity: 'error',\n issue: 'variant-required',\n message: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n const json = design.toJSON();\n const placement = json.activeArtboard;\n\n // The embed renders exactly ONE placement — the design's artboard. A\n // product that requires several can never complete through it: the canvas\n // mounts perfectly, then the server waits on the missing canvas_states until\n // the ~15s \"Timed out waiting for all placements\" error. Fully knowable at\n // mount from the catalog data already on the product, so say so now.\n const required = requiredPlacementLabels(product);\n if (required.length > 1) {\n issues.push({\n severity: 'error',\n issue: 'multi-placement',\n message:\n `product ${product.productId} requires placements ` +\n `[${required.join(', ')}] but this embed renders a single ` +\n `placement (\"${placement}\"). The render will time out waiting for the ` +\n 'others. This product needs the eject path — see ' +\n 'https://developers.snowcone.app/embed-mode#eject.',\n });\n }\n\n if (product?.placements?.length && !product.placements.includes(placement)) {\n issues.push({\n severity: 'error',\n issue: 'placement-mismatch',\n message:\n `the design's placement \"${placement}\" is not in ` +\n `product.placements [${product.placements.join(', ')}]. The canvas ` +\n 'artboard name and renderState placement must equal a real product ' +\n 'placement label, or the server renders a blank mockup. Fix the ' +\n '`name` passed to design({ name }).',\n });\n }\n\n const names = json.elements.map((el) => (el as { name?: string }).name).filter((n): n is string => Boolean(n));\n const dupes = names.filter((n, i) => names.indexOf(n) !== i);\n if (dupes.length) {\n issues.push({\n severity: 'warn',\n issue: 'duplicate-layer-names',\n message:\n `duplicate layer name(s) [${[...new Set(dupes)].join(', ')}] — ` +\n 'useTextBinding(name) / useImageBinding(name) bind to the FIRST match, ' +\n 'so a duplicate name makes a control edit the wrong layer. Keep names unique.',\n });\n }\n\n return issues;\n}\n\n/** Legacy advisory API: log everything, never throw. (`placement-mismatch`\n * keeps its historical `console.warn` level here; in `Editor.Root`'s throw\n * mode it is error-severity per F3.) */\nexport function validateEmbed(input: ValidateEmbedInput): void {\n for (const issue of collectEmbedIssues(input)) {\n const log =\n issue.severity === 'error' && issue.issue !== 'placement-mismatch' ? console.error : console.warn;\n log(`${TAG} ${issue.message}`);\n }\n}\n","'use client';\n\n/**\n * `<Editor.Root>` — the one provider boundary of the composable editor\n * primitives (ADR-0085). Owns the realtime {@link RenderSession}, the design,\n * the live mockups, the ONE design-state store, the part registry, and the\n * built-in error boundary. Parts (`Editor.Canvas/Preview/TextField/Buy/…`)\n * carry behavior + state subscription only; the HOST owns all layout.\n *\n * STATE MODEL (D9 — state always, renderer lazy):\n *\n * Editor.Root (one provider boundary · error boundary · applies .sc-root once)\n * │\n * ├── STATE — always mounted, renderer-free\n * │ └── EmbedContext design · product · render session · mockups ·\n * │ pushRender · stateStore (the ONE live design state)\n * │ (EditorProvider joins here in P1's inversion — until then the\n * │ editor document still mounts inside Editor.Canvas's chunk)\n * │\n * ├── <Editor.Canvas/> dynamic import ──→ [HEAVY RENDERER CHUNK]\n * ├── <Editor.Preview/> ←─ mockups (×N under one Root is VALID)\n * ├── <Editor.TextField/> ─→ stateStore (by layer token) ─→ pushRender\n * └── <Editor.Buy/> ←─ stateStore + required-TextField registry\n *\n * This file is the EXTRACTION of `<RealtimeEmbed>`'s internals (D5 — not a\n * copy): `RealtimeEmbed` is now `<EditorRoot>` plus the legacy advisory\n * validation mode, so the existing realtime tests exercise this Root.\n *\n * The legacy embed had no DOM of its own; Root must apply `.sc-root` once\n * (parts never self-apply, ADR-0085). `display: contents` squares the two —\n * the scope div generates no box, so host grid/flex layouts see the children\n * directly and the legacy wrapper stays layout-identical.\n */\n\nimport React, {\n Component,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n type ReactNode,\n} from 'react';\nimport {\n RenderSession,\n type RenderProduct,\n type RenderState,\n type MockupResult,\n type RealtimeGrant,\n} from '@snowcone-app/sdk';\nimport type { AnyDesign } from '../../design/design-builder.js';\nimport { CanvasServicesProvider, type CanvasServices } from '../../contexts/CanvasServicesContext.js';\nimport { EditorProvider } from '../../contexts/EditorContext.js';\nimport { BoundLayerGuardContext } from '../../contexts/BoundLayerGuardContext.js';\nimport { EmbedContext, type EmbedContextValue } from '../embed-realtime/context.js';\nimport { usePieceGuideBundle, pieceGuidesForArtboard } from '../embed-realtime/usePieceGuideBundle.js';\nimport { collectEmbedIssues, validateEmbed } from '../embed-realtime/validateEmbed.js';\nimport { EditorError, isEditorError } from '../../errors/editorError.js';\nimport { recordContainedEditorError } from '../../testing/editorErrors.js';\nimport { serializeStateForServer } from '../../rendering/serialize-for-server.js';\nimport { DesignStateStore } from './designStateStore.js';\nimport { CommerceStateStore } from './commerceStore.js';\nimport {\n EditorPartsRegistry,\n EditorRootInternalsContext,\n makeInvariantReporter,\n type EditorRootInternals,\n} from './RootInternals.js';\n\n/**\n * How the session authorizes. Provide exactly one — the discriminated union makes\n * \"I forgot the grant\" a compile error rather than a silent runtime hang.\n *\n * Member order is load-bearing: when NEITHER prop is supplied (the common\n * mistake) TS reports the missing property of the LAST union member, so the\n * `grantUrl` arm is kept last on purpose — the error then reads \"Property\n * 'grantUrl' is missing\", pointing at the recommended prop instead of `grant`.\n * Don't reorder these.\n */\nexport type GrantSource =\n | {\n /** Full control over fetching the grant: a token or a token factory. */\n grant: RealtimeGrant | (() => Promise<RealtimeGrant>);\n grantUrl?: never;\n }\n | {\n /** Your endpoint returning `{ token, expiresAt }` for `POST { shop }` —\n * a same-origin proxy to `mintRealtimeGrant`. Recommended. */\n grantUrl: string;\n grant?: never;\n };\n\nexport type EditorRootBaseProps = {\n /** Publishable shop id (= shop.id, like a Stripe pk_). Billing target. */\n shop: string;\n /** Product to render against (catalog ids). `mockupIds` are scene codes\n * (product.mockups[].id), NOT placement names. Pass `placements`, `options`\n * + `requiredPlacements` so wiring mistakes (including a multi-placement\n * product, which the embed can't render) fail loud at mount instead of\n * hanging. */\n product: RenderProduct;\n /** Single source of truth — seeds the canvas AND the first render. Build it\n * with `design({ name, width, height })…`. Its artboard `name` is the\n * placement every render targets. */\n design: AnyDesign;\n /** Edit→render throttle in ms (default 200). */\n throttleMs?: number;\n /** Called whenever new mockups arrive. */\n onMockups?: (results: MockupResult[]) => void;\n /** Called on a render/timeout error. */\n onRenderError?: (message: string) => void;\n /** Override the realtime WS endpoint (defaults to the SDK's prod URL). */\n wsUrl?: string;\n /**\n * Privileged-service wiring for the editor chrome (the Image Browser's\n * stock-image search and AI generation tabs). Same pattern as `grantUrl`:\n * host these URLs on your server; your vendor keys live there.\n */\n services?: CanvasServices;\n children?: ReactNode;\n /**\n * Wiring-validation mode. `Editor.Root` defaults to `'throw'` (F3:\n * console.error is invisible to headless agents — error-severity wiring\n * issues throw `EditorError E_EMBED_CONFIG` into Root's boundary). The\n * legacy `<RealtimeEmbed>` wrapper passes `'warn'` for back-compat\n * (dev-only console diagnostics, never throws).\n * @internal\n */\n __validation?: 'throw' | 'warn';\n};\n\nexport type EditorRootProps = GrantSource & EditorRootBaseProps;\n\n/**\n * How long a render may be in flight before the embed assumes something is wrong\n * and surfaces a diagnostic. A healthy render returns in ~2s; the session's own\n * watchdog is ~30s. 8s sits in between — long enough not to false-fire on a\n * genuinely slow render, short enough to spare a first-timer the full 30s of\n * silence.\n */\nexport const SLOW_RENDER_HINT_MS = 8000;\n\n/**\n * The dev-console message shown when a render hasn't produced a mockup in\n * {@link SLOW_RENDER_HINT_MS}. A general backstop for the whole silent-hang\n * class — not just the missing-`variantId` trap — so a stuck embed always says\n * *something* actionable instead of hanging quietly.\n */\nexport function slowRenderHint(placement: string): string {\n return (\n `[RealtimeEmbed] No mockup after ${Math.round(SLOW_RENDER_HINT_MS / 1000)}s. ` +\n `Common causes: a variant product missing \\`variantId\\` (pass \\`product.options\\` ` +\n `so the embed can flag it up front), a multi-placement product (the server waits ` +\n `for every required placement but <RealtimeEmbed> sends only \"${placement}\" — pass ` +\n `\\`product.requiredPlacements\\` so this is flagged at mount; such products need ` +\n `the eject path), an unreachable or non-public asset URL in the design, or the ` +\n `placement \"${placement}\" not existing on the product. ` +\n `The render may still arrive — this is a heads-up, not a failure.`\n );\n}\n\nfunction toGetToken(props: EditorRootProps): { grantUrl: string } | { getToken: () => Promise<RealtimeGrant> } {\n if ('grantUrl' in props && props.grantUrl) {\n return { grantUrl: props.grantUrl };\n }\n const grant = (props as { grant: RealtimeGrant | (() => Promise<RealtimeGrant>) }).grant;\n if (typeof grant === 'function') return { getToken: grant };\n return { getToken: () => Promise.resolve(grant) };\n}\n\n// ── The error card (D11): contained, loud, in the widget slot ───────────────\n\nfunction ErrorCard({ error, onRetry }: { error: Error; onRetry?: () => void }): React.ReactElement {\n const code = isEditorError(error) ? error.code : 'EDITOR_ERROR';\n return (\n <div\n data-sc-part=\"error\"\n role=\"alert\"\n style={{\n padding: '16px',\n borderRadius: '12px',\n border: '1px solid var(--sc-color-destructive, #b91c1c)',\n background: 'var(--sc-color-surface, #fef2f2)',\n color: 'var(--sc-color-foreground, #7f1d1d)',\n fontFamily: 'ui-sans-serif, system-ui, sans-serif',\n fontSize: '13px',\n lineHeight: 1.5,\n }}\n >\n <p style={{ margin: 0, fontWeight: 700 }}>Editor failed: {code}</p>\n <p style={{ margin: '4px 0 0' }}>{error.message}</p>\n {onRetry ? (\n <button\n type=\"button\"\n data-sc-part=\"error-retry\"\n onClick={onRetry}\n style={{\n marginTop: '10px',\n padding: '6px 14px',\n borderRadius: '9999px',\n border: '1px solid currentColor',\n background: 'transparent',\n color: 'inherit',\n font: 'inherit',\n fontWeight: 600,\n cursor: 'pointer',\n }}\n >\n Retry\n </button>\n ) : null}\n </div>\n );\n}\n\ninterface BoundaryProps {\n /** Imperatively-reported error (handler/async path) — same card. */\n reportedError: EditorError | null;\n onRetry: () => void;\n children: ReactNode;\n}\n\ninterface BoundaryState {\n caught: Error | null;\n}\n\n/**\n * The catching half of Root's boundary (D11): render/lifecycle/effect throws\n * from the parts show an error card in the widget slot while the host page\n * survives.\n *\n * Test containment-bypass (the D11 review concern — \"an agent's mounts-\n * without-crashing test passes green on a broken composition\"): under\n * NODE_ENV=test/dev every contained error is RECORDED, and\n * `expectNoEditorErrors()` from `@snowcone-app/canvas/testing` fails the\n * test. (A literal rethrow-from-the-boundary was tried and rejected: an\n * uncaught throw from a layout effect corrupts React 18's work loop and\n * poisons every later render in the test file — \"Should not already be\n * working\".)\n */\nclass CatchingBoundary extends Component<BoundaryProps, BoundaryState> {\n state: BoundaryState = { caught: null };\n\n static getDerivedStateFromError(error: Error): BoundaryState {\n return { caught: error };\n }\n\n componentDidCatch(error: Error): void {\n recordContainedEditorError(error);\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[Editor.Root] contained a composition error:', error);\n }\n }\n\n render(): ReactNode {\n if (this.state.caught) {\n // Composition mistakes need a code change; a retry would just re-throw.\n return <ErrorCard error={this.state.caught} />;\n }\n return this.props.children;\n }\n}\n\n/**\n * Root's built-in boundary (D11): the imperatively-REPORTED channel\n * (handler/async failures like the lazy chunk failing to load) renders the\n * card directly, with retry when the failure is retryable; everything else\n * goes through the catching class boundary above.\n */\nfunction EditorBoundary({ reportedError, onRetry, children }: BoundaryProps): React.ReactElement {\n if (reportedError) {\n const retryable = isEditorError(reportedError) && reportedError.code === 'E_CHUNK_LOAD_FAILED';\n return <ErrorCard error={reportedError} onRetry={retryable ? onRetry : undefined} />;\n }\n return <CatchingBoundary reportedError={null} onRetry={onRetry}>{children}</CatchingBoundary>;\n}\n\n// ── The state-owning inner (everything here is INSIDE the boundary) ─────────\n\nfunction EditorRootInner(props: EditorRootProps & { internals: EditorRootInternals }): React.ReactElement {\n const {\n shop,\n product,\n design,\n throttleMs = 200,\n onMockups,\n onRenderError,\n wsUrl,\n services,\n children,\n internals,\n __validation = 'throw',\n } = props;\n\n const placement = useMemo(() => design.toJSON().activeArtboard, [design]);\n\n // Buy-owned variant selection (ADR-0085 §2, P2): subscribe to the commerce\n // store so a host's `select()` re-renders this component with the newly\n // resolved variant. The resolved variant NEVER re-keys the session — it is\n // applied to the LIVE session below (`setProduct` + a re-push of the\n // current design state), so a color click costs one config message + one\n // render, not a WS teardown/re-grant/reconnect.\n useSyncExternalStore(\n internals.commerce.subscribe,\n internals.commerce.getVersion,\n internals.commerce.getVersion,\n );\n const selectedVariantId = internals.commerce.resolvedVariantId();\n\n // #566: fetch the product's printable-area guides (camera cutouts, safe\n // areas) so the editor shows them automatically — without this, a buyer can\n // edit artwork that sits under hardware and the mockup never changes, with\n // no signal anywhere. variantId IS a gvid; fall back to the catalog's\n // default variant. Gated below on the design's artboard matching the\n // print-file frame the guides were authored in (same gate as snowcone.app).\n // The SELECTED variant wins — guides follow the variant being rendered.\n const guideBundle = usePieceGuideBundle(selectedVariantId ?? product.variantId ?? product.defaultGvid);\n const pieceGuides = useMemo(() => {\n if (!guideBundle) return null;\n const artboard = design.toJSON().artboards[0];\n return pieceGuidesForArtboard(guideBundle, artboard) ?? null;\n }, [guideBundle, design]);\n\n // Keep the latest callbacks reachable without re-creating the session.\n const onMockupsRef = useRef(onMockups);\n const onRenderErrorRef = useRef(onRenderError);\n onMockupsRef.current = onMockups;\n onRenderErrorRef.current = onRenderError;\n\n const [mockups, setMockups] = useState<MockupResult[]>([]);\n const [isRendering, setIsRendering] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n const hasGrant = Boolean(('grantUrl' in props && props.grantUrl) || ('grant' in props && props.grant));\n\n // One session per (shop, product, placement, auth). Key it on the product's\n // identity-BEARING fields, not the object reference — so an embedder passing\n // an inline `product={{…}}` (the natural way to write it) doesn't rebuild the\n // session and reconnect on every render. A real change (different product,\n // mockups, or variant) still re-keys it. `options`/`placements` are advisory\n // (fail-fast validation) so they don't need to force a rebuild.\n const auth = toGetToken(props);\n const authKey = 'grantUrl' in auth ? auth.grantUrl : 'getToken';\n const productKey = `${product.productId}|${product.mockupIds.join(',')}|${product.variantId ?? ''}`;\n\n // Wiring validation. Editor.Root throws (F3 — fails loud into the boundary,\n // visible to headless agents); the legacy <RealtimeEmbed> wrapper keeps the\n // advisory dev-only console diagnostics. The ref-based dedup survives\n // StrictMode's deliberate unmount/remount cycle.\n const validationKey = `${shop}|${productKey}|${placement}|${hasGrant}`;\n // Render-time on purpose: in throw mode a wiring mistake must throw into\n // Root's boundary, not log (F3 — console.error is invisible to headless\n // agents). Memoized so it runs once per meaningful change.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n useMemo(() => {\n if (__validation !== 'throw') return;\n const issues = collectEmbedIssues({ shop, product, design, hasGrant });\n const fatal = issues.find((i) => i.severity === 'error');\n if (fatal) {\n throw new EditorError('E_EMBED_CONFIG', fatal.message, {\n issue: fatal.issue,\n docSlug: 'embed-mode',\n });\n }\n for (const issue of issues) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[Editor.Root] ${issue.message}`);\n }\n }\n }, [validationKey, __validation]);\n const validatedKeyRef = useRef<string | null>(null);\n useEffect(() => {\n if (__validation !== 'warn') return;\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n if (validatedKeyRef.current === validationKey) return;\n validatedKeyRef.current = validationKey;\n validateEmbed({ shop, product, design, hasGrant });\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [validationKey, __validation]);\n\n // RenderSession's constructor fail-fasts (e.g. a variant product with no\n // variantId) by THROWING. Catch it here so a config mistake surfaces through\n // `onRenderError` + the error state instead of throwing during render and\n // white-screening the whole host page.\n const sessionResult = useMemo<{ session: RenderSession } | { error: string }>(\n () => {\n try {\n return { session: new RenderSession({ shop, product, wsUrl, ...auth }) };\n } catch (err) {\n return { error: err instanceof Error ? err.message : String(err) };\n }\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [shop, productKey, placement, wsUrl, authKey]\n );\n const session = 'session' in sessionResult ? sessionResult.session : null;\n const constructError = 'error' in sessionResult ? sessionResult.error : null;\n\n const pushRender = useMemo(() => {\n return (state: RenderState, throttle = throttleMs) => {\n if (!session) return;\n setError(null);\n setIsRendering(true);\n void session.renderState(placement, state, throttle).catch((err) => {\n const message = err instanceof Error ? err.message : String(err);\n setError(message);\n setIsRendering(false);\n onRenderErrorRef.current?.(message);\n });\n };\n }, [session, placement, throttleMs]);\n\n useEffect(() => {\n // Construction fail-fast (caught above) — surface it instead of rendering.\n if (constructError) {\n setError(constructError);\n setIsRendering(false);\n onRenderErrorRef.current?.(constructError);\n return;\n }\n if (!session) return;\n\n session.onMockups((results) => {\n setMockups(results);\n setIsRendering(false);\n onMockupsRef.current?.(results);\n });\n session.onError((message) => {\n setError(message);\n setIsRendering(false);\n onRenderErrorRef.current?.(message);\n });\n\n // Seed the first mockup from the design before any edit, so a freshly\n // mounted embed shows a real mockup immediately (no duplicate seed state —\n // the design is the single source).\n pushRender(design.toServerRequest());\n\n return () => session.close();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [session, constructError]);\n\n // Apply a Buy-owned variant change to the LIVE session (no re-key). The\n // baseline per session is the prop variant it was constructed with; a\n // selection that resolves elsewhere sends `setProduct` (config on the open\n // socket) and re-pushes the CURRENT design state so every Preview updates.\n const appliedVariantRef = useRef<{ session: RenderSession | null; variantId: string | undefined }>({\n session: null,\n variantId: undefined,\n });\n useEffect(() => {\n if (!session || !selectedVariantId) return;\n const applied = appliedVariantRef.current;\n const baseline = applied.session === session ? applied.variantId : product.variantId;\n if (selectedVariantId === baseline) {\n appliedVariantRef.current = { session, variantId: baseline };\n return;\n }\n appliedVariantRef.current = { session, variantId: selectedVariantId };\n session.setProduct({ ...product, variantId: selectedVariantId });\n pushRender(serializeStateForServer(internals.store.getState()));\n // `product` identity is deliberately NOT a dep (embedders pass inline\n // objects); a REAL product change re-keys the session above, which resets\n // the baseline through `applied.session !== session`.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [session, selectedVariantId]);\n\n // Runtime silent-hang backstop. While a render is in flight, arm a timer; if no\n // mockup (or error) lands within SLOW_RENDER_HINT_MS, log an actionable hint.\n // Unlike the mount-time wiring guard this fires ONLY on an actual stall, so it\n // never nags a working embed — and it covers every silent-hang cause, not just\n // missing variantId. Dev-only (the `process` ref is typeof-guarded on the same\n // line); cleared the moment `isRendering` flips false.\n useEffect(() => {\n if (!isRendering) return;\n if (typeof process === 'undefined' || process.env?.NODE_ENV === 'production') return;\n const timer = setTimeout(() => console.warn(slowRenderHint(placement)), SLOW_RENDER_HINT_MS);\n return () => clearTimeout(timer);\n }, [isRendering, placement]);\n\n const value = useMemo<EmbedContextValue>(\n () => ({\n session,\n design,\n placement,\n product,\n mockups,\n isRendering,\n error,\n throttleMs,\n pieceGuides,\n pushRender,\n stateStore: internals.store,\n }),\n [session, design, placement, product, mockups, isRendering, error, throttleMs, pieceGuides, pushRender, internals.store]\n );\n\n // Single validation point for the part registry (ADR-0085 §4). Parts\n // register in their layout effects (so a whole commit's registrations\n // arrive together — no race against the lazy canvas chunk); each change\n // re-renders this component, and validation throws RENDER-side, where\n // Root's boundary reliably contains it (layout-effect throws are not\n // dependably boundary-caught across React 18 + DOM test environments).\n const registryVersion = useSyncExternalStore(\n internals.registry.subscribe,\n internals.registry.getVersion,\n internals.registry.getVersion,\n );\n // eslint-disable-next-line react-hooks/exhaustive-deps\n useMemo(() => internals.registry.validate(), [internals.registry, registryVersion]);\n\n const body = (\n <EditorRootInternalsContext.Provider value={internals}>\n <EmbedContext.Provider value={value}>\n {/* P1 provider inversion (D9: state always, renderer lazy): Root owns\n BOTH provider boundaries — EmbedContext above, and the editor\n document (EditorProvider) here, mounted in EVERY composition.\n Its graph is renderer-free (element/renderer split), CI-gated by\n the import-graph check. `Editor.Canvas`'s inner SnowconeCanvas\n mounts with `externalProvider` and writes into THIS document.\n The bound-layer guard sits ABOVE EditorProvider so the command\n layer can consult the parts registry (E_BOUND_LAYER_MUTATION). */}\n <BoundLayerGuardContext.Provider value={internals.registry}>\n <EditorProvider>{children}</EditorProvider>\n </BoundLayerGuardContext.Provider>\n </EmbedContext.Provider>\n </EditorRootInternalsContext.Provider>\n );\n\n // Only mount a services provider when configured — `<Editor.Canvas>`'s\n // inner SnowconeCanvas inherits it through context.\n if (services) {\n return <CanvasServicesProvider services={services}>{body}</CanvasServicesProvider>;\n }\n return body;\n}\n\n/**\n * The root of an `Editor.*` composition. See the module doc for the state\n * model; see `RealtimeEmbed` for the legacy turnkey wrapper this was\n * extracted from.\n *\n * Stable since ADR-0085 P4 (the default editor is rebuilt from this public\n * surface, CI-gated); additive-only from here.\n */\nexport function EditorRoot(props: EditorRootProps): React.ReactElement {\n const { design, product } = props;\n\n // One store + registry per (design) — remounting with a new design reseeds.\n // The commerce store is keyed on the PRODUCT's identity instead (a new\n // product or a host-driven `variantId` prop change reseeds the selection;\n // design edits never touch it).\n const productIdentity = `${product.productId}|${product.variantId ?? ''}`;\n const internalsRef = useRef<{ design: AnyDesign; internals: Omit<EditorRootInternals, 'reportInvariant' | 'reportRuntimeError' | 'commerce'> } | null>(null);\n const commerceRef = useRef<{ productIdentity: string; commerce: CommerceStateStore } | null>(null);\n const [reportedError, setReportedError] = useState<EditorError | null>(null);\n if (internalsRef.current === null || internalsRef.current.design !== design) {\n internalsRef.current = {\n design,\n internals: {\n store: new DesignStateStore(design.toJSON()),\n registry: new EditorPartsRegistry(),\n },\n };\n }\n if (commerceRef.current === null || commerceRef.current.productIdentity !== productIdentity) {\n commerceRef.current = { productIdentity, commerce: new CommerceStateStore(product) };\n }\n\n const internals = useMemo<EditorRootInternals>(\n () => ({\n ...internalsRef.current!.internals,\n commerce: commerceRef.current!.commerce,\n ...makeInvariantReporter(setReportedError),\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [internalsRef.current.internals, commerceRef.current.commerce]\n );\n\n return (\n // `display: contents` — the .sc-root scope without a layout box, so the\n // host's grid/flex sees the parts directly (and the legacy RealtimeEmbed\n // wrapper, which had no DOM at all, stays layout-identical).\n <div className=\"sc-root\" style={{ display: 'contents' }} data-sc-part=\"root\">\n <EditorBoundary reportedError={reportedError} onRetry={() => setReportedError(null)}>\n <EditorRootInner {...props} internals={internals} />\n </EditorBoundary>\n </div>\n );\n}\n","'use client';\n\n/**\n * `<Editor.Canvas>` — the editable artboard, and the ONE lazy boundary of the\n * primitives (D9): all state mounts with `Editor.Root`; the heavy rendering\n * engine lives in {@link EditorCanvasImpl}'s chunk and loads only when this\n * part mounts. A no-canvas composition (Preview + TextField + Buy) never\n * fetches it — CI-asserted by the import-graph check.\n *\n * A failed chunk load (network/CDN) is a RUNTIME failure, not a composition\n * mistake: it routes to Root's error card with a retry affordance\n * (`E_CHUNK_LOAD_FAILED`) in every env. Retry clears the card, which remounts\n * this part and re-attempts the import.\n */\n\nimport React, { forwardRef, useEffect, useId, useLayoutEffect, useState, type CSSProperties, type ReactNode } from 'react';\nimport { EditorError } from '../../errors/editorError.js';\nimport { useEditorRootInternals } from './RootInternals.js';\nimport type { EditorCanvasImplProps } from './EditorCanvasImpl.js';\nimport type { SnowconeCanvasHandle } from '../embed/SnowconeCanvas.js';\n\ntype ImplComponent = (typeof import('./EditorCanvasImpl.js'))['EditorCanvasImpl'];\n\nlet implLoader: () => Promise<ImplComponent> = () =>\n import('./EditorCanvasImpl.js').then((m) => m.EditorCanvasImpl);\n\n/** Load the heavy impl chunk. Exposed for the legacy `<RealtimeCanvas>`\n * wrapper so both share ONE lazy boundary (one chunk). @internal */\nexport function loadCanvasImpl(): Promise<ImplComponent> {\n return implLoader();\n}\n\n/** Swap the chunk loader — TEST-ONLY seam for the chunk-load-failure → error\n * card → retry contract (a real `import()` can't be made to fail once and\n * then succeed under the module cache). Returns a restore function.\n * @internal */\nexport function __setCanvasImplLoaderForTests(loader: () => Promise<ImplComponent>): () => void {\n const previous = implLoader;\n implLoader = loader;\n return () => {\n implLoader = previous;\n };\n}\n\nexport interface EditorCanvasProps {\n /** Your overlay controls — rendered inside the editor context, so the\n * binding hooks (`useTextBinding` …) resolve against live elements. */\n children?: ReactNode;\n /** Cap the canvas height in px. */\n maxHeight?: number;\n className?: string;\n style?: CSSProperties;\n}\n\n/**\n * The editable artboard. Mount at most one under a Root\n * (`E_DUPLICATE_CANVAS`); mount none for the no-canvas personalization\n * composition.\n *\n * Stable since ADR-0085 P4 (the default editor is rebuilt from this public\n * surface, CI-gated); additive-only from here.\n */\nexport const EditorCanvas = forwardRef<SnowconeCanvasHandle, EditorCanvasProps>(function EditorCanvas(\n { children, maxHeight, className, style }: EditorCanvasProps,\n ref,\n): React.ReactElement {\n const internals = useEditorRootInternals('Editor.Canvas');\n const instanceId = useId();\n\n // Registration is by THIS component's mount, not the chunk's arrival — so\n // duplicate detection and requires-canvas validation never race the lazy\n // load (ADR-0085 §4).\n useLayoutEffect(() => {\n return internals.registry.registerCanvas(instanceId);\n }, [internals.registry, instanceId]);\n\n const [Impl, setImpl] = useState<ImplComponent | null>(null);\n useEffect(() => {\n let cancelled = false;\n loadCanvasImpl().then(\n (component) => {\n if (!cancelled) setImpl(() => component);\n },\n (err) => {\n if (cancelled) return;\n internals.reportRuntimeError(\n new EditorError(\n 'E_CHUNK_LOAD_FAILED',\n `the editor's rendering chunk failed to load (${err instanceof Error ? err.message : String(err)}). ` +\n 'This is a network/CDN failure, not a composition mistake — retry, or check the deployment ' +\n 'serves the @snowcone-app/canvas lazy chunks.',\n { cause: err instanceof Error ? err.message : String(err), docSlug: 'embed-mode' },\n ),\n );\n },\n );\n return () => {\n cancelled = true;\n };\n }, [internals]);\n\n if (!Impl) {\n // Lightweight placeholder while the chunk loads — keeps the host layout\n // stable; themed via .sc-root tokens like every part.\n return (\n <div\n data-sc-part=\"canvas\"\n data-sc-state=\"loading\"\n className={className}\n style={{ minHeight: maxHeight ?? 200, ...style }}\n aria-busy=\"true\"\n />\n );\n }\n\n return (\n // `builtinControls`: the canvas owns the floating contextual toolbar\n // unless a docked <Editor.Controls> is mounted (ADR-0085 §5). Only here —\n // the legacy <RealtimeCanvas> wrapper stays chrome-less.\n <Impl ref={ref} kit=\"embed-only\" partAttr=\"canvas\" builtinControls maxHeight={maxHeight} className={className} style={style}>\n {children}\n </Impl>\n );\n});\n\nexport type { EditorCanvasImplProps };\n","'use client';\n\n/**\n * `<Editor.Preview>` — the live product mockup (the buyable thing), extracted\n * from the legacy `<RealtimeMockup>` (which now wraps this).\n *\n * Reads the shared session's mockups from context and renders the rendered\n * image, updating as the shopper edits. Because every Preview shares one\n * session with the rest of the composition, it can never desync — and\n * MULTIPLE Previews under one Root are explicitly VALID (front/back; mockup\n * scenes via `mockupId`). Canvas-free by design: the no-canvas\n * personalization widget is Preview + TextField + Buy.\n */\n\nimport React, { useRef, type CSSProperties, type ReactNode, type SyntheticEvent } from 'react';\nimport { useEmbedContext } from '../embed-realtime/context.js';\n\nexport interface EditorPreviewProps {\n /** Which mockup scene to show (a `product.mockupIds` entry). Defaults to the\n * first mockup that has rendered. */\n mockupId?: string;\n /** Shown before the first mockup arrives / while a render is in flight with no\n * prior image. Defaults to nothing. */\n fallback?: ReactNode;\n /** Alt text for the rendered image. */\n alt?: string;\n className?: string;\n style?: CSSProperties;\n}\n\n/**\n * How far the displayed device-pixel width may exceed the delivered mockup's\n * natural width before {@link resolutionMismatchHint} fires. Renders default to\n * 1000px wide, so a 1000px image inside a ~1100 device-px slot is fine (browser\n * downscale slack), but stretched across 2000 device px it looks soft and the\n * developer deserves to hear why.\n */\nexport const RESOLUTION_MISMATCH_RATIO = 1.2;\n\n/**\n * The render-width ladder a mismatch suggestion rounds UP to. Mirrors the\n * `product.width` guidance (\"bump to ~2000 for a crisp preview\") with sensible\n * steps — suggesting the exact device-px count would invite over-precise\n * configs that re-trigger on the next viewport.\n */\nconst SUGGESTED_WIDTHS = [1200, 1400, 1600, 1800, 2000, 2500, 3000, 4000] as const;\n\n/** Rounds a device-pixel width up to the next {@link SUGGESTED_WIDTHS} step\n * (capped at the top step). */\nexport function suggestRenderWidth(devicePx: number): number {\n for (const step of SUGGESTED_WIDTHS) {\n if (step >= devicePx) return step;\n }\n return SUGGESTED_WIDTHS[SUGGESTED_WIDTHS.length - 1];\n}\n\n/**\n * Builds the dev-console warning shown when a delivered mockup's natural width\n * is meaningfully below the width it's displayed at in DEVICE pixels (CSS width\n * × `devicePixelRatio`) — the \"my preview looks soft and nothing says why\"\n * trap: renders default to 1000px wide, which blurs on a large or high-density\n * display. Returns `null` when the resolution is adequate (within\n * {@link RESOLUTION_MISMATCH_RATIO}) or either measurement is unusable.\n */\nexport function resolutionMismatchHint(naturalWidth: number, devicePx: number): string | null {\n if (!(naturalWidth > 0) || !(devicePx > 0)) return null;\n if (devicePx <= naturalWidth * RESOLUTION_MISMATCH_RATIO) return null;\n const suggestion = suggestRenderWidth(devicePx);\n return (\n `[RealtimeMockup] mockup rendered at ${naturalWidth}px but displayed at ` +\n `~${devicePx} device px — the preview will look soft. Pass ` +\n `\\`product.width\\` (e.g. ${suggestion}) on the embed for a crisp preview.`\n );\n}\n\n/**\n * The live product mockup. Mount as many as you need under one Root.\n *\n * Stable since ADR-0085 P4 (the default editor is rebuilt from this public\n * surface, CI-gated); additive-only from here.\n */\nexport function EditorPreview({\n mockupId,\n fallback = null,\n alt = 'Live product mockup',\n className,\n style,\n}: EditorPreviewProps): React.ReactElement {\n const { mockups, error } = useEmbedContext();\n\n // Mockup ids already warned about this mount — re-renders and repeated loads\n // of the same scene stay quiet; a different scene gets its own one warning.\n const warnedMockupIdsRef = useRef<Set<string>>(new Set());\n\n const result = mockupId\n ? mockups.find((m) => m.mockupId === mockupId && m.imageUrl)\n : mockups.find((m) => m.imageUrl);\n\n if (!result?.imageUrl) {\n // A render/grant/transport failure with nothing to show must SURFACE, not\n // blank (ADR-0085 failure-modes table: \"error state, no silent blank\").\n // Machine-readable for agents; hosts style or replace it via the\n // `data-sc-part` hook. Once a mockup exists we keep showing it (stale\n // beats blank) and the failure stays on the session's onRenderError.\n if (error) {\n return (\n <div data-sc-part=\"preview-error\" role=\"alert\" data-sc-error={error} className={className} style={style}>\n {fallback ?? `Render failed: ${error}`}\n </div>\n );\n }\n return <>{fallback}</>;\n }\n\n // Dev-only resolution check (the `process` reference is typeof-guarded on the\n // same line — non-Node bundlers don't define it). Runs on load because only a\n // decoded image knows its natural width; skips SSR (no `window`) and\n // unmeasurable (zero-width) elements.\n const handleLoad = (event: SyntheticEvent<HTMLImageElement>) => {\n if (typeof process === 'undefined' || process.env?.NODE_ENV === 'production') return;\n if (typeof window === 'undefined') return;\n if (warnedMockupIdsRef.current.has(result.mockupId)) return;\n const img = event.currentTarget;\n const cssWidth = img.getBoundingClientRect().width;\n if (cssWidth <= 0) return;\n const devicePx = Math.round(cssWidth * (window.devicePixelRatio || 1));\n const hint = resolutionMismatchHint(img.naturalWidth, devicePx);\n if (hint) {\n warnedMockupIdsRef.current.add(result.mockupId);\n console.warn(hint);\n }\n };\n\n return (\n // eslint-disable-next-line @next/next/no-img-element\n <img\n data-sc-part=\"preview\"\n src={result.imageUrl}\n alt={alt}\n className={className}\n style={style}\n onLoad={handleLoad}\n />\n );\n}\n","'use client';\n\n/**\n * `<Editor.TextField>` — a form input bound to a design text layer by TYPED\n * TOKEN (ADR-0085 §1 / T1). Canvas-free by design: in the no-canvas\n * personalization widget it writes the Root's design state directly and the\n * preview re-renders live; with a mounted `Editor.Canvas` the same writes\n * route through the editor command path (undo/redo, repaint) via the canvas\n * bridge — the editor document stays the single write authority (§3). The\n * routing is internal; the API is identical in both compositions.\n *\n * Contract (D10):\n * - `layer` accepts ONLY a `design.layer(\"name\")` token — a bare string\n * throws `E_LAYER_TOKEN_REQUIRED` (today's silent no-op binding became a\n * throw when entering `Editor.*`).\n * - Mount-time revalidation is the authority: the token's name is re-resolved\n * against the mounted Root's CURRENT design state — a token minted from a\n * different design throws `E_LAYER_NOT_FOUND` (dev AND prod).\n * - Mounted + non-`optional` ⇒ required for `Editor.Buy` completeness\n * (non-empty after trim AND differs from seed — C2/C3); unmounted (incl.\n * conditionally hidden) ⇒ not required. Registration lives in Root context.\n * - Reconciliation with canvas edits of the same layer is by construction:\n * one store, last-write-wins; this is a controlled input subscribed to the\n * store, so a canvas edit updates the field.\n */\n\nimport React, { useCallback, useId, useLayoutEffect, useRef, useSyncExternalStore, type CSSProperties } from 'react';\nimport { serializeStateForServer } from '../../rendering/serialize-for-server.js';\nimport { isLayerToken, type LayerToken } from '../../design/design-builder.js';\nimport { EditorError } from '../../errors/editorError.js';\nimport { useEmbedContext } from '../embed-realtime/context.js';\nimport { useEditorRootInternals } from './RootInternals.js';\n\nexport interface EditorTextFieldProps {\n /** The text layer this input edits — mint with `design.layer(\"name\")`.\n * Type-checked against the design's TEXT-layer names when the design is\n * statically built; runtime-validated always. */\n layer: LayerToken<'text'>;\n /** Marked optional ⇒ Buy completeness does not require it (C2/C3). */\n optional?: boolean;\n placeholder?: string;\n /** Accessible label. Defaults to the layer name. */\n 'aria-label'?: string;\n className?: string;\n style?: CSSProperties;\n}\n\n/**\n * A text input bound to a design layer. Works with or without a mounted\n * `Editor.Canvas`.\n *\n * Stable since ADR-0085 P4 (the default editor is rebuilt from this public\n * surface, CI-gated); additive-only from here.\n */\nexport function EditorTextField(props: EditorTextFieldProps): React.ReactElement {\n const { layer, optional = false, placeholder, className, style } = props;\n const internals = useEditorRootInternals('Editor.TextField');\n const { pushRender, throttleMs, stateStore } = useEmbedContext();\n const instanceId = useId();\n\n // ── Token + MOUNT-time revalidation (render-time on purpose: a bad layer\n // prop is a composition mistake → Root's boundary, dev AND prod). Validated\n // once per layer name, against the state AT MOUNT — later state churn (the\n // user emptying the canvas, teardown ordering) is user state, not a\n // composition mistake; the write path reports it if a write ever misses. ──\n const validatedNameRef = useRef<string | null>(null);\n if (!isLayerToken(layer)) {\n throw new EditorError(\n 'E_LAYER_TOKEN_REQUIRED',\n `the \\`layer\\` prop must be a token minted by the design — pass ` +\n `layer={design.layer(\"name\")}, not ${typeof layer === 'string' ? `the bare string \"${layer}\"` : 'a plain value'}. ` +\n `Tokens validate the name against the design's layers at mint time.`,\n { received: typeof layer === 'string' ? layer : typeof layer, docSlug: 'embed-mode' },\n );\n }\n if (validatedNameRef.current !== layer.name) {\n const kindNow = stateStore.layerKindOf(layer.name);\n if (kindNow === undefined) {\n throw new EditorError(\n 'E_LAYER_NOT_FOUND',\n `no layer \"${layer.name}\" in this Root's design — the token was minted from a ` +\n `different design than the one passed to <Editor.Root design={…}>. Bindable layers ` +\n `here: ${JSON.stringify(stateStore.bindableLayerNames())}.`,\n { layerName: layer.name, validNames: stateStore.bindableLayerNames(), docSlug: 'embed-mode' },\n );\n }\n if (kindNow !== 'text') {\n throw new EditorError(\n 'E_LAYER_WRONG_KIND',\n `layer \"${layer.name}\" is ${kindNow === null ? 'not a bindable kind' : `an ${kindNow} layer`} — ` +\n `<Editor.TextField> binds text layers only.`,\n { layerName: layer.name, actualKind: kindNow, docSlug: 'embed-mode' },\n );\n }\n validatedNameRef.current = layer.name;\n }\n\n // ── Required-layer registration for Buy completeness (C2/C3) ─────────────\n useLayoutEffect(() => {\n return internals.registry.registerTextField(instanceId, { name: layer.name, optional });\n }, [internals.registry, instanceId, layer.name, optional]);\n\n // ── Controlled value from the ONE store (a canvas edit updates the field) ─\n const value = useSyncExternalStore(\n stateStore.subscribe,\n () => stateStore.textOf(layer.name) ?? '',\n () => stateStore.textOf(layer.name) ?? '',\n );\n\n const handleChange = useCallback(\n (event: React.ChangeEvent<HTMLInputElement>) => {\n const next = event.target.value;\n const bridge = internals.registry.getCanvasBridge();\n if (bridge) {\n // Canvas mounted: the editor document is the write authority — route\n // through commands; the canvas onChange lands the new state back in\n // the store and pushes the render.\n if (!bridge.setTextByName(layer.name, next)) {\n internals.reportInvariant(\n new EditorError(\n 'E_LAYER_NOT_FOUND',\n `layer \"${layer.name}\" no longer exists in the mounted canvas — it was removed ` +\n `or renamed after this <Editor.TextField> bound to it. Bound layers must not be ` +\n `renamed or deleted while a field is mounted (ADR-0085 §3).`,\n { layerName: layer.name, docSlug: 'embed-mode' },\n ),\n );\n }\n return;\n }\n // No canvas: the store IS the authority. Trailing-edge throttle in the\n // session keeps the last keystroke always rendering.\n stateStore.updateTextLayer(layer.name, next);\n pushRender(serializeStateForServer(stateStore.getState()), throttleMs);\n },\n [internals, layer.name, stateStore, pushRender, throttleMs],\n );\n\n return (\n <input\n data-sc-part=\"textfield\"\n data-sc-layer={layer.name}\n type=\"text\"\n value={value}\n onChange={handleChange}\n placeholder={placeholder}\n aria-label={props['aria-label'] ?? layer.name}\n className={className}\n style={style}\n />\n );\n}\n","'use client';\n\n/**\n * `<Editor.Buy>` — the SMART commerce part (ADR-0085 §2; plan decision: thin\n * callback-Buy was rejected). OWNS variant selection + quantity (P2 — they\n * live in the Root's commerce store, host-visible via `useProductSelection()`,\n * never on Root props where a change would re-key the RenderSession), runs\n * design-completeness validation, and assembles the cart payload; only the\n * final submit is the host's callback — their one line.\n *\n * Completeness rules (v1, C1–C5):\n * - C1 variant resolution — FULL selection resolution (the P2 amendment:\n * `validateProductSelection`/`findBestCombination` replace the old\n * color-axis-only gate). Each unselected required attribute gates with\n * reason `option:<key>`; a complete-but-invalid combination gates with\n * reason `variant`.\n * - C2 every MOUNTED non-`optional` `Editor.TextField` layer non-empty\n * after trim.\n * - C3 those layers must DIFFER from their seed value (F4 — placeholder\n * text like 'YOUR NAME' must not pass).\n * - C4 the design has ≥1 renderable element.\n * - C5 quantity is an integer ≥ 1.\n *\n * Incompleteness is USER state, not a composition error — the button renders\n * disabled with machine-readable `data-sc-buy-state` / `data-sc-buy-missing`\n * reason codes; it never throws. Throws are reserved for composition\n * violations (`E_BUY_NO_PRODUCT`, outside-Root, `E_UNKNOWN_OPTION`).\n *\n * The payload is assembled from DESIGN STATE (the Root's live store — never\n * the seed, never rendered pixels) plus the COMMERCE state (selection,\n * resolved variant, quantity), so render staleness cannot corrupt an order;\n * the preview is just preview (D10).\n */\n\nimport React, { useCallback, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type CSSProperties, type ReactNode } from 'react';\nimport {\n createCartDetail,\n type CartDetail,\n type OptionSelection,\n type RenderProduct,\n} from '@snowcone-app/sdk';\nimport { serializeStateForServer, type ServerRenderRequest } from '../../rendering/serialize-for-server.js';\nimport { EditorError } from '../../errors/editorError.js';\nimport { useEmbedContext } from '../embed-realtime/context.js';\nimport type { DesignState } from './designStateStore.js';\nimport { choiceLabelsOf, type CommerceStateStore } from './commerceStore.js';\nimport { useEditorRootInternals } from './RootInternals.js';\n\n/** A structured incompleteness reason — also serialized (comma-joined) into\n * the button's `data-sc-buy-missing` attribute for agents and styling. */\nexport type BuyMissingReason =\n | `option:${string}`\n | 'variant'\n | `layer:${string}`\n | `layer-seed:${string}`\n | 'empty-design'\n | 'quantity';\n\nexport interface EditorBuyPayload {\n productId: string;\n /** The variant (gvid) the selection resolves to. */\n variantId?: string;\n quantity: number;\n /** The variant choices at click time, e.g. `{ Color: 'Black', Size: 'M' }`. */\n selection: OptionSelection;\n /** SDK cart detail (variant resolution + price) when the product carries\n * catalog `options`; `null` for option-less products. */\n cartDetail: CartDetail | null;\n /** The DESIGN STATE at click time (editor shape) — persist this; it is the\n * re-renderable source of truth for the purchased design. */\n designState: DesignState;\n /** The same state serialized for the server render path. */\n serverRequest: ServerRenderRequest;\n}\n\nexport interface EditorBuyProps {\n /** The final submit — the host's one line. Everything before it (variant,\n * quantity, completeness, payload assembly) is this part's job. */\n onAddToCart: (payload: EditorBuyPayload) => void | Promise<void>;\n /**\n * Seeds the Buy-owned quantity once on mount (integer ≥ 1; the store\n * defaults to 1). Live reads/writes go through `useProductSelection()` —\n * this is deliberately NOT a controlled prop, so two Buy parts under one\n * Root can never disagree about quantity.\n */\n defaultQuantity?: number;\n /** Button label. Defaults to \"Add to cart\". */\n children?: ReactNode;\n className?: string;\n style?: CSSProperties;\n}\n\n/** Pure completeness evaluation — exported for tests. @internal */\nexport function evaluateBuyCompleteness(input: {\n quantity: number;\n /** Required attribute keys still unselected (C1 — `option:<key>`). */\n missingOptionKeys: string[];\n /** Full-resolution validity of the selection (C1 — `variant`). */\n selectionValid: boolean;\n textFields: Array<{ name: string; optional: boolean }>;\n textOf: (name: string) => string | undefined;\n seedTextOf: (name: string) => string | undefined;\n hasRenderableElement: boolean;\n}): BuyMissingReason[] {\n const missing: BuyMissingReason[] = [];\n\n // C1 — full selection resolution (P2 amendment). Unselected axes first;\n // `variant` only for a complete selection that matches no combination.\n for (const key of input.missingOptionKeys) {\n missing.push(`option:${key}`);\n }\n if (input.missingOptionKeys.length === 0 && !input.selectionValid) {\n missing.push('variant');\n }\n\n // C2 + C3 — mounted required TextField layers.\n for (const field of input.textFields) {\n if (field.optional) continue;\n const value = (input.textOf(field.name) ?? '').trim();\n if (value.length === 0) {\n missing.push(`layer:${field.name}`);\n continue;\n }\n const seed = (input.seedTextOf(field.name) ?? '').trim();\n if (seed.length > 0 && value === seed) {\n missing.push(`layer-seed:${field.name}`);\n }\n }\n\n // C4 — something to print.\n if (!input.hasRenderableElement) {\n missing.push('empty-design');\n }\n\n // C5 — sane quantity.\n if (!Number.isInteger(input.quantity) || input.quantity < 1) {\n missing.push('quantity');\n }\n\n return missing;\n}\n\n/** Assemble the SDK cart detail from the commerce store's selection. */\nfunction buildCartDetail(product: RenderProduct, commerce: CommerceStateStore): CartDetail | null {\n const combinations = commerce.getCombinations();\n const attributes = commerce.getAttributes();\n if (Object.keys(attributes).length === 0 || combinations.length === 0) return null;\n\n // createCartDetail's selection math speaks label-string choices (the SDK\n // currency); the store hands out object choices — convert.\n const stringAttrs: Parameters<typeof createCartDetail>[0]['attributes'] = Object.fromEntries(\n Object.entries(attributes).map(([key, attr]) => [key, { ...attr, choices: choiceLabelsOf(attr) }]),\n );\n\n return createCartDetail({\n productId: product.productId,\n quantity: commerce.getQuantity(),\n selection: commerce.getSelection(),\n combinations: combinations as Parameters<typeof createCartDetail>[0]['combinations'],\n attributes: stringAttrs,\n });\n}\n\n/**\n * The add-to-cart button, completeness-gated and payload-assembling.\n *\n * Stable since ADR-0085 P4 (the default editor is rebuilt from this public\n * surface, CI-gated); additive-only from here.\n */\nexport function EditorBuy(props: EditorBuyProps): React.ReactElement {\n const { onAddToCart, defaultQuantity, children, className, style } = props;\n const internals = useEditorRootInternals('Editor.Buy');\n const { product, stateStore } = useEmbedContext();\n const commerce = internals.commerce;\n\n // Composition violation — not user state: throw into Root's boundary.\n if (!product?.productId) {\n throw new EditorError(\n 'E_BUY_NO_PRODUCT',\n '<Editor.Buy> has no product context — pass `product` (with `productId`) on ' +\n '<Editor.Root product={…}>. Buy assembles its cart payload from the Root product ' +\n 'and the live design state.',\n { docSlug: 'embed-mode' },\n );\n }\n\n // Seed the Buy-owned quantity once per mount (the prop is a seed, not a\n // controlled value — see the prop doc).\n const seededRef = useRef(false);\n useLayoutEffect(() => {\n if (seededRef.current) return;\n seededRef.current = true;\n if (typeof defaultQuantity === 'number') commerce.setQuantity(defaultQuantity);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [commerce]);\n\n // Subscribe narrowly: design state + commerce state + part registry.\n const stateVersion = useSyncExternalStore(stateStore.subscribe, stateStore.getState, stateStore.getState);\n const commerceVersion = useSyncExternalStore(commerce.subscribe, commerce.getVersion, commerce.getVersion);\n const registryVersion = useSyncExternalStore(\n internals.registry.subscribe,\n internals.registry.getVersion,\n internals.registry.getVersion,\n );\n\n const quantity = commerce.getQuantity();\n const missing = useMemo(\n () =>\n evaluateBuyCompleteness({\n quantity,\n missingOptionKeys: commerce.missingOptionKeys(),\n selectionValid: commerce.selectionValid(),\n textFields: internals.registry.getTextFields(),\n textOf: (name) => stateStore.textOf(name),\n seedTextOf: (name) => stateStore.seedTextOf(name),\n hasRenderableElement: stateStore.hasRenderableElement(),\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [commerce, quantity, stateVersion, commerceVersion, registryVersion],\n );\n const complete = missing.length === 0;\n\n // Double-click inert: the callback fires exactly once per click while\n // assembling/submitting (P2 test contract).\n const [busy, setBusy] = useState(false);\n const busyRef = useRef(false);\n\n const handleClick = useCallback(() => {\n if (busyRef.current || !complete) return;\n busyRef.current = true;\n setBusy(true);\n\n const designState = stateStore.getState();\n const variantId = commerce.resolvedVariantId();\n const payload: EditorBuyPayload = {\n productId: product.productId,\n ...(variantId ? { variantId } : {}),\n quantity: commerce.getQuantity(),\n selection: commerce.getSelection(),\n cartDetail: buildCartDetail(product, commerce),\n designState,\n serverRequest: serializeStateForServer(designState),\n };\n\n // Invoke synchronously (predictable for hosts and tests); only the\n // SETTLING of an async callback is awaited for the busy window.\n let result: void | Promise<void>;\n try {\n result = onAddToCart(payload);\n } catch (err) {\n busyRef.current = false;\n setBusy(false);\n throw err;\n }\n void Promise.resolve(result).finally(() => {\n busyRef.current = false;\n setBusy(false);\n });\n }, [complete, product, commerce, stateStore, onAddToCart]);\n\n return (\n <button\n type=\"button\"\n data-sc-part=\"buy\"\n data-sc-buy-state={busy ? 'busy' : complete ? 'ready' : 'incomplete'}\n data-sc-buy-missing={missing.join(',') || undefined}\n disabled={!complete || busy}\n aria-busy={busy || undefined}\n onClick={handleClick}\n className={className}\n style={style}\n >\n {children ?? 'Add to cart'}\n </button>\n );\n}\n","'use client';\n\n/**\n * `<Editor.Controls>` — the morphing contextual zone, ONE coarse part in v1\n * (ADR-0085 §5). Wraps the existing `ContextualToolbars` chrome:\n *\n * - `placement=\"docked\"` (default): the host-docked (class-1) contextual\n * zone, rendered exactly where the host mounts it — today's\n * `ContextualToolbars` embedded mode. Mounting a docked Controls\n * SUPPRESSES the canvas's built-in floating toolbar (one contextual zone\n * at a time), via the part registry.\n * - `placement=\"floating\"`: renders nothing in place and declares the\n * class-3 floating body-portal variant explicitly — the built-in floating\n * toolbar that `Editor.Canvas` mounts by default stays active.\n * - No `Editor.Controls` mounted at all: `Editor.Canvas` defaults to the\n * floating toolbar.\n *\n * Requires a mounted `Editor.Canvas` (`E_REQUIRES_CANVAS`, ADR-0085 §4): the\n * zone morphs on canvas selection; no selection exists without a canvas.\n *\n * The chrome itself statically imports the paint pipeline (panels, effects),\n * so the docked impl loads through a dynamic import — this module's static\n * graph stays renderer-free (import-graph gate), and in any valid\n * composition the renderer is already loading behind `Editor.Canvas`'s\n * boundary. A failed chrome chunk load routes to Root's error card with\n * retry (`E_CHUNK_LOAD_FAILED`), exactly like the canvas chunk.\n */\n\nimport React, { useEffect, useId, useLayoutEffect, useState, type CSSProperties } from 'react';\nimport { EditorError } from '../../errors/editorError.js';\nimport { useEditorRootInternals, useRequiresCanvas } from './RootInternals.js';\n\ntype ControlsImpl = (typeof import('../ContextualToolbars.js'))['ContextualToolbars'];\n\nexport interface EditorControlsProps {\n /** Where the contextual zone lives (ADR-0085 §5). The host docks the part\n * by where it renders it — there is deliberately no \"bottom\"/\"top\" value. */\n placement?: 'docked' | 'floating';\n className?: string;\n style?: CSSProperties;\n}\n\n/**\n * The contextual controls zone.\n *\n * Stable since ADR-0085 P4 (the default editor is rebuilt from this public\n * surface, CI-gated); additive-only from here.\n */\nexport function EditorControls({\n placement = 'docked',\n className,\n style,\n}: EditorControlsProps): React.ReactElement | null {\n const internals = useEditorRootInternals('Editor.Controls');\n useRequiresCanvas('Editor.Controls');\n const instanceId = useId();\n\n // Registration is by THIS component's mount (layout effect, like every\n // part) — suppression of the built-in floating toolbar never races the\n // chrome chunk's arrival.\n useLayoutEffect(\n () => internals.registry.registerControls(instanceId, placement),\n [internals.registry, instanceId, placement],\n );\n\n const docked = placement === 'docked';\n const [Impl, setImpl] = useState<ControlsImpl | null>(null);\n useEffect(() => {\n if (!docked) return;\n let cancelled = false;\n import('../ContextualToolbars.js').then(\n (m) => {\n if (!cancelled) setImpl(() => m.ContextualToolbars);\n },\n (err) => {\n if (cancelled) return;\n internals.reportRuntimeError(\n new EditorError(\n 'E_CHUNK_LOAD_FAILED',\n `the editor's controls chunk failed to load (${err instanceof Error ? err.message : String(err)}). ` +\n 'This is a network/CDN failure, not a composition mistake — retry, or check the deployment ' +\n 'serves the @snowcone-app/canvas lazy chunks.',\n { cause: err instanceof Error ? err.message : String(err), docSlug: 'embed-mode' },\n ),\n );\n },\n );\n return () => {\n cancelled = true;\n };\n }, [docked, internals]);\n\n if (!docked) {\n // The floating variant is the canvas's built-in body portal (class-3) —\n // this part only declares it; there is nothing to render in place.\n return null;\n }\n\n return (\n <div\n data-sc-part=\"controls\"\n data-sc-placement=\"docked\"\n className={className}\n style={style}\n aria-busy={Impl ? undefined : 'true'}\n >\n {Impl ? <Impl mode=\"embedded\" /> : null}\n </div>\n );\n}\n","'use client';\n\n/**\n * `useProductSelection()` — the host's window into `Editor.Buy`'s commerce\n * state (ADR-0085 §2, P2: Buy-owned variant + quantity).\n *\n * The DIVISION OF LABOR (the rendering contract): the HOST renders the\n * variant-selection UI — swatches, dropdowns, steppers, its brand — and this\n * hook supplies the state + transitions. `Editor.Buy` owns that state: it\n * gates completeness on it (C1/C5) and assembles the cart payload from it.\n * Neither side ever touches Root props for selection, so picking a color\n * costs one live config message + one render — never a session re-key.\n *\n * ```tsx\n * function VariantPicker() {\n * const { attributes, selection, select, disabledChoices } = useProductSelection();\n * // choices are ALWAYS `{ label, hex? }` objects; the label STRING is the\n * // currency for select()/selection/disabledChoices.\n * return Object.entries(attributes).map(([key, attr]) => (\n * <div key={key}>\n * {attr.choices.map(({ label = '', hex }) => (\n * <button\n * key={label}\n * style={hex ? { background: hex } : undefined}\n * disabled={disabledChoices[key]?.includes(label)}\n * aria-pressed={selection[key] === label}\n * onClick={() => select(key, label)}\n * >\n * {label}\n * </button>\n * ))}\n * </div>\n * ));\n * }\n * ```\n *\n * Mount it anywhere under the same `<Editor.Root>` (outside one throws\n * `E_OUTSIDE_ROOT`). `select()` with an unknown key/choice throws structured\n * `E_UNKNOWN_OPTION` listing the valid ones (D4/E3 — wiring mistakes are\n * loud, not silently ignored).\n */\n\nimport { useCallback, useMemo, useSyncExternalStore } from 'react';\nimport type { OptionSelection } from '@snowcone-app/sdk';\nimport type { ProductSelectionAttribute } from './commerceStore.js';\nimport { useEditorRootInternals } from './RootInternals.js';\n\nexport interface ProductSelectionApi {\n /** The product's variant attributes (normalized catalog `options.attributes`).\n * Choices are ALWAYS `{ label, hex?, … }` OBJECTS — render `choice.label`,\n * use `hex` for color swatches. Empty object for an option-less product. */\n attributes: Record<string, ProductSelectionAttribute>;\n /** Current choices BY LABEL STRING, e.g. `{ Color: 'Black', Size: 'M' }` —\n * the label is the currency everywhere selection is read or written.\n * Seeded from the Root product's `variantId` combination when present. */\n selection: OptionSelection;\n /** Select a choice by its LABEL string (`select('Color', choice.label)`).\n * Unknown key/choice → throws `E_UNKNOWN_OPTION` listing the valid ones. */\n select: (key: string, choice: string) => void;\n /** Choice LABELS invalid given the rest of the selection — disable these. */\n disabledChoices: Record<string, string[]>;\n /** The variant (gvid) the selection resolves to; `undefined` while\n * incomplete/invalid. This is what renders and what Buy submits. */\n variantId: string | undefined;\n /** Resolved combination's price, when the catalog carries one. */\n price: number | undefined;\n /** Buy-owned quantity (completeness rule C5 gates on it). */\n quantity: number;\n /** Set the Buy-owned quantity. Values that are not integers ≥ 1 are stored\n * as-is and GATE Buy with the `quantity` reason code (user state, never a\n * throw) — clamp in your stepper if you never want that state. */\n setQuantity: (quantity: number) => void;\n /** True when every required attribute is selected and the combination is\n * valid — the C1 component of Buy's completeness. */\n complete: boolean;\n /** Required attribute keys still unselected (Buy's `option:<key>` codes). */\n missing: string[];\n}\n\n/**\n * Read/write the Buy-owned product selection under this `Editor.Root`.\n *\n * Stable since ADR-0085 P4 (the default editor is rebuilt from this public\n * surface, CI-gated); additive-only from here.\n */\nexport function useProductSelection(): ProductSelectionApi {\n const internals = useEditorRootInternals('useProductSelection');\n const commerce = internals.commerce;\n\n const version = useSyncExternalStore(commerce.subscribe, commerce.getVersion, commerce.getVersion);\n\n const select = useCallback((key: string, choice: string) => commerce.select(key, choice), [commerce]);\n const setQuantity = useCallback((quantity: number) => commerce.setQuantity(quantity), [commerce]);\n\n return useMemo<ProductSelectionApi>(\n () => ({\n attributes: commerce.getAttributes(),\n selection: commerce.getSelection(),\n select,\n disabledChoices: commerce.disabledChoices(),\n variantId: commerce.resolvedVariantId(),\n price: commerce.resolvedPrice(),\n quantity: commerce.getQuantity(),\n setQuantity,\n complete: commerce.selectionValid(),\n missing: commerce.missingOptionKeys(),\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [commerce, select, setQuantity, version],\n );\n}\n","'use client';\n\n/**\n * `Editor.*` — composable editor primitives over one `Editor.Root`\n * (ADR-0085). Parts carry behavior + state subscription; the HOST owns all\n * layout (with the documented exception of the canvas's selection-anchored\n * overlays — anchoring contract, ADR-0085 §5).\n *\n * ```tsx\n * import { Editor, design } from '@snowcone-app/canvas/embed';\n *\n * const d = design({ name: 'Front', width: 1480, height: 2328 })\n * .background(artUrl, { aspectRatio: 1480 / 2328, name: 'art' })\n * .text('YOUR NAME', { anchor: 'top', name: 'headline' });\n *\n * // No-canvas personalization widget — the rendering engine never loads:\n * <Editor.Root shop={SHOP_KEY} product={product} design={d} grantUrl=\"/api/grant\">\n * <Editor.Preview />\n * <Editor.TextField layer={d.layer('headline')} placeholder=\"Your name\" />\n * <Editor.Buy onAddToCart={({ designState }) => persist(designState)} />\n * </Editor.Root>\n *\n * // Full editor — same surface, plus the lazy canvas:\n * <Editor.Root shop={SHOP_KEY} product={product} design={d} grantUrl=\"/api/grant\">\n * <Editor.Canvas />\n * <Editor.Preview />\n * <Editor.Buy onAddToCart={…} />\n * </Editor.Root>\n * ```\n *\n * Stable since the ADR-0085 P4 gate passed: the default editor\n * (`SnowconeEditor`) is rebuilt from exactly these parts, CI-enforced, so the\n * surface is additive-only from here.\n */\n\nimport { EditorRoot } from './EditorRoot.js';\nimport { EditorCanvas } from './EditorCanvas.js';\nimport { EditorPreview } from './EditorPreview.js';\nimport { EditorTextField } from './EditorTextField.js';\nimport { EditorBuy } from './EditorBuy.js';\nimport { EditorLayers } from './EditorLayers.js';\nimport { EditorControls } from './EditorControls.js';\nimport { EditorHistory } from './EditorHistory.js';\nimport { EditorMenu } from './EditorMenu.js';\nimport { EditorAdd } from './EditorAdd.js';\n\nexport const Editor = {\n /** The one provider boundary — session, design, live state, error boundary. */\n Root: EditorRoot,\n /** The editable artboard (the ONE lazy renderer boundary — D9). */\n Canvas: EditorCanvas,\n /** Live product mockup. ×N under one Root is valid. */\n Preview: EditorPreview,\n /** Form input bound to a design text layer by typed token (T1). */\n TextField: EditorTextField,\n /** Smart commerce part: completeness + payload assembly; submit = host callback. */\n Buy: EditorBuy,\n /** Layer list. The one editor part that works canvas-free (ADR-0085 §4). */\n Layers: EditorLayers,\n /** Morphing contextual zone — ONE coarse part; placement docked|floating (§5). */\n Controls: EditorControls,\n /** Undo/redo controls. Requires Editor.Canvas. */\n History: EditorHistory,\n /** The one ⋯ overflow menu. Requires Editor.Canvas. */\n Menu: EditorMenu,\n /** The ⊕ add-element menu. Requires Editor.Canvas. */\n Add: EditorAdd,\n} as const;\n\nexport type { EditorRootProps, EditorRootBaseProps, GrantSource } from './EditorRoot.js';\nexport type { EditorCanvasProps } from './EditorCanvas.js';\nexport type { EditorPreviewProps } from './EditorPreview.js';\nexport type { EditorTextFieldProps } from './EditorTextField.js';\nexport type { EditorBuyProps, EditorBuyPayload, BuyMissingReason } from './EditorBuy.js';\nexport type { DesignState } from './designStateStore.js';\nexport { DesignStateStore } from './designStateStore.js';\n// Buy-owned commerce state (ADR-0085 §2, P2) — the host's variant-UI hook.\nexport { useProductSelection } from './useProductSelection.js';\nexport type { ProductSelectionApi } from './useProductSelection.js';\nexport { CommerceStateStore } from './commerceStore.js';\nexport type { ProductOptionChoice, ProductSelectionAttribute } from './commerceStore.js';\nexport type { EditorLayersProps } from './EditorLayers.js';\nexport type { EditorControlsProps } from './EditorControls.js';\nexport type { EditorHistoryProps } from './EditorHistory.js';\nexport type { EditorMenuProps } from './EditorMenu.js';\nexport type { EditorAddProps } from './EditorAdd.js';\n","'use client';\n\n/**\n * `<RealtimeEmbed>` — the legacy turnkey wrapper around `<Editor.Root>`.\n *\n * Everything it used to own (the single RenderSession, the design seed, the\n * live mockups, the context) was EXTRACTED into `EditorRoot` (ADR-0085 / D5 —\n * extraction, not copy): this component is `<EditorRoot>` plus the legacy\n * advisory validation mode (dev-only `console.error` diagnostics instead of\n * `Editor.Root`'s throw-on-misconfiguration, F3). The existing realtime\n * surface — `<RealtimeCanvas>`, `<RealtimeMockup>`, `useRealtimeMockups` —\n * reads the same context `EditorRoot` provides, so nothing existing changes\n * meaning, and the existing realtime tests exercise the new Root.\n *\n * @example\n * ```tsx\n * const d = design({ name: 'Front', width: 1480, height: 2328 })\n * .background(artUrl, { aspectRatio: 1480 / 2328, name: 'art' })\n * .text('YOUR NAME', { anchor: 'top', name: 'headline' });\n *\n * <RealtimeEmbed\n * shop=\"YOUR_SHOP_ID\"\n * grantUrl=\"/api/realtime/grant\"\n * // variantId is REQUIRED for a product with a color/variant axis (BEEB77 has\n * // a Frame color) — omit it and the render hangs. Pass `options` too so a\n * // wrong/missing variantId fails fast instead of timing out. Read both from\n * // getProduct(productId) (its options.combinations[].variantId).\n * product={{ productId: 'BEEB77', mockupIds: ['FV1qjO'], variantId: 'Pv1sLC', placements: ['Front'] }}\n * design={d}\n * >\n * <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr' }}>\n * <RealtimeCanvas /> {/* editor *\\/}\n * <RealtimeMockup /> {/* live preview *\\/}\n * </div>\n * </RealtimeEmbed>\n * ```\n */\n\nimport React from 'react';\nimport {\n EditorRoot,\n type EditorRootBaseProps,\n type EditorRootProps,\n type GrantSource,\n} from '../editor/EditorRoot.js';\n\n// Re-exported from the extraction home so existing imports keep working.\nexport { SLOW_RENDER_HINT_MS, slowRenderHint } from '../editor/EditorRoot.js';\nexport type { GrantSource };\n\n// Omit only from the non-union half — Omit over the GrantSource union would\n// collapse the exactly-one-of grant/grantUrl discrimination.\nexport type RealtimeEmbedProps = GrantSource & Omit<EditorRootBaseProps, '__validation'>;\n\nexport function RealtimeEmbed(props: RealtimeEmbedProps): React.ReactElement {\n return <EditorRoot {...(props as EditorRootProps)} __validation=\"warn\" />;\n}\n","'use client';\n\n/**\n * `<RealtimeCanvas>` — the interactive editor half of a realtime embed\n * (legacy turnkey API; `Editor.Canvas` is the primitives-era equivalent).\n *\n * Mounts a `<SnowconeCanvas>` seeded from the embed's `design`, and forwards\n * every edit to the shared RenderSession as a server render. All the\n * load-bearing wiring an embedder used to copy by hand is internal: the\n * `sc-root` class, `inheritTheme`, edit→`serializeStateForServer`→\n * `renderState`, and the artboard/placement match.\n *\n * Since ADR-0085 (D9) the implementation lives in the shared lazy renderer\n * chunk ({@link EditorCanvasImpl}) behind a dynamic import — the embed\n * entry's static import graph stays renderer-free, so a no-canvas\n * composition never downloads the rendering engine. The canvas therefore\n * mounts one micro-beat after first paint (a chunk fetch on cold cache); the\n * forwarded ref attaches when it does.\n *\n * Defaults to the chrome-less `kit=\"embed-only\"` — bring your own controls as\n * `children` (they render as an overlay INSIDE the canvas's editor context, so\n * `useTextBinding(name)` / `useImageBinding(name)` resolve against the live\n * elements). For a full in-canvas editor pass `kit=\"compact-customizer\"` or\n * `kit=\"pro-studio\"`.\n *\n * Must be rendered inside `<RealtimeEmbed>` (or any `EmbedContext` provider).\n */\n\nimport React, { forwardRef, useEffect, useState, type CSSProperties, type ReactNode } from 'react';\nimport type { CanvasState, SnowconeCanvasHandle } from '../embed/SnowconeCanvas.js';\nimport type { KitPresetId, KitDefinition } from '../../kits/types.js';\nimport type { CanvasServices } from '../../contexts/CanvasServicesContext.js';\nimport { loadCanvasImpl } from '../editor/EditorCanvas.js';\n\nexport interface RealtimeCanvasProps {\n /** Your controls (toolbar, inputs). Rendered as an overlay inside the editor\n * context so binding hooks work. */\n children?: ReactNode;\n /**\n * Editor chrome to mount. The default `'embed-only'` is a chrome-less canvas —\n * the host supplies every control as `children` (text inputs, image swap)\n * through `useTextBinding` / `useImageBinding`. That's the right call for a\n * fill-in-the-blanks personalizer, but it gives the shopper NO way to select a\n * layer and change its font size, add an element, or reorder layers.\n *\n * To ship a real editor through the turnkey realtime path, pass a richer\n * preset — `'compact-customizer'` (a trimmed toolbar) or `'pro-studio'` (full\n * panels). Every edit still flows to the shared RenderSession as a\n * server render automatically; you get add-element / font-size / layers for\n * free without ejecting to a raw `SnowconeCanvas` + `RenderSession`.\n *\n * Pair a chrome'd kit with `children` only when your overlay adds to — not\n * duplicates — the kit's controls, or you'll get double chrome.\n *\n * @default 'embed-only'\n */\n kit?: KitPresetId | KitDefinition;\n /** Inherit the host app's theme instead of managing its own (default true). */\n inheritTheme?: boolean;\n /** Cap the canvas height in px. */\n maxHeight?: number;\n /**\n * Privileged-service wiring for the editor chrome (Image Browser search /\n * AI tabs). Usually set once on `<RealtimeEmbed services={…}>` and inherited;\n * pass it here only to override for this canvas. Host the URLs on your\n * server — your vendor keys live there.\n */\n services?: CanvasServices;\n /**\n * Observe the live design state. Fires with the full {@link CanvasState}\n * (elements stamped with their artboard name) whenever the canvas content\n * changes — including once after the initial seed loads — in addition to the\n * embed's internal edit→server-render flow, which is unaffected. This is the\n * state you persist at add-to-cart / checkout so the purchased design can be\n * re-rendered server-side later.\n *\n * Safe to pass inline: the underlying canvas reads the callback from a ref,\n * so a new identity each render never re-fires or loops.\n */\n onChange?: (state: CanvasState) => void;\n className?: string;\n style?: CSSProperties;\n}\n\ntype ImplComponent = Awaited<ReturnType<typeof loadCanvasImpl>>;\n\n/**\n * Note the export naming wart, kept for backwards compatibility:\n * - The ref handle's {@link SnowconeCanvasHandle.exportArtboards} resolves a\n * record keyed by artboard **name** (e.g. `'Front'`) — names match the\n * `placements` you configured on the embed.\n * - The lower-level `useExport().exportArtboard(id)` hook takes an artboard\n * **ID** (get one from `useArtboards()`).\n * For print-res exports at checkout, the ref handle is the intended path:\n * `ref.current.exportArtboards({ all: true, scale: 4, format: 'blob' })`.\n */\nexport const RealtimeCanvas = forwardRef<SnowconeCanvasHandle, RealtimeCanvasProps>(\n function RealtimeCanvas(props: RealtimeCanvasProps, ref): React.ReactElement {\n const { children, className, style, maxHeight, ...rest } = props;\n\n const [Impl, setImpl] = useState<ImplComponent | null>(null);\n useEffect(() => {\n let cancelled = false;\n loadCanvasImpl().then(\n (component) => {\n if (!cancelled) setImpl(() => component);\n },\n (err) => {\n // Legacy surface keeps the advisory console contract (no Root\n // boundary is guaranteed to exist here).\n console.error('[RealtimeCanvas] failed to load the rendering chunk:', err);\n },\n );\n return () => {\n cancelled = true;\n };\n }, []);\n\n if (!Impl) {\n return (\n <div\n className={`sc-root${className ? ` ${className}` : ''}`}\n style={{ minHeight: maxHeight ?? 200, ...style }}\n aria-busy=\"true\"\n />\n );\n }\n\n return (\n <Impl ref={ref} selfScope maxHeight={maxHeight} className={className} style={style} {...rest}>\n {children}\n </Impl>\n );\n },\n);\n","'use client';\n\n/**\n * `<RealtimeMockup>` — the live preview half of a realtime embed (legacy\n * turnkey API). The implementation was EXTRACTED to `Editor.Preview`\n * (ADR-0085 / D5); this wrapper keeps the original name and props. (The\n * rendered `<img>` now carries `data-sc-part=\"preview\"` — additive only.)\n *\n * Because it shares one session with the rest of the embed, the preview can\n * never desync from the editor and needs no wiring of its own. Place it\n * anywhere inside `<RealtimeEmbed>`.\n */\n\nimport React from 'react';\nimport { EditorPreview, type EditorPreviewProps } from '../editor/EditorPreview.js';\n\n// Re-exported from the extraction home so existing imports keep working.\nexport {\n RESOLUTION_MISMATCH_RATIO,\n resolutionMismatchHint,\n suggestRenderWidth,\n} from '../editor/EditorPreview.js';\n\nexport type RealtimeMockupProps = EditorPreviewProps;\n\nexport function RealtimeMockup(props: RealtimeMockupProps): React.ReactElement {\n return <EditorPreview {...props} />;\n}\n","'use client';\n\nimport type { MockupResult } from '@snowcone-app/sdk';\nimport { useEmbedContext } from './context.js';\n\nexport interface UseRealtimeMockupsResult {\n /** All mockups from the latest render (one per requested mockupId). */\n mockups: MockupResult[];\n /** True between a render dispatch and the next mockup / error. */\n isRendering: boolean;\n /** Last render/timeout error message, or null. */\n error: string | null;\n}\n\n/**\n * Read the live mockups for a custom preview UI. Reactive: re-renders when new\n * mockups arrive. Must be called inside `<RealtimeEmbed>`.\n *\n * For the common case (just show the rendered image) use `<RealtimeMockup>`\n * instead — this hook is for building your own gallery / loading treatment.\n */\nexport function useRealtimeMockups(): UseRealtimeMockupsResult {\n const { mockups, isRendering, error } = useEmbedContext();\n return { mockups, isRendering, error };\n}\n","'use client';\n\n/**\n * `<SnowconeEditor>` — the turnkey default editor, REBUILT FROM THE PUBLIC\n * PARTS (ADR-0085, P4). Visual spec: `canvas-default-chrome-new-v1`\n * (`/design-system/page/canvas-default-chrome-new-v1` in apps/www) — the\n * PDP-editor grammar: calm surface, an \"Editor\" header (undo/redo · ⋯ ·\n * Buy-instead-of-Done), nothing floating over the artwork, a morphing\n * control zone BELOW the stage, and the buyable 2:3 mockup in a PiP that\n * swaps with the stage.\n *\n * THE LOAD-BEARING CONSTRAINT: this module imports ONLY the public embed\n * entry (`../api/embed.js` — the same surface a host gets from\n * `@snowcone-app/canvas/embed`) plus react. No `../` imports into internals,\n * mechanically gated (publicSurfaceGate test + verify typecheck). The day\n * this default needs a private API, the primitives are wrong — restyling to\n * a future chrome (e.g. the v2 bar-less mock) must be a composition tweak.\n *\n * PART COMPOSITION MAP (the plan's inline-diagram home for P4):\n *\n * SnowconeEditor\n * └── Editor.Root session · design · stores · boundary\n * └── frame (embed card ⇄ fullscreen takeover — same chrome, only the\n * │ frame changes; both directions live in the ⋯ menu)\n * ├── header\n * │ ├── \"Editor\" title\n * │ ├── Editor.History undo/redo\n * │ ├── ⋯ menu (own DOM) fullscreen · view switch · export PNG\n * │ │ (export via the Editor.Canvas ref\n * │ │ handle — runtime, not a static import)\n * │ └── Editor.Buy \"Add to cart · $price\" pill\n * │ └── useProductSelection() price + completeness\n * ├── stage\n * │ ├── Editor.Canvas the editable artboard (center)\n * │ └── Editor.Preview buyable mockup PiP (top-right,\n * │ tap to swap with the stage)\n * └── control zone (morphs below the stage; nothing floats)\n * ├── selected → Editor.Controls placement=\"docked\"\n * │ (registering docked Controls suppresses the\n * │ canvas's built-in floating toolbar — §5)\n * └── idle → Editor.Add ⊕ + layer thumbnails\n * (useLayers(): previews + select — public\n * headless floor, no private API)\n *\n * Stable since ADR-0085 P4 (this component IS the gate artifact — composed\n * only from the public embed entry); additive-only from here.\n */\n\nimport React, {\n useCallback,\n useEffect,\n useRef,\n useState,\n type CSSProperties,\n} from 'react';\nimport {\n Editor,\n useProductSelection,\n useSelectedElement,\n useLayers,\n type EditorRootBaseProps,\n type EditorBuyPayload,\n type GrantSource,\n type SnowconeCanvasHandle,\n} from '../api/embed.js';\n\nexport type SnowconeEditorProps = GrantSource &\n Omit<EditorRootBaseProps, 'children' | '__validation'> & {\n /** The final submit — your one line. Variant/quantity/completeness and\n * payload assembly are `Editor.Buy`'s job. */\n onAddToCart: (payload: EditorBuyPayload) => void | Promise<void>;\n /** Seeds the Buy-owned quantity once on mount (default 1). */\n defaultQuantity?: number;\n /** Header title. Default \"Editor\". */\n title?: string;\n /** Embedded-card height (px or CSS length). Fullscreen ignores it. */\n height?: number | string;\n className?: string;\n style?: CSSProperties;\n };\n\n/** Price label for the Buy pill — catalog prices are cents. Whole dollars\n * render without cents (\"$24\"), like the PDP. */\nexport function formatBuyPrice(cents: number): string {\n return new Intl.NumberFormat('en-US', {\n style: 'currency',\n currency: 'USD',\n minimumFractionDigits: cents % 100 === 0 ? 0 : 2,\n maximumFractionDigits: cents % 100 === 0 ? 0 : 2,\n }).format(cents / 100);\n}\n\n// ── Shared inline styles (themed via .sc-root tokens, like every part) ──────\n\nconst iconButtonStyle: CSSProperties = {\n display: 'inline-flex',\n alignItems: 'center',\n justifyContent: 'center',\n width: 32,\n height: 32,\n padding: 0,\n borderRadius: 9999,\n border: 'none',\n background: 'transparent',\n color: 'var(--sc-color-foreground, #111)',\n font: 'inherit',\n fontSize: 16,\n lineHeight: 1,\n cursor: 'pointer',\n};\n\nconst menuItemStyle: CSSProperties = {\n display: 'flex',\n alignItems: 'center',\n gap: 10,\n width: '100%',\n padding: '8px 10px',\n borderRadius: 8,\n border: 'none',\n background: 'transparent',\n color: 'inherit',\n font: 'inherit',\n fontSize: 12,\n fontWeight: 500,\n textAlign: 'left',\n cursor: 'pointer',\n};\n\nfunction MenuItem({\n label,\n onSelect,\n}: {\n label: string;\n onSelect: () => void;\n}): React.ReactElement {\n return (\n <button\n type=\"button\"\n role=\"menuitem\"\n data-sc-part=\"snowcone-editor-menu-item\"\n style={menuItemStyle}\n onClick={onSelect}\n >\n {label}\n </button>\n );\n}\n\n// ── The ⋯ menu (own DOM — the turnkey ARRANGEMENT owns fullscreen/view/export;\n// they are modes of this composition, not editor-document commands) ───────\n\nfunction OverflowMenu({\n fullscreen,\n onToggleFullscreen,\n viewCount,\n viewIndex,\n onSelectView,\n onExport,\n}: {\n fullscreen: boolean;\n onToggleFullscreen: () => void;\n viewCount: number;\n viewIndex: number;\n onSelectView: (index: number) => void;\n onExport: () => void;\n}): React.ReactElement {\n const [open, setOpen] = useState(false);\n const close = (): void => setOpen(false);\n return (\n <div style={{ position: 'relative' }}>\n <button\n type=\"button\"\n aria-label=\"Editor menu\"\n aria-haspopup=\"menu\"\n aria-expanded={open}\n data-sc-part=\"snowcone-editor-menu\"\n style={iconButtonStyle}\n onClick={() => setOpen((o) => !o)}\n >\n ⋮\n </button>\n {open ? (\n <>\n {/* click-away backdrop */}\n <div\n style={{ position: 'fixed', inset: 0, zIndex: 39 }}\n onClick={close}\n aria-hidden=\"true\"\n />\n <div\n role=\"menu\"\n data-sc-part=\"snowcone-editor-menu-list\"\n style={{\n position: 'absolute',\n right: 0,\n top: '100%',\n marginTop: 4,\n minWidth: 176,\n padding: 4,\n borderRadius: 12,\n background: 'var(--sc-color-surface, #fff)',\n boxShadow: '0 8px 24px rgba(0,0,0,0.14)',\n border: '1px solid rgba(0,0,0,0.08)',\n zIndex: 40,\n }}\n >\n <MenuItem\n label={fullscreen ? 'Exit fullscreen' : 'Fullscreen'}\n onSelect={() => {\n close();\n onToggleFullscreen();\n }}\n />\n {viewCount > 1\n ? Array.from({ length: viewCount }, (_, i) => (\n <MenuItem\n key={i}\n label={`View ${i + 1}${i === viewIndex ? ' ✓' : ''}`}\n onSelect={() => {\n close();\n onSelectView(i);\n }}\n />\n ))\n : null}\n <MenuItem\n label=\"Export PNG\"\n onSelect={() => {\n close();\n onExport();\n }}\n />\n </div>\n </>\n ) : null}\n </div>\n );\n}\n\n// ── Idle dock: ⊕ + layer thumbnails (public headless floor) ─────────────────\n\nfunction IdleDock(): React.ReactElement {\n const { flatLayers, selectLayer, generateAllPreviews } = useLayers({ previewSize: 96 });\n\n useEffect(() => {\n if (flatLayers.length > 0) void generateAllPreviews();\n }, [flatLayers.length, generateAllPreviews]);\n\n return (\n <div\n data-sc-part=\"snowcone-editor-idle-dock\"\n style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, minHeight: 44 }}\n >\n <Editor.Add />\n {flatLayers.length > 0 ? (\n <div style={{ width: 1, height: 28, background: 'rgba(0,0,0,0.1)', flexShrink: 0 }} aria-hidden=\"true\" />\n ) : null}\n {flatLayers.map((layer) => (\n <button\n key={layer.id}\n type=\"button\"\n data-sc-part=\"snowcone-editor-layer-thumb\"\n aria-label={`Select ${layer.name}`}\n onClick={() => selectLayer(layer.id)}\n style={{\n width: 44,\n height: 44,\n padding: 2,\n borderRadius: 12,\n border: '1px solid rgba(0,0,0,0.1)',\n background: 'var(--sc-color-surface, #fff)',\n overflow: 'hidden',\n cursor: 'pointer',\n flexShrink: 0,\n display: 'inline-flex',\n alignItems: 'center',\n justifyContent: 'center',\n }}\n >\n {layer.previewUrl ? (\n // eslint-disable-next-line @next/next/no-img-element\n <img src={layer.previewUrl} alt=\"\" style={{ width: '100%', height: '100%', objectFit: 'contain' }} />\n ) : (\n <span\n style={{\n fontSize: 10,\n fontWeight: 600,\n maxWidth: '100%',\n overflow: 'hidden',\n textOverflow: 'ellipsis',\n whiteSpace: 'nowrap',\n }}\n >\n {layer.name}\n </span>\n )}\n </button>\n ))}\n </div>\n );\n}\n\n// ── Buy pill (label = \"Add to cart · $price\" when the catalog has one) ──────\n\nfunction BuyPill({\n onAddToCart,\n defaultQuantity,\n}: {\n onAddToCart: (payload: EditorBuyPayload) => void | Promise<void>;\n defaultQuantity?: number;\n}): React.ReactElement {\n const { price, complete } = useProductSelection();\n return (\n <Editor.Buy\n onAddToCart={onAddToCart}\n {...(typeof defaultQuantity === 'number' ? { defaultQuantity } : {})}\n style={{\n display: 'inline-flex',\n alignItems: 'center',\n gap: 6,\n padding: '7px 16px',\n marginLeft: 4,\n borderRadius: 9999,\n border: 'none',\n background: 'var(--sc-color-foreground, #111)',\n color: 'var(--sc-color-surface, #fff)',\n font: 'inherit',\n fontSize: 12,\n fontWeight: 700,\n whiteSpace: 'nowrap',\n cursor: complete ? 'pointer' : 'not-allowed',\n opacity: complete ? 1 : 0.5,\n }}\n >\n Add to cart{typeof price === 'number' ? ` · ${formatBuyPrice(price)}` : ''}\n </Editor.Buy>\n );\n}\n\n// ── The chrome (everything inside Editor.Root) ──────────────────────────────\n\nfunction DefaultChrome({\n title,\n height,\n mockupIds,\n onAddToCart,\n defaultQuantity,\n className,\n style,\n}: {\n title: string;\n height: number | string;\n mockupIds: string[];\n onAddToCart: (payload: EditorBuyPayload) => void | Promise<void>;\n defaultQuantity?: number;\n className?: string;\n style?: CSSProperties;\n}): React.ReactElement {\n const [fullscreen, setFullscreen] = useState(false);\n const [viewIndex, setViewIndex] = useState(0);\n const [swapped, setSwapped] = useState(false);\n const canvasRef = useRef<SnowconeCanvasHandle>(null);\n const selected = useSelectedElement();\n\n const mockupId = mockupIds[Math.min(viewIndex, mockupIds.length - 1)];\n\n // Export through the mounted canvas's public ref handle — runtime-only, so\n // this module's static graph stays renderer-free (the heavy export path\n // lives behind Editor.Canvas's lazy chunk, where it already is).\n const handleExport = useCallback(async () => {\n const exports = await canvasRef.current?.exportArtboards({ format: 'dataUrl' });\n if (!exports) return;\n const [name, dataUrl] = Object.entries(exports)[0] ?? [];\n if (typeof dataUrl !== 'string') return;\n const anchor = document.createElement('a');\n anchor.href = dataUrl;\n anchor.download = `${name ?? 'design'}.png`;\n anchor.click();\n }, []);\n\n const frameStyle: CSSProperties = {\n display: 'flex',\n flexDirection: 'column',\n overflow: 'hidden',\n background: 'var(--sc-color-surface, #fff)',\n color: 'var(--sc-color-foreground, #111)',\n fontFamily: 'ui-sans-serif, system-ui, sans-serif',\n ...(fullscreen\n ? {\n position: 'fixed',\n inset: 0,\n zIndex: 9999,\n height: '100dvh',\n paddingBottom: 'env(safe-area-inset-bottom)',\n }\n : {\n position: 'relative',\n height,\n borderRadius: 16,\n border: '1px solid rgba(0,0,0,0.08)',\n boxShadow: '0 1px 3px rgba(0,0,0,0.08)',\n }),\n ...style,\n };\n\n const pipBoxStyle: CSSProperties = {\n position: 'absolute',\n top: 8,\n right: 12,\n width: 96,\n aspectRatio: '2 / 3',\n borderRadius: 12,\n overflow: 'hidden',\n border: '1px solid rgba(0,0,0,0.1)',\n boxShadow: '0 4px 12px rgba(0,0,0,0.12)',\n background: 'var(--sc-color-surface, #fff)',\n padding: 0,\n cursor: 'pointer',\n zIndex: 2,\n };\n\n return (\n <div\n data-sc-part=\"snowcone-editor\"\n data-sc-fullscreen={fullscreen ? 'true' : undefined}\n className={className}\n style={frameStyle}\n >\n {/* Header — title · undo/redo · ⋯ · Buy (the PDP header, Done → Buy) */}\n <div\n data-sc-part=\"snowcone-editor-header\"\n style={{\n display: 'flex',\n alignItems: 'center',\n gap: 2,\n padding: '10px 12px 4px 16px',\n flexShrink: 0,\n }}\n >\n <span style={{ fontSize: 14, fontWeight: 700, marginRight: 'auto' }}>{title}</span>\n <Editor.History />\n <OverflowMenu\n fullscreen={fullscreen}\n onToggleFullscreen={() => setFullscreen((f) => !f)}\n viewCount={mockupIds.length}\n viewIndex={viewIndex}\n onSelectView={setViewIndex}\n onExport={() => void handleExport()}\n />\n <BuyPill onAddToCart={onAddToCart} defaultQuantity={defaultQuantity} />\n </div>\n\n {/* Stage — artboard center; buyable mockup PiP top-right, tap to swap */}\n <div\n data-sc-part=\"snowcone-editor-stage\"\n style={{ position: 'relative', flex: 1, minHeight: 0, padding: '4px 12px' }}\n >\n <Editor.Canvas ref={canvasRef} style={{ height: '100%' }} />\n\n {swapped ? (\n // Swapped: the mockup IS the stage; the corner chip returns to the\n // artwork. The canvas stays mounted underneath (no document\n // teardown), just covered.\n <div\n data-sc-part=\"snowcone-editor-swap-stage\"\n style={{\n position: 'absolute',\n inset: 0,\n zIndex: 1,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n background: 'var(--sc-color-surface, #fff)',\n padding: 8,\n }}\n >\n <Editor.Preview\n mockupId={mockupId}\n alt=\"Product mockup\"\n fallback={<div aria-busy=\"true\">Rendering…</div>}\n style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain', borderRadius: 12 }}\n />\n <button\n type=\"button\"\n aria-label=\"Back to artwork\"\n data-sc-part=\"snowcone-editor-swap-back\"\n onClick={() => setSwapped(false)}\n style={{\n ...pipBoxStyle,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n fontSize: 11,\n fontWeight: 600,\n color: 'inherit',\n border: '1px dashed rgba(0,0,0,0.25)',\n }}\n >\n artwork\n </button>\n </div>\n ) : (\n <button\n type=\"button\"\n aria-label=\"Show product mockup\"\n data-sc-part=\"snowcone-editor-pip\"\n onClick={() => setSwapped(true)}\n style={pipBoxStyle}\n >\n <Editor.Preview\n mockupId={mockupId}\n alt=\"Product mockup preview\"\n fallback={<span style={{ fontSize: 10, opacity: 0.5 }} aria-busy=\"true\">mockup…</span>}\n style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}\n />\n </button>\n )}\n </div>\n\n {/* Control zone — morphs BELOW the stage (PDP grammar): idle → ⊕ +\n layer thumbs; selected → the docked contextual zone (which also\n suppresses the canvas's floating toolbar — nothing floats). */}\n <div\n data-sc-part=\"snowcone-editor-zone\"\n data-sc-zone-state={selected ? 'selected' : 'idle'}\n style={{ flexShrink: 0, padding: '4px 16px 14px' }}\n >\n <div style={{ display: selected ? undefined : 'none' }}>\n <Editor.Controls placement=\"docked\" />\n </div>\n {selected ? null : <IdleDock />}\n </div>\n </div>\n );\n}\n\n/**\n * The turnkey Snowcone editor — the same public parts, our arrangement.\n *\n * ```tsx\n * import { SnowconeEditor, design } from '@snowcone-app/canvas/embed';\n *\n * <SnowconeEditor\n * shop={SHOP_KEY}\n * product={{ productId: 'BEEB77', mockupIds: ['FV1qjO'], variantId: 'Pv1sLC', placements: ['Front'] }}\n * design={design({ name: 'Front', width: 1480, height: 2328 }).text('hello', { name: 'headline' })}\n * grantUrl=\"/api/realtime/grant\"\n * onAddToCart={(payload) => persist(payload.designState)}\n * />\n * ```\n *\n * Customizing beyond the props means composing `Editor.*` yourself — this\n * component is ~300 lines of public-surface composition you can copy and own.\n *\n * Stable since ADR-0085 P4 (this component IS the gate artifact — composed\n * only from the public embed entry); additive-only from here.\n */\nexport function SnowconeEditor(props: SnowconeEditorProps): React.ReactElement {\n const {\n onAddToCart,\n defaultQuantity,\n title = 'Editor',\n height = 480,\n className,\n style,\n ...rootProps\n } = props;\n\n return (\n <Editor.Root {...rootProps}>\n <DefaultChrome\n title={title}\n height={height}\n mockupIds={rootProps.product.mockupIds}\n onAddToCart={onAddToCart}\n {...(typeof defaultQuantity === 'number' ? { defaultQuantity } : {})}\n className={className}\n style={style}\n />\n </Editor.Root>\n );\n}\n","/**\n * @snowcone-app/canvas/embed — Realtime embed primitives (Tier 2)\n *\n * The turnkey way to drop a live, server-rendered product editor into your app.\n * Three components that share one session so the editor and the preview can't\n * desync, plus the `design()` builder that seeds both:\n *\n * ```tsx\n * import { RealtimeEmbed, RealtimeCanvas, RealtimeMockup, design }\n * from '@snowcone-app/canvas/embed';\n * import '@snowcone-app/canvas/style.css';\n *\n * const d = design({ name: 'Front', width: 1480, height: 2328 })\n * .background(artUrl, { aspectRatio: 1480 / 2328, name: 'art' })\n * .text('YOUR NAME', { anchor: 'top', name: 'headline' });\n *\n * <RealtimeEmbed\n * shop=\"YOUR_SHOP_ID\"\n * grantUrl=\"/api/realtime/grant\"\n * // variantId is REQUIRED when the product has a color/variant axis (BEEB77\n * // does) — omit it and the render hangs. Read it + options from getProduct().\n * product={{ productId: 'BEEB77', mockupIds: ['FV1qjO'], variantId: 'Pv1sLC', placements: ['Front'] }}\n * design={d}\n * >\n * <RealtimeCanvas />\n * <RealtimeMockup />\n * </RealtimeEmbed>\n * ```\n *\n * Everything an embed needs is REQUIRED on `<RealtimeEmbed>` — there's no\n * silently-optional prop to forget. For full manual control (your own session,\n * custom layout, multi-placement, color variants) drop to `<SnowconeCanvas>` +\n * `RenderSession` directly; see the docs' \"eject\" section.\n *\n * @packageDocumentation\n */\n\n// Register icons on module load (the editor + overlay controls use them).\nimport { ensureIconsRegistered } from '../icons/registry.js';\nensureIconsRegistered();\n\n// === Editor.* composable primitives (ADR-0085) ===\n// STABLE: the P4 gate passed — SnowconeEditor (bottom of this file) is rebuilt\n// from exactly this surface, CI-enforced. Additive-only from here; renames and\n// removals are pinned by publicSurfaceGate.test.ts.\nexport { Editor, DesignStateStore, useProductSelection } from '../components/editor/index.js';\nexport type {\n EditorRootProps,\n EditorRootBaseProps,\n EditorCanvasProps,\n EditorPreviewProps,\n EditorTextFieldProps,\n EditorBuyProps,\n EditorBuyPayload,\n BuyMissingReason,\n DesignState,\n EditorLayersProps,\n EditorControlsProps,\n EditorHistoryProps,\n EditorMenuProps,\n EditorAddProps,\n ProductSelectionApi,\n ProductOptionChoice,\n ProductSelectionAttribute,\n} from '../components/editor/index.js';\nexport { EditorError, isEditorError } from '../errors/editorError.js';\nexport type { EditorErrorCode, EditorErrorData } from '../errors/editorError.js';\n\n// === Embed primitives ===\nexport { RealtimeEmbed } from '../components/embed-realtime/RealtimeEmbed.js';\nexport type { RealtimeEmbedProps, GrantSource } from '../components/embed-realtime/RealtimeEmbed.js';\n\nexport { RealtimeCanvas } from '../components/embed-realtime/RealtimeCanvas.js';\nexport type { RealtimeCanvasProps } from '../components/embed-realtime/RealtimeCanvas.js';\n// `<RealtimeCanvas ref>` exposes the underlying canvas handle (print-res\n// `exportArtboards`, keyed by artboard NAME); `onChange` hands you the same\n// CanvasState shape — persist it at checkout, re-render it server-side later.\nexport type { SnowconeCanvasHandle, CanvasState } from '../components/embed/SnowconeCanvas.js';\n\nexport { RealtimeMockup } from '../components/embed-realtime/RealtimeMockup.js';\nexport type { RealtimeMockupProps } from '../components/embed-realtime/RealtimeMockup.js';\n\nexport { useRealtimeMockups } from '../components/embed-realtime/useRealtimeMockups.js';\nexport type { UseRealtimeMockupsResult } from '../components/embed-realtime/useRealtimeMockups.js';\n\nexport { validateEmbed, collectEmbedIssues } from '../components/embed-realtime/validateEmbed.js';\nexport type { ValidateEmbedInput, EmbedIssue } from '../components/embed-realtime/validateEmbed.js';\n\n// === Design builder — the single source of truth for an embed ===\nexport { design, DesignBuilder, isLayerToken } from '../design/design-builder.js';\nexport type {\n Anchor,\n ShapeKind,\n DesignArtboard,\n StateArtboard,\n FromStateOptions,\n AnyDesign,\n LayerKind,\n LayerToken,\n} from '../design/design-builder.js';\n\n// === Chrome-building hooks (build your own editor chrome inside <RealtimeCanvas>) ===\n// These run inside the canvas's editor context — render the component that\n// calls them as `children` of <RealtimeCanvas> (the overlay slot). Same\n// exports as the stable entry, so chrome built against `@snowcone-app/canvas`\n// ports to the embed entry unchanged.\n\nexport { useEditor } from '../contexts/EditorContext.js';\nexport type { EditorContextValue, EditorProviderProps } from '../contexts/EditorContext.js';\n\nexport { useLayers } from '../hooks/useLayers.js';\nexport type { LayerInfo, UseLayersOptions, UseLayersReturn } from '../hooks/useLayers.js';\n\nexport { useCommands } from '../hooks/useCommands.js';\nexport type { UseCommandsReturn } from '../hooks/useCommands.js';\n\nexport { useArtboards } from '../hooks/useArtboards.js';\nexport type { ArtboardInfo, UseArtboardsReturn } from '../hooks/useArtboards.js';\n\n// NOTE the naming wart: `useExport().exportArtboard(id)` takes an artboard ID\n// (from `useArtboards()`), while the <RealtimeCanvas ref> handle's\n// `exportArtboards()` resolves a record keyed by artboard NAME.\nexport { useExport } from '../hooks/useExport.js';\nexport type { ExportProgress, ContinuousExportOptions, UseExportReturn } from '../hooks/useExport.js';\n\nexport { useSelectedElement } from '../hooks/useSelectedElement.js';\n\n// === State serialization (CanvasStateV1 — persist a design at checkout) ===\nexport { serializeState } from '../state/index.js';\nexport type {\n CanvasStateV1,\n SerializedArtboard,\n SerializedElement,\n} from '../state/index.js';\n\n// === Binding hooks (build your own controls inside <RealtimeCanvas>) ===\nexport { useTextBinding } from '../hooks/useTextBinding.js';\nexport { useImageBinding } from '../hooks/useImageBinding.js';\nexport { useColorBinding } from '../hooks/useColorBinding.js';\nexport type { ColorBindingResult } from '../hooks/useColorBinding.js';\nexport { useFontBinding } from '../hooks/useFontBinding.js';\nexport type { FontBindingResult } from '../hooks/useFontBinding.js';\nexport { useElementByName } from '../hooks/useElementByName.js';\n\n// === Editable templates (saved state + buyer-editable field manifest) ===\nexport {\n readTemplateFields,\n withTemplateFields,\n TEMPLATE_FIELDS_KEY,\n} from '../design/template-fields.js';\nexport type {\n TemplateField,\n TemplateTextField,\n TemplateImageField,\n TemplateColorField,\n TemplateSelectField,\n} from '../design/template-fields.js';\n\n// === Privileged services (Image Browser search / AI generation) ===\n// Same pattern as `grantUrl`: host the proxy routes on your server, your\n// vendor keys live there. Wire via `services` on <RealtimeEmbed>.\nexport { CanvasServicesProvider, useCanvasServices } from '../contexts/CanvasServicesContext.js';\nexport type { CanvasServices, ResolvedCanvasServices } from '../contexts/CanvasServicesContext.js';\nexport { createProxyImageSearch, createProxyGenerate } from '../services/imageSearch.js';\nexport type {\n ImageSearchProvider,\n ImageSearchResult,\n ImageSearchResponse,\n ImageSearchParams,\n GenerateProvider,\n GenerateParams,\n GenerateResponse,\n} from '../services/imageSearch.js';\n\n// === Re-exported SDK types embedders touch ===\nexport type {\n RenderProduct,\n RenderProductOptions,\n RenderProductCombination,\n RenderProductRequiredPlacement,\n MockupResult,\n RealtimeGrant,\n} from '@snowcone-app/sdk';\n\n// === The turnkey default editor — rebuilt from the public parts (P4) ===\n// Deliberately LAST: SnowconeEditor itself imports this entry (it compiles\n// against the public surface only — the ADR-0085 P4 gate), so its module\n// body evaluates after everything above is initialized.\nexport { SnowconeEditor, formatBuyPrice } from '../default-editor/SnowconeEditor.js';\nexport type { SnowconeEditorProps } from '../default-editor/SnowconeEditor.js';\n"],"names":["EmbedContext","createContext","useEmbedContext","ctx","useContext","TAG","requiredPlacementLabels","product","_a","p","variantIds","_b","c","id","collectEmbedIssues","shop","design","hasGrant","issues","assertVariantSelected","err","json","placement","required","names","el","n","dupes","i","validateEmbed","input","issue","SLOW_RENDER_HINT_MS","slowRenderHint","toGetToken","props","grant","ErrorCard","error","onRetry","code","isEditorError","jsxs","jsx","CatchingBoundary","Component","recordContainedEditorError","process","EditorBoundary","reportedError","children","retryable","EditorRootInner","throttleMs","onMockups","onRenderError","wsUrl","services","internals","__validation","useMemo","useSyncExternalStore","selectedVariantId","guideBundle","usePieceGuideBundle","pieceGuides","artboard","pieceGuidesForArtboard","onMockupsRef","useRef","onRenderErrorRef","mockups","setMockups","useState","isRendering","setIsRendering","setError","auth","authKey","productKey","validationKey","fatal","EditorError","validatedKeyRef","useEffect","sessionResult","RenderSession","session","constructError","pushRender","state","throttle","message","results","appliedVariantRef","applied","baseline","serializeStateForServer","timer","value","registryVersion","body","EditorRootInternalsContext","BoundLayerGuardContext","EditorProvider","CanvasServicesProvider","EditorRoot","productIdentity","internalsRef","commerceRef","setReportedError","DesignStateStore","EditorPartsRegistry","CommerceStateStore","makeInvariantReporter","implLoader","m","loadCanvasImpl","EditorCanvas","forwardRef","maxHeight","className","style","ref","useEditorRootInternals","instanceId","useId","useLayoutEffect","Impl","setImpl","cancelled","component","RESOLUTION_MISMATCH_RATIO","SUGGESTED_WIDTHS","suggestRenderWidth","devicePx","step","resolutionMismatchHint","naturalWidth","suggestion","EditorPreview","mockupId","fallback","alt","warnedMockupIdsRef","result","handleLoad","event","img","cssWidth","hint","EditorTextField","layer","optional","placeholder","stateStore","validatedNameRef","isLayerToken","kindNow","handleChange","useCallback","next","bridge","evaluateBuyCompleteness","missing","key","field","seed","buildCartDetail","commerce","combinations","attributes","stringAttrs","attr","choiceLabelsOf","createCartDetail","EditorBuy","onAddToCart","defaultQuantity","seededRef","stateVersion","commerceVersion","quantity","name","complete","busy","setBusy","busyRef","handleClick","designState","variantId","payload","EditorControls","useRequiresCanvas","docked","useProductSelection","version","select","choice","setQuantity","Editor","EditorLayers","EditorHistory","EditorMenu","EditorAdd","RealtimeEmbed","RealtimeCanvas","rest","RealtimeMockup","useRealtimeMockups","formatBuyPrice","cents","iconButtonStyle","menuItemStyle","MenuItem","label","onSelect","OverflowMenu","fullscreen","onToggleFullscreen","viewCount","viewIndex","onSelectView","onExport","open","setOpen","close","o","Fragment","_","IdleDock","flatLayers","selectLayer","generateAllPreviews","useLayers","BuyPill","price","DefaultChrome","title","height","mockupIds","setFullscreen","setViewIndex","swapped","setSwapped","canvasRef","selected","useSelectedElement","handleExport","exports","dataUrl","anchor","frameStyle","pipBoxStyle","f","SnowconeEditor","rootProps","ensureIconsRegistered"],"mappings":";;;;;;;;;;AA0DO,MAAMA,KAAeC,GAA6C,MAAS;AAM3E,SAASC,IAAqC;AACnD,QAAMC,IAAMC,GAAWJ,EAAY;AACnC,MAAI,CAACG;AACH,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAKJ,SAAOA;AACT;ACvBA,MAAME,KAAM;AAUZ,SAASC,GAAwBC,GAAkC;;AACjE,OAAIC,IAAAD,KAAA,gBAAAA,EAAS,uBAAT,QAAAC,EAA6B;AAC/B,WAAOD,EAAQ,mBAAmB,OAAO,CAACE,MAAM,CAACA,EAAE,mBAAmB,EAAE,IAAI,CAACA,MAAMA,EAAE,KAAK;AAE5F,QAAMC,IAAa,IAAI;AAAA,OACpBC,IAAAJ,KAAA,gBAAAA,EAAS,YAAT,gBAAAI,EAAkB,iBAAgB,CAAA,GAChC,IAAI,CAACC,MAAMA,EAAE,SAAS,EACtB,OAAO,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AAA,MACC,GAAI,OAAOC,KAAoB,WAAW,EAAE,iBAAAA,EAAA,IAAoB,CAAA;AAAA,MACjE,WAAAzD;AAAA,MACA,OAAAC;AAAA,IAAA;AAAA,EAAA,GAEJ;AAEJ;AC9hBAuI,GAAA;"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"template-fields-BsnHMf1i.js","sources":["../src/components/editor/designStateStore.ts","../src/components/editor/commerceStore.ts","../src/hooks/useCommands.ts","../src/hooks/useSelectedElement.ts","../src/hooks/useDeadBindingWarning.ts","../src/hooks/useTextBinding.ts","../src/hooks/useImageBinding.ts","../src/hooks/useColorBinding.ts","../src/hooks/useFontBinding.ts","../src/hooks/useElementByName.ts","../src/design/template-fields.ts"],"sourcesContent":["/**\n * The ONE live design-state value under an `Editor.Root` (ADR-0085 §3 / T2).\n *\n * Today's turnkey flow is two stores, one-way, one-shot: the design seeds the\n * canvas once and edits never flow back, so the seed goes stale after the\n * first edit. This store fixes that by construction — seeded from the design\n * at Root mount, updated by every canvas change AND every TextField write,\n * last-write-wins. `Editor.Buy` (and `assertRenders`, P2) read THIS, never\n * the seed, so design staleness can't corrupt an order.\n *\n * TextField ─┐\n * ├─→ DesignStateStore ─→ pushRender ─→ session ─→ Preview(s)\n * Canvas ───┘\n *\n * (With a mounted Canvas the editor document is the write authority and this\n * store derives from its `onChange`; without one, this store IS the\n * authority. The routing lives in the parts — see EditorTextField.)\n *\n * Deliberately a tiny hand-rolled external store (subscribe + snapshot for\n * `useSyncExternalStore`) — narrow subscriptions without re-rendering the\n * whole Root tree per keystroke. Alternate state libraries were considered\n * and rejected (plan decision D3-C).\n */\n\nimport type { AnyElementConfig } from '../../types/index.js';\nimport { EditorError } from '../../errors/editorError.js';\nimport { layerKindOfConfig } from '../../design/design-builder.js';\n\n/** Editor-shape design state — the same shape `design.toJSON()` produces and\n * `<SnowconeCanvas onChange>` emits (and `serializeStateForServer` accepts). */\nexport interface DesignState {\n elements: AnyElementConfig[];\n artboards: Array<{\n name: string;\n width: number;\n height: number;\n backgroundColor?: string;\n exportBackground?: boolean;\n }>;\n activeArtboard: string;\n}\n\nfunction textOf(el: AnyElementConfig): string | undefined {\n return (el as { text?: string }).text;\n}\n\nfunction nameOf(el: AnyElementConfig): string | undefined {\n return (el as { name?: string }).name;\n}\n\nexport class DesignStateStore {\n private state: DesignState;\n /** Frozen snapshot of the values the design was seeded with — Buy's\n * \"differs from seed\" completeness rule (C3) compares against this. */\n private readonly seedTextByName: ReadonlyMap<string, string>;\n private readonly listeners = new Set<() => void>();\n\n constructor(seed: DesignState) {\n this.state = seed;\n const seedTexts = new Map<string, string>();\n for (const el of seed.elements) {\n const name = nameOf(el);\n const text = textOf(el);\n if (name && typeof text === 'string') seedTexts.set(name, text);\n }\n this.seedTextByName = seedTexts;\n }\n\n // Arrow on purpose: handed bare to `useSyncExternalStore` as the snapshot.\n getState = (): DesignState => {\n return this.state;\n };\n\n subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n };\n\n /** Replace the whole state (the canvas `onChange` path). */\n setState(next: DesignState): void {\n this.state = next;\n this.emit();\n }\n\n /** The seed value of a named text layer (for completeness rule C3). */\n seedTextOf(name: string): string | undefined {\n return this.seedTextByName.get(name);\n }\n\n /** Current text of a named text layer, or undefined when absent. */\n textOf(name: string): string | undefined {\n const el = this.state.elements.find((e) => nameOf(e) === name);\n return el ? textOf(el) : undefined;\n }\n\n /** Kind of the named layer in the CURRENT state ('text' | 'image' | null\n * for unbindable), or undefined when no layer has the name. */\n layerKindOf(name: string): 'text' | 'image' | null | undefined {\n const el = this.state.elements.find((e) => nameOf(e) === name);\n return el ? layerKindOfConfig(el) : undefined;\n }\n\n /** Names of bindable layers in the current state, for error messages. */\n bindableLayerNames(): string[] {\n return this.state.elements\n .filter((e) => layerKindOfConfig(e) !== null)\n .map(nameOf)\n .filter((n): n is string => Boolean(n));\n }\n\n /**\n * Direct write path for `Editor.TextField` when NO canvas is mounted (with\n * one, writes route through the editor command path and arrive back here\n * via `setState`). Immutable update; last-write-wins.\n */\n updateTextLayer(name: string, text: string): void {\n let found = false;\n const elements = this.state.elements.map((el) => {\n if (nameOf(el) !== name) return el;\n found = true;\n return { ...el, text } as AnyElementConfig;\n });\n if (!found) {\n throw new EditorError(\n 'E_LAYER_NOT_FOUND',\n `no layer \"${name}\" in the current design state. Bindable layers: ` +\n `${JSON.stringify(this.bindableLayerNames())}.`,\n { layerName: name, validNames: this.bindableLayerNames(), docSlug: 'embed-mode' },\n );\n }\n this.setState({ ...this.state, elements });\n }\n\n /** ≥1 element with visible content (completeness rule C4): non-empty text,\n * an image with a URL, or a shape. Hidden elements don't count. */\n hasRenderableElement(): boolean {\n return this.state.elements.some((el) => {\n if ((el as { visible?: boolean }).visible === false) return false;\n const t = (el as { transformType?: string }).transformType;\n if (t === 'image') return Boolean((el as { imageUrl?: string }).imageUrl);\n if (t === 'shape') return true;\n if (t === 'group' || t === 'path') return true;\n const text = textOf(el);\n return typeof text === 'string' && text.trim().length > 0;\n });\n }\n\n private emit(): void {\n for (const l of [...this.listeners]) l();\n }\n}\n","/**\n * The ONE commerce-selection state under an `Editor.Root` (ADR-0085 §2, P2 —\n * \"Buy-owned variant + quantity state\").\n *\n * Ownership model: `Editor.Buy` OWNS this state (it gates on it and assembles\n * the cart payload from it); the HOST renders the variant-selection UI and\n * reads/writes the same state through `useProductSelection()` — parts carry\n * behavior, hosts own layout/markup (the rendering contract). The state does\n * NOT live on Root props: changing `product.variantId` up there re-keys the\n * whole RenderSession (WS teardown + re-grant + reconnect per color click),\n * which is session identity, not user selection.\n *\n * host variant UI ──select()──┐\n * ├─→ CommerceStateStore ─→ resolvedVariantId ─→ session.setProduct\n * Editor.Buy ──reads─────────┘ │ (live config, no re-key) + re-push state\n * └─→ completeness (C1/C5) + cart payload\n *\n * Selection resolution is the SDK's: `validateProductSelection` +\n * `findBestCombination` (the C1 amendment: full resolution replaces the\n * color-axis-only gate). Like `DesignStateStore`, this is a tiny hand-rolled\n * external store — narrow `useSyncExternalStore` subscriptions, no state lib.\n */\n\nimport {\n computeDisabledChoices,\n findBestCombination,\n getMissingSelections,\n toCombinations,\n toOptionAttributes,\n validateProductSelection,\n type Combination,\n type OptionAttribute,\n type OptionSelection,\n type RenderProduct,\n} from '@snowcone-app/sdk';\nimport { EditorError } from '../../errors/editorError.js';\n\n/**\n * One choice of a variant attribute as the commerce store HANDS IT OUT —\n * always the catalog's choice OBJECT (`toOptionAttributes` normalizes bare\n * strings to `{ label }`). A `hex` marks a color-axis choice (render it as a\n * swatch). NOTE the currency mismatch this type exists to make honest: the\n * SDK's `OptionAttribute` declares `choices: string[]` for its selection\n * math, but the runtime objects flowing through this store are these.\n */\nexport interface ProductOptionChoice {\n label?: string;\n hex?: string;\n [key: string]: unknown;\n}\n\n/** An attribute as `useProductSelection().attributes` returns it: the SDK\n * shape with the choices typed as the objects they actually are. The\n * CURRENCY for `select()` / `selection` / `disabledChoices` is the choice's\n * `label` STRING — pass `choice.label`, never the object. */\nexport interface ProductSelectionAttribute extends Omit<OptionAttribute, 'choices'> {\n choices: ProductOptionChoice[];\n}\n\n/** The label strings of an attribute's choices (legacy attrs may carry bare\n * strings; normalized attrs carry `{ label, hex?, … }` objects). */\nexport function choiceLabelsOf(attr: OptionAttribute | ProductSelectionAttribute): string[] {\n return ((attr.choices ?? []) as Array<string | ProductOptionChoice>)\n .map((c) => (typeof c === 'string' ? c : (c.label ?? '')))\n .filter((label) => label !== '');\n}\n\n/** Derive the seed selection from the product's initial `variantId` — the\n * combination it resolves to pins one value per variant-affecting attribute.\n * No `variantId` (or no match) seeds an empty selection. */\nexport function seedSelectionOf(product: RenderProduct, combinations: Combination[]): OptionSelection {\n if (!product.variantId) return {};\n const combination = combinations.find((c) => c.variantId === product.variantId);\n if (!combination) return {};\n const selection: OptionSelection = {};\n for (const [key, value] of Object.entries(combination)) {\n if (key === 'variantId' || key === 'price') continue;\n if (typeof value === 'string') selection[key] = value;\n else if (typeof value === 'number') selection[key] = String(value);\n }\n return selection;\n}\n\nexport class CommerceStateStore {\n private product: RenderProduct;\n private attrs: Record<string, OptionAttribute>;\n private combos: Combination[];\n private selection: OptionSelection;\n private quantity = 1;\n private version = 0;\n private readonly listeners = new Set<() => void>();\n\n constructor(product: RenderProduct) {\n this.product = product;\n this.attrs = toOptionAttributes({ options: product.options } as Parameters<typeof toOptionAttributes>[0]);\n this.combos = toCombinations({ options: product.options } as Parameters<typeof toCombinations>[0]);\n this.selection = seedSelectionOf(product, this.combos);\n }\n\n // Arrows on purpose: handed bare to `useSyncExternalStore`.\n getVersion = (): number => this.version;\n\n subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n };\n\n getAttributes(): Record<string, ProductSelectionAttribute> {\n // `toOptionAttributes` always normalizes choices to objects (bare strings\n // become `{ label }`), so this narrowing is true by construction. The SDK\n // type's `choices: string[]` describes its selection-math currency, not\n // the runtime shape — hence the through-unknown cast.\n return this.attrs as unknown as Record<string, ProductSelectionAttribute>;\n }\n\n getSelection(): OptionSelection {\n return this.selection;\n }\n\n getQuantity(): number {\n return this.quantity;\n }\n\n /**\n * Select a choice for a variant attribute. Strict + loud (D4/E3): an\n * attribute key or choice that doesn't exist on the product is a wiring\n * mistake, not user state — throws `E_UNKNOWN_OPTION` listing what IS valid.\n */\n select(key: string, choice: string): void {\n const attr = this.attrs[key];\n if (!attr) {\n throw new EditorError(\n 'E_UNKNOWN_OPTION',\n `product ${this.product.productId} has no option \"${key}\". ` +\n `Valid option keys: ${JSON.stringify(Object.keys(this.attrs))}.`,\n { key, validKeys: Object.keys(this.attrs), docSlug: 'embed-mode' },\n );\n }\n const labels = choiceLabelsOf(attr);\n if (labels.length > 0 && !labels.includes(choice)) {\n throw new EditorError(\n 'E_UNKNOWN_OPTION',\n `\"${choice}\" is not a choice of option \"${key}\" on product ${this.product.productId}. ` +\n `Valid choices: ${JSON.stringify(labels)}.`,\n { key, choice, validChoices: labels, docSlug: 'embed-mode' },\n );\n }\n if (this.selection[key] === choice) return;\n this.selection = { ...this.selection, [key]: choice };\n this.bump();\n }\n\n /** Quantity is USER state (completeness rule C5 gates on it) — never throws. */\n setQuantity(quantity: number): void {\n if (this.quantity === quantity) return;\n this.quantity = quantity;\n this.bump();\n }\n\n /** Attribute keys still required (non-optional) but unselected — Buy's\n * `option:<key>` reason codes. */\n missingOptionKeys(): string[] {\n if (Object.keys(this.attrs).length === 0) return [];\n return getMissingSelections(this.attrs, this.selection);\n }\n\n /** Full selection resolution (the C1 amendment): true when every required\n * attribute is selected AND the selection matches a valid combination. */\n selectionValid(): boolean {\n if (Object.keys(this.attrs).length === 0) return true;\n return validateProductSelection(this.attrs, this.selection, this.combos);\n }\n\n /** The variant (gvid) the current selection resolves to. Falls back to the\n * product's initial `variantId` while nothing has been selected. */\n resolvedVariantId(): string | undefined {\n if (Object.keys(this.attrs).length === 0 || this.combos.length === 0) {\n return this.product.variantId;\n }\n if (!this.selectionValid()) return undefined;\n const best = findBestCombination(this.selection, this.combos, this.attrs);\n return (typeof best?.variantId === 'string' && best.variantId !== '' ? best.variantId : undefined) ?? this.product.variantId;\n }\n\n /** Price of the resolved combination, when the catalog carries one. */\n resolvedPrice(): number | undefined {\n if (!this.selectionValid()) return undefined;\n const best = findBestCombination(this.selection, this.combos, this.attrs);\n return typeof best?.price === 'number' ? best.price : undefined;\n }\n\n /** Choices invalid given the rest of the current selection — for hosts to\n * disable/grey out in their variant UI. */\n disabledChoices(): Record<string, string[]> {\n // computeDisabledChoices compares choice strings to combination values, so\n // feed it label-string choices.\n const stringAttrs: Record<string, OptionAttribute> = {};\n for (const [key, attr] of Object.entries(this.attrs)) {\n stringAttrs[key] = { ...attr, choices: choiceLabelsOf(attr) as OptionAttribute['choices'] };\n }\n return computeDisabledChoices(this.selection, stringAttrs, this.combos);\n }\n\n /** The combinations (for payload assembly via `createCartDetail`). */\n getCombinations(): Combination[] {\n return this.combos;\n }\n\n private bump(): void {\n this.version++;\n for (const l of [...this.listeners]) l();\n }\n}\n","/**\n * useCommands - Hook for undo/redo and command history operations\n *\n * Provides a clean interface to command history functionality\n * Must be used within EditorProvider\n *\n * @example\n * ```tsx\n * function UndoRedoToolbar() {\n * const { undo, redo, canUndo, canRedo, clearHistory } = useCommands();\n *\n * return (\n * <div className=\"toolbar\">\n * <button onClick={undo} disabled={!canUndo}>\n * Undo (⌘Z)\n * </button>\n * <button onClick={redo} disabled={!canRedo}>\n * Redo (⌘⇧Z)\n * </button>\n * <button onClick={clearHistory}>\n * Clear History\n * </button>\n * </div>\n * );\n * }\n * ```\n */\n\nimport { useCallback } from 'react';\nimport { useEditor } from '../contexts/EditorContext.js';\nimport { createLogger } from '../utils/logger.js';\n\nconst logger = createLogger('useCommands');\n\nexport interface UseCommandsReturn {\n // Undo/Redo\n undo: () => void;\n redo: () => void;\n canUndo: boolean;\n canRedo: boolean;\n\n // History management\n clearHistory: () => void;\n clearArtboardHistory: (artboardId: string) => void;\n\n // Command execution\n executeElementUpdate: ReturnType<typeof useEditor>['executeElementUpdate'];\n executeAddElement: ReturnType<typeof useEditor>['executeAddElement'];\n executeRemoveElement: ReturnType<typeof useEditor>['executeRemoveElement'];\n executeReorderElement: ReturnType<typeof useEditor>['executeReorderElement'];\n executeCreateArtboard: ReturnType<typeof useEditor>['executeCreateArtboard'];\n executeDeleteArtboard: ReturnType<typeof useEditor>['executeDeleteArtboard'];\n executeUpdateArtboard: ReturnType<typeof useEditor>['executeUpdateArtboard'];\n\n // Batch execution\n executeCommandBatch: (commands: Array<{ execute: () => void; undo: () => void }>) => void;\n}\n\n/**\n * Hook for accessing command history and undo/redo functionality\n * Must be used within EditorProvider\n *\n * @example\n * ```tsx\n * function MyComponent() {\n * const { undo, redo, canUndo, canRedo } = useCommands();\n * const { selectedElement } = useEditor();\n *\n * const handleDelete = () => {\n * if (selectedElement) {\n * executeRemoveElement(selectedElement);\n * }\n * };\n *\n * return (\n * <div>\n * <button onClick={undo} disabled={!canUndo}>Undo</button>\n * <button onClick={redo} disabled={!canRedo}>Redo</button>\n * <button onClick={handleDelete}>Delete</button>\n * </div>\n * );\n * }\n * ```\n */\nexport function useCommands(): UseCommandsReturn {\n const context = useEditor();\n\n // Extract command history methods\n const {\n undo,\n redo,\n canUndo,\n canRedo,\n executeElementUpdate,\n executeAddElement,\n executeRemoveElement,\n executeReorderElement,\n executeCommandBatch,\n executeCreateArtboard,\n executeDeleteArtboard,\n executeUpdateArtboard,\n } = context;\n\n // Clear all history (not exposed in EditorContext yet, so create a placeholder)\n const clearHistory = useCallback(() => {\n logger.warn('[useCommands] clearHistory is not yet implemented in EditorContext');\n }, []);\n\n // Clear artboard-specific history (not exposed in EditorContext yet, so create a placeholder)\n const clearArtboardHistory = useCallback((_artboardId: string) => {\n logger.warn('[useCommands] clearArtboardHistory is not yet implemented in EditorContext');\n }, []);\n\n return {\n // Undo/Redo\n undo,\n redo,\n canUndo,\n canRedo,\n\n // History management\n clearHistory,\n clearArtboardHistory,\n\n // Command execution\n executeElementUpdate,\n executeAddElement,\n executeRemoveElement,\n executeReorderElement,\n executeCreateArtboard,\n executeDeleteArtboard,\n executeUpdateArtboard,\n\n // Batch execution\n executeCommandBatch,\n };\n}\n","import { useEditor } from '../contexts/EditorContext.js';\nimport type { EditorElement } from '../contexts/EditorContext.js';\n\n/**\n * Returns the currently selected element, or null if nothing is selected.\n *\n * This is a convenience wrapper around `useEditor()` that only extracts\n * selection state, keeping consumer components focused on what they need.\n *\n * @example\n * ```tsx\n * function PropertiesPanel() {\n * const selected = useSelectedElement();\n * if (!selected) return <p>Nothing selected</p>;\n * return <p>Selected: {selected.id}</p>;\n * }\n * ```\n */\nexport function useSelectedElement(): EditorElement | null {\n const { selectedElement } = useEditor();\n return selectedElement ?? null;\n}\n","/**\n * useDeadBindingWarning - Dev-only diagnostic for \"dead\" binding hooks.\n *\n * `useTextBinding('typo')` / `useImageBinding('typo')` on a layer name that\n * matches no element returns `isConnected: false` with no-op setters — by\n * design. But with no diagnostic, a typo'd layer name produces a dead control\n * with ZERO console output (the silent-failure finding from the embed-SDK DX\n * evaluation). This hook emits a one-time, dev-only `console.warn` naming the\n * requested layer and listing the canvas's named layers — the same\n * silent-blank-guard pattern as the SDK's `warnImagelessElements` /\n * `[RealtimeEmbed]` validateEmbed warnings.\n *\n * Timing is settle-aware: elements may legitimately arrive late\n * (`initialElements` seeding, an async state load), so warning on first render\n * would false-fire constantly. The `ElementStore` is immutable — every mutation\n * hands the context a NEW store instance, which re-runs the effect — so the\n * grace timer re-arms on every element change and only fires once the element\n * set has been quiet for {@link DEAD_BINDING_GRACE_MS} with still no match.\n * Connecting (or unmounting — StrictMode's throwaway first mount included)\n * clears the pending timer.\n *\n * @module\n */\n\nimport { useEffect } from 'react';\nimport type { ElementStore, StoreElement } from '../core/ElementStore.js';\nimport { TextElement } from '../core/TextElement.js';\nimport { ImageElement } from '../core/ImageElement.js';\n\n/** The binding hook flavor (font binds to TEXT layers — see TARGET_KIND). */\nexport type BindingKind = 'text' | 'image' | 'font';\n\n/**\n * How long the element set must be SETTLED (no store changes) with the binding\n * still unmatched before the warning fires. Long enough for `initialElements`\n * seeding and async state loads to land; short enough to surface a typo well\n * before the user gives up on the dead control.\n */\nexport const DEAD_BINDING_GRACE_MS = 3000;\n\nconst HOOK_NAME: Record<BindingKind, string> = {\n text: 'useTextBinding',\n image: 'useImageBinding',\n font: 'useFontBinding',\n};\n\nconst SETTER_NAME: Record<BindingKind, string> = {\n text: 'setText',\n image: 'setImageUrl',\n font: 'setFontFamily',\n};\n\n/** The element flavor each hook actually matches (font targets text layers). */\nconst TARGET_KIND: Record<BindingKind, 'text' | 'image'> = {\n text: 'text',\n image: 'image',\n font: 'text',\n};\n\n/** Layer names already warned about — the warning is one-time per page load. */\nconst warned = new Set<string>();\n\n/** Test-only: forget which dead bindings have already been warned about. */\nexport function resetDeadBindingWarnings(): void {\n warned.clear();\n}\n\nfunction kindOf(el: StoreElement): string {\n if (el instanceof TextElement) return 'text';\n if (el instanceof ImageElement) return 'image';\n return 'other';\n}\n\n/**\n * Build the dead-binding warning message. Exported for tests; the message\n * distinguishes the two failure shapes:\n * - the name matches a layer of the WRONG type → point at the right hook\n * - the name matches nothing → list the available named layers (or explain\n * how to name one when none carry a name)\n */\nexport function deadBindingWarning(kind: BindingKind, name: string, store: ElementStore): string {\n const tag = `[${HOOK_NAME[kind]}]`;\n const dead = `the binding is dead (isConnected: false, ${SETTER_NAME[kind]} is a no-op)`;\n\n const target = TARGET_KIND[kind];\n const sameName = store.getAllByName(name);\n if (sameName.length > 0) {\n const kinds = [...new Set(sameName.map(kindOf))];\n const other = target === 'text' ? 'image' : 'text';\n const hint =\n kinds.length === 1 && kinds[0] === other\n ? ` Bind it with ${HOOK_NAME[other]}(\"${name}\") instead.`\n : '';\n return (\n `${tag} the layer named \"${name}\" is ${kinds.join('/')}, not ${target} — ` +\n `${dead}.${hint}`\n );\n }\n\n const named = store\n .getAll()\n .filter((el) => el.name)\n .map((el) => `\"${el.name}\" (${kindOf(el)})`);\n const available = named.length\n ? `Named layers on this canvas: ${named.join(', ')}. Check the name for a typo.`\n : `No element on this canvas has a name — name one via design().${target}(…, ` +\n `{ name: '${name}' }) or the element's \\`name\\` property.`;\n return `${tag} no ${target} layer named \"${name}\" exists — ${dead}. ${available}`;\n}\n\n/**\n * Emit the one-time dead-binding warning once the element set settles with the\n * binding still disconnected. Used by `useTextBinding` / `useImageBinding`;\n * dev-only (compiled out of production via the `NODE_ENV` guard) and never\n * throws.\n */\nexport function useDeadBindingWarning(\n kind: BindingKind,\n name: string,\n store: ElementStore,\n isConnected: boolean,\n): void {\n useEffect(() => {\n if (isConnected) return;\n if (typeof process === 'undefined' || process.env?.NODE_ENV === 'production') return;\n const key = `${kind}:${name}`;\n if (warned.has(key)) return;\n\n // The store is immutable, so any element change re-runs this effect with a\n // new instance — re-arming the timer. It fires only once the element set\n // has been quiet for the full grace period with still no match.\n const timer = setTimeout(() => {\n if (warned.has(key)) return; // another component already warned for this name\n warned.add(key);\n console.warn(deadBindingWarning(kind, name, store));\n }, DEAD_BINDING_GRACE_MS);\n return () => clearTimeout(timer);\n }, [kind, name, store, isConnected]);\n}\n","/**\n * useTextBinding - Bidirectional text binding between HTML inputs and canvas text elements.\n *\n * Links an external input to one or more canvas text elements by their `name` property.\n * Multiple elements can share the same name — `setText` updates all of them.\n * Changes flow both ways: input → canvas via `setText`, and canvas edits\n * propagate back through the element store re-render.\n *\n * @example\n * ```tsx\n * function NameInput() {\n * const { text, setText, isConnected } = useTextBinding('headline');\n * return (\n * <input\n * value={text}\n * onChange={(e) => setText(e.target.value)}\n * disabled={!isConnected}\n * />\n * );\n * }\n * ```\n *\n * @module\n */\n\nimport { useMemo, useCallback } from 'react';\nimport { useElementsContext } from '../contexts/ElementsContext.js';\nimport { useCommandContext } from '../contexts/CommandContext.js';\nimport { TextElement } from '../core/TextElement.js';\nimport type { EditorElement } from '../contexts/EditorContext.js';\nimport { useDeadBindingWarning } from './useDeadBindingWarning.js';\n\n/** Result returned by {@link useTextBinding}. */\nexport interface TextBindingResult {\n /** Current plain text content (from first bound element). Empty string if disconnected. */\n text: string;\n /** Update text on all bound elements. No-op if disconnected. */\n setText: (text: string) => void;\n /** The first bound element, or null if no matching text element exists. */\n element: EditorElement | null;\n /** All bound text elements (empty array if disconnected). */\n elements: readonly EditorElement[];\n /** Whether at least one matching text element exists. */\n isConnected: boolean;\n}\n\nconst NOOP = () => {};\nconst EMPTY: readonly EditorElement[] = [];\n\n/**\n * Bind an HTML input to canvas text elements by their `name` property.\n *\n * Multiple elements can share the same name — `setText` updates all of them.\n * Text is read from the first matching element (render order).\n *\n * Must be used within an `EditorProvider`.\n *\n * @param name - The element name to bind to.\n * @returns Text value, setter, element references, and connection status.\n */\nexport function useTextBinding(name: string): TextBindingResult {\n const { elementStore } = useElementsContext();\n const { executeElementUpdate } = useCommandContext();\n\n const textElements = useMemo(() => {\n const all = elementStore.getAllByName(name);\n return all.filter((el): el is TextElement => el instanceof TextElement);\n }, [elementStore, name]);\n\n const setText = useCallback(\n (newText: string) => {\n for (const el of textElements) {\n const cloned = el.clone() as TextElement;\n cloned.setText(newText);\n executeElementUpdate(el, cloned);\n }\n },\n [textElements, executeElementUpdate],\n );\n\n // Dev-only: a name that never matches produces a dead control with no-op\n // setters — warn once the element set settles so a typo isn't silent.\n useDeadBindingWarning('text', name, elementStore, textElements.length > 0);\n\n if (textElements.length === 0) {\n return { text: '', setText: NOOP, element: null, elements: EMPTY, isConnected: false };\n }\n\n return {\n text: textElements[0].getText(),\n setText,\n element: textElements[0],\n elements: textElements,\n isConnected: true,\n };\n}\n","/**\n * useImageBinding - Bidirectional image URL binding between external inputs and canvas image elements.\n *\n * Links an external input to one or more canvas image elements by their `name` property.\n * Multiple elements can share the same name — `setImageUrl` updates all of them.\n * Changes flow both ways: input → canvas via `setImageUrl`, and canvas edits\n * propagate back through the element store re-render.\n *\n * @example\n * ```tsx\n * function LogoUpload() {\n * const { imageUrl, setImageUrl, isConnected } = useImageBinding('logo');\n * return (\n * <input\n * type=\"url\"\n * value={imageUrl}\n * onChange={(e) => setImageUrl(e.target.value)}\n * disabled={!isConnected}\n * />\n * );\n * }\n * ```\n *\n * @module\n */\n\nimport { useMemo, useCallback, useRef } from 'react';\nimport { useElementsContext } from '../contexts/ElementsContext.js';\nimport { useCommandContext } from '../contexts/CommandContext.js';\nimport { ImageElement } from '../core/ImageElement.js';\nimport type { EditorElement } from '../contexts/EditorContext.js';\nimport { useDeadBindingWarning } from './useDeadBindingWarning.js';\n\n/** How the image fits the element bounds. */\nexport type ImageFitMode = 'cover' | 'contain';\n\n/** Options for {@link useImageBinding}. */\nexport interface ImageBindingOptions {\n /** How the image fits the element bounds. Default: \"cover\". */\n fit?: ImageFitMode;\n}\n\n/** Result returned by {@link useImageBinding}. */\nexport interface ImageBindingResult {\n /** Current image URL (from first bound element). Empty string if disconnected. */\n imageUrl: string;\n /** Update image URL on all bound elements. No-op if disconnected. */\n setImageUrl: (url: string) => void;\n /** The first bound element, or null if no matching image element exists. */\n element: EditorElement | null;\n /** All bound image elements (empty array if disconnected). */\n elements: readonly EditorElement[];\n /** Whether at least one matching image element exists. */\n isConnected: boolean;\n}\n\nconst NOOP = () => {};\nconst EMPTY: readonly EditorElement[] = [];\n\n/**\n * Calculate center-crop values so the visible area fills the original element bounds.\n */\nfunction coverCrop(\n origWidth: number,\n origHeight: number,\n imageAspectRatio: number,\n) {\n const placeholderAR = origWidth / origHeight;\n\n if (imageAspectRatio >= placeholderAR) {\n // Image is wider — match height, crop width\n const frameHeight = origHeight;\n const frameWidth = frameHeight * imageAspectRatio;\n const cropWidth = origWidth / frameWidth;\n return {\n width: frameWidth,\n height: frameHeight,\n cropX: (1 - cropWidth) / 2,\n cropY: 0,\n cropWidth,\n cropHeight: 1,\n };\n } else {\n // Image is taller — match width, crop height\n const frameWidth = origWidth;\n const frameHeight = frameWidth / imageAspectRatio;\n const cropHeight = origHeight / frameHeight;\n return {\n width: frameWidth,\n height: frameHeight,\n cropX: 0,\n cropY: (1 - cropHeight) / 2,\n cropWidth: 1,\n cropHeight,\n };\n }\n}\n\n/**\n * Bind an external input to canvas image elements by their `name` property.\n *\n * Multiple elements can share the same name — `setImageUrl` updates all of them.\n * The image URL is read from the first matching element (render order).\n *\n * Must be used within an `EditorProvider`.\n *\n * @param name - The element name to bind to.\n * @param options - Optional configuration (fit mode, etc.).\n * @returns Image URL value, setter, element references, and connection status.\n */\nexport function useImageBinding(name: string, options?: ImageBindingOptions): ImageBindingResult {\n const fit = options?.fit ?? 'cover';\n const { elementStore, setElements } = useElementsContext();\n const { executeElementUpdate } = useCommandContext();\n\n const imageElements = useMemo(() => {\n const all = elementStore.getAllByName(name);\n return all.filter((el): el is ImageElement => el instanceof ImageElement);\n }, [elementStore, name]);\n\n // Capture the original placeholder dimensions once (from the first time we see each element).\n // All subsequent image replacements fit within this fixed box.\n const origDimsRef = useRef<Map<string, { width: number; height: number }>>(new Map());\n for (const el of imageElements) {\n if (!origDimsRef.current.has(el.id)) {\n const td = el.transformData;\n origDimsRef.current.set(el.id, {\n width: td.width * td.cropWidth,\n height: td.height * td.cropHeight,\n });\n }\n }\n\n // Use refs for values that change on every element update to keep setImageUrl stable.\n // Without this, setImageUrl gets a new identity after every executeElementUpdate call,\n // which causes infinite loops when used in useEffect dependency arrays.\n const imageElementsRef = useRef(imageElements);\n imageElementsRef.current = imageElements;\n const executeRef = useRef(executeElementUpdate);\n executeRef.current = executeElementUpdate;\n const setElementsRef = useRef(setElements);\n setElementsRef.current = setElements;\n\n const setImageUrl = useCallback(\n (url: string) => {\n const currentElements = imageElementsRef.current;\n const exec = executeRef.current;\n\n for (const el of currentElements) {\n const orig = origDimsRef.current.get(el.id);\n if (!orig) continue;\n const { width: origW, height: origH } = orig;\n\n const cloned = el.clone() as ImageElement;\n cloned.imageLoaded = false;\n cloned.imageElement = null;\n cloned.isCropping = false;\n cloned.imageUrl = url;\n\n if (fit === 'cover') {\n cloned.preserveDimensions = true;\n\n cloned.onLoadCallback = (loadedElement) => {\n const imgAR = loadedElement.imageAspectRatio || 1;\n const crop = coverCrop(origW, origH, imgAR);\n\n loadedElement.transformData.width = crop.width;\n loadedElement.transformData.height = crop.height;\n loadedElement.transformData.cropX = crop.cropX;\n loadedElement.transformData.cropY = crop.cropY;\n loadedElement.transformData.cropWidth = crop.cropWidth;\n loadedElement.transformData.cropHeight = crop.cropHeight;\n\n // Single atomic update: command history + element store.\n // This ensures auto-export only sees the final cropped state,\n // not an intermediate unloaded state that would produce wrong mockups.\n exec(el, loadedElement);\n };\n } else {\n cloned.preserveDimensions = false;\n\n cloned.onLoadCallback = (loadedElement) => {\n const w = loadedElement.transformData.width;\n const h = loadedElement.transformData.height;\n const scale = Math.min(origW / w, origH / h, 1);\n if (scale < 1) {\n loadedElement.transformData.width = w * scale;\n loadedElement.transformData.height = h * scale;\n }\n loadedElement.transformData.cropX = 0;\n loadedElement.transformData.cropY = 0;\n loadedElement.transformData.cropWidth = 1;\n loadedElement.transformData.cropHeight = 1;\n\n exec(el, loadedElement);\n };\n }\n\n // Start loading — onLoadCallback will update the store via exec()\n // once the image is ready with final dimensions/crop.\n cloned.loadImage(url);\n }\n },\n [fit], // Stable deps only — imageElements/executeElementUpdate/setElements accessed via refs\n );\n\n // Dev-only: a name that never matches produces a dead control with no-op\n // setters — warn once the element set settles so a typo isn't silent.\n useDeadBindingWarning('image', name, elementStore, imageElements.length > 0);\n\n if (imageElements.length === 0) {\n return { imageUrl: '', setImageUrl: NOOP, element: null, elements: EMPTY, isConnected: false };\n }\n\n return {\n imageUrl: imageElements[0].imageUrl,\n setImageUrl,\n element: imageElements[0],\n elements: imageElements,\n isConnected: true,\n };\n}\n","/**\n * useColorBinding - Bind an external color control to every element painted a given color.\n *\n * Unlike `useTextBinding` / `useImageBinding` (which bind by element `name`),\n * a color binding matches by VALUE: every element whose text color, shape\n * fill, path stroke color, or stroke-effect color equals the bound color is\n * updated together. This is how an editable template exposes \"Accent Color\" —\n * the designer picks a color once, and the buyer's swatch repaints every\n * element that used it.\n *\n * The hook tracks the *currently applied* color: after `setColor('#00FF00')`,\n * subsequent matches (and the next `setColor`) are computed against the new\n * color, so repeated changes keep following the same set of elements.\n *\n * @example\n * ```tsx\n * function AccentSwatch({ field }: { field: { color: string; label: string } }) {\n * const { color, setColor, isConnected } = useColorBinding(field.color);\n * return (\n * <input\n * type=\"color\"\n * value={color}\n * onChange={(e) => setColor(e.target.value)}\n * disabled={!isConnected}\n * />\n * );\n * }\n * ```\n *\n * @module\n */\n\nimport { useMemo, useState, useCallback } from 'react';\nimport { useElementsContext } from '../contexts/ElementsContext.js';\nimport { useCommandContext } from '../contexts/CommandContext.js';\nimport type { EditorElement } from '../contexts/EditorContext.js';\n\n/** Result returned by {@link useColorBinding}. */\nexport interface ColorBindingResult {\n /** The currently applied color (normalized uppercase hex). */\n color: string;\n /** Repaint all matching elements. No-op if the value is unchanged. */\n setColor: (color: string) => void;\n /** All elements currently matching the applied color. */\n elements: readonly EditorElement[];\n /** Whether at least one element currently carries the applied color. */\n isConnected: boolean;\n}\n\nconst EMPTY: readonly EditorElement[] = [];\n\n/** Normalize any hex color to uppercase 6-digit form (#RGB → #RRGGBB). */\nfunction normalizeHex(color: string): string {\n let hex = color.trim().toUpperCase();\n if (hex.length === 4 && hex.startsWith('#')) {\n hex = '#' + hex[1] + hex[1] + hex[2] + hex[2] + hex[3] + hex[3];\n }\n return hex;\n}\n\n/** The color-carrying slots a canvas element may have. */\ninterface ColorCarrier {\n color?: unknown;\n setColor?: (c: string) => void;\n transformData?: { fillColor?: unknown; strokeColor?: unknown };\n stroke?: { enabled?: boolean; color?: unknown };\n}\n\nfunction slotMatches(value: unknown, match: string): boolean {\n return typeof value === 'string' && normalizeHex(value) === match;\n}\n\n/** Whether any color slot on the element equals `match` (normalized hex). */\nfunction elementMatchesColor(el: EditorElement, match: string): boolean {\n const c = el as unknown as ColorCarrier;\n return (\n slotMatches(c.color, match) ||\n slotMatches(c.transformData?.fillColor, match) ||\n slotMatches(c.transformData?.strokeColor, match) ||\n (c.stroke?.enabled === true && slotMatches(c.stroke.color, match))\n );\n}\n\n/**\n * Repaint every matching slot on a clone of `el`. Returns the clone if any\n * slot matched, or null if the element doesn't carry the color.\n */\nfunction applyColorToClone(\n el: EditorElement,\n match: string,\n newColor: string,\n): EditorElement | null {\n if (!elementMatchesColor(el, match)) return null;\n\n const cloned = el.clone() as EditorElement;\n const src = el as unknown as ColorCarrier;\n const dst = cloned as unknown as ColorCarrier;\n\n // Text elements: use setColor so richText spans update too.\n if (slotMatches(src.color, match)) {\n if (typeof dst.setColor === 'function') {\n dst.setColor(newColor);\n } else {\n dst.color = newColor;\n }\n }\n\n // Shape/Path elements: fill and stroke colors live in transformData.\n if (slotMatches(src.transformData?.fillColor, match)) {\n dst.transformData = { ...dst.transformData, fillColor: newColor };\n }\n if (slotMatches(src.transformData?.strokeColor, match)) {\n dst.transformData = { ...dst.transformData, strokeColor: newColor };\n }\n\n // Stroke effect (outline) color.\n if (src.stroke?.enabled === true && slotMatches(src.stroke.color, match)) {\n dst.stroke = { ...dst.stroke, color: newColor };\n }\n\n return cloned;\n}\n\n/**\n * Bind an external color control to all elements painted `originalColor`.\n *\n * Must be used within an `EditorProvider`.\n *\n * @param originalColor - The hex color to match (the template field's `color`).\n * @returns Applied color, setter, matching elements, and connection status.\n */\nexport function useColorBinding(originalColor: string): ColorBindingResult {\n const { elementStore } = useElementsContext();\n const { executeElementUpdate } = useCommandContext();\n\n const [applied, setApplied] = useState(() => normalizeHex(originalColor));\n\n // If the hook is re-bound to a different template field, restart tracking.\n const [prevOriginal, setPrevOriginal] = useState(originalColor);\n if (originalColor !== prevOriginal) {\n setPrevOriginal(originalColor);\n setApplied(normalizeHex(originalColor));\n }\n\n // ElementStore is immutable — every mutation hands the context a new store\n // instance, so this memo recomputes whenever elements change.\n const matching = useMemo(\n () => elementStore.getAll().filter((el) => elementMatchesColor(el, applied)),\n [elementStore, applied],\n );\n\n const setColor = useCallback(\n (newColor: string) => {\n const normalizedNew = normalizeHex(newColor);\n if (normalizedNew === applied) return;\n\n for (const el of elementStore.getAll()) {\n const cloned = applyColorToClone(el, applied, newColor);\n if (cloned) executeElementUpdate(el, cloned);\n }\n setApplied(normalizedNew);\n },\n [elementStore, applied, executeElementUpdate],\n );\n\n if (matching.length === 0) {\n return { color: applied, setColor, elements: EMPTY, isConnected: false };\n }\n\n return { color: applied, setColor, elements: matching, isConnected: true };\n}\n","/**\n * useFontBinding - Bind an external font picker to canvas text elements.\n *\n * Links a control to one or more canvas TEXT elements by their `name` property\n * (same matching as `useTextBinding`). `setFontFamily` updates all of them and\n * loads the Google Font into the document, so a family the page hasn't used\n * yet still renders. This is how an editable template exposes a\n * designer-curated font choice (a `select` template field with\n * `property: 'fontFamily'`).\n *\n * Fonts must be on Google Fonts — the picker ecosystem is Google-only so\n * designs render identically across platforms (system fonts are deny-listed).\n *\n * @example\n * ```tsx\n * function FontPicker({ options }: { options: string[] }) {\n * const { fontFamily, setFontFamily, isConnected } = useFontBinding('headline');\n * if (!isConnected) return null;\n * return (\n * <select value={fontFamily} onChange={(e) => setFontFamily(e.target.value)}>\n * {options.map((f) => <option key={f} value={f}>{f}</option>)}\n * </select>\n * );\n * }\n * ```\n *\n * @module\n */\n\nimport { useMemo, useCallback } from 'react';\nimport { useElementsContext } from '../contexts/ElementsContext.js';\nimport { useCommandContext } from '../contexts/CommandContext.js';\nimport { TextElement } from '../core/TextElement.js';\nimport type { EditorElement } from '../contexts/EditorContext.js';\nimport { FontAnalyzer } from '../utils/FontAnalyzer.js';\nimport { UnifiedFontService } from '../utils/UnifiedFontService.js';\nimport { useDeadBindingWarning } from './useDeadBindingWarning.js';\n\n/** Result returned by {@link useFontBinding}. */\nexport interface FontBindingResult {\n /** Current font family (from first bound element). Empty string if disconnected. */\n fontFamily: string;\n /** Update the font family on all bound text elements. No-op if disconnected. */\n setFontFamily: (fontFamily: string) => void;\n /** The first bound element, or null if no matching text element exists. */\n element: EditorElement | null;\n /** All bound text elements (empty array if disconnected). */\n elements: readonly EditorElement[];\n /** Whether at least one matching text element exists. */\n isConnected: boolean;\n}\n\nconst NOOP = () => {};\nconst EMPTY: readonly EditorElement[] = [];\n\n/**\n * Bind a font control to canvas text elements by their `name` property.\n *\n * Must be used within an `EditorProvider`.\n *\n * @param name - The element name to bind to.\n * @returns Font family, setter, element references, and connection status.\n */\nexport function useFontBinding(name: string): FontBindingResult {\n const { elementStore } = useElementsContext();\n const { executeElementUpdate } = useCommandContext();\n\n const textElements = useMemo(() => {\n const all = elementStore.getAllByName(name);\n return all.filter((el): el is TextElement => el instanceof TextElement);\n }, [elementStore, name]);\n\n const setFontFamily = useCallback(\n (newFamily: string) => {\n // Make sure the family is actually available in the document — a buyer\n // picking a font the page never used would otherwise see the fallback.\n UnifiedFontService.loadGoogleFontByName(newFamily);\n\n for (const el of textElements) {\n if (el.fontFamily === newFamily) continue;\n // Old-family glyph caches are per-font and large on iOS — drop them\n // when switching, same as the editor's own font picker.\n FontAnalyzer.clearCache(el.fontFamily);\n const cloned = el.clone() as TextElement;\n cloned.fontFamily = newFamily;\n executeElementUpdate(el, cloned);\n }\n },\n [textElements, executeElementUpdate],\n );\n\n useDeadBindingWarning('font', name, elementStore, textElements.length > 0);\n\n if (textElements.length === 0) {\n return { fontFamily: '', setFontFamily: NOOP, element: null, elements: EMPTY, isConnected: false };\n }\n\n return {\n fontFamily: textElements[0].fontFamily,\n setFontFamily,\n element: textElements[0],\n elements: textElements,\n isConnected: true,\n };\n}\n","/**\n * useElementByName - Look up an element by its `name` property.\n *\n * General-purpose complement to {@link useElementById}. Returns the first\n * element whose `name` matches, following render order.\n *\n * @example\n * ```tsx\n * function ElementInspector({ elementName }: { elementName: string }) {\n * const element = useElementByName(elementName);\n * if (!element) return <p>Element not found</p>;\n * return <p>Position: ({element.x}, {element.y})</p>;\n * }\n * ```\n *\n * @module\n */\n\nimport { useElementsContext } from '../contexts/ElementsContext.js';\nimport type { EditorElement } from '../contexts/EditorContext.js';\n\n/**\n * Returns the first element matching the given name, or null.\n *\n * Must be used within an `EditorProvider`.\n *\n * @param name - The element name to look up, or null to skip the lookup.\n * @returns The matching element, or null if no element matches.\n */\nexport function useElementByName(name: string | null): EditorElement | null {\n const { elementStore } = useElementsContext();\n if (!name) return null;\n return elementStore.getByName(name) ?? null;\n}\n","/**\n * Template fields — the manifest that turns a saved design into an editable template.\n *\n * An editable template is a saved canvas state plus a list of {@link TemplateField}s\n * describing which parts a buyer may change. Text and image fields reference\n * elements by their `name` property (the same names `useTextBinding` /\n * `useImageBinding` bind to); color fields match by value (`useColorBinding`).\n *\n * The fields are stored ON the state document itself under the\n * {@link TEMPLATE_FIELDS_KEY} key (`personalization`) — the same convention\n * snowcone.app's own editor uses, so a template authored in a host app\n * round-trips through Edit / Remix / the PDP unchanged:\n *\n * ```json\n * {\n * \"elements\": [...],\n * \"artboards\": [...],\n * \"activeArtboard\": \"Front\",\n * \"personalization\": [\n * { \"type\": \"text\", \"name\": \"headline\", \"label\": \"Your name\" }\n * ]\n * }\n * ```\n *\n * Write with {@link withTemplateFields}, read back with {@link readTemplateFields}.\n *\n * @module\n */\n\nimport { z } from 'zod';\nimport type { ImageFitMode } from '../hooks/useImageBinding.js';\n\n/** A buyer-editable text slot, bound to elements by their `name` property. */\nexport interface TemplateTextField {\n type: 'text';\n /** Element name (matches canvas layer `name` property). */\n name: string;\n /** Label shown to the buyer (e.g. \"Your name\"). */\n label: string;\n /** Placeholder text for the input. */\n placeholder?: string;\n /**\n * Designer's length limit for the buyer's text — long names overflow fixed\n * layouts. Intent, not enforcement: your control applies it (an input's\n * `maxLength`); the canvas itself doesn't truncate.\n */\n maxLength?: number;\n /**\n * Artboard (page) this field is scoped to, by artboard NAME — the same\n * convention as the element `artboard` membership tag. In a multi-page\n * template (ADR-0086) the same element name can repeat on every page;\n * scoping disambiguates which page's element the field binds. Absent =\n * whole-design (legacy behavior: binds across all artboards).\n */\n artboard?: string;\n /** Optional grouping label — consecutive fields sharing a group render together. */\n group?: string;\n}\n\n/** A buyer-swappable image slot, bound to elements by their `name` property. */\nexport interface TemplateImageField {\n type: 'image';\n /** Element name (matches canvas layer `name` property). */\n name: string;\n /** Label shown to the buyer (e.g. \"Upload your logo\"). */\n label: string;\n /** Placeholder text for the input. */\n placeholder?: string;\n /** How the buyer's image fits the original element bounds. Default: \"cover\". */\n fit?: ImageFitMode;\n /**\n * Artboard (page) this field is scoped to, by artboard NAME — the same\n * convention as the element `artboard` membership tag. In a multi-page\n * template (ADR-0086) the same element name can repeat on every page;\n * scoping disambiguates which page's element the field binds. Absent =\n * whole-design (legacy behavior: binds across all artboards).\n */\n artboard?: string;\n /** Optional grouping label — consecutive fields sharing a group render together. */\n group?: string;\n}\n\n/** A buyer-editable color, matched by value across all elements that use it. */\nexport interface TemplateColorField {\n type: 'color';\n /** Original hex color to match (e.g. \"#FF0000\"). */\n color: string;\n /** Label shown to the buyer (e.g. \"Accent color\"). */\n label: string;\n /**\n * Artboard (page) this field is scoped to, by artboard NAME — the same\n * convention as the element `artboard` membership tag. In a multi-page\n * template (ADR-0086) the same element name can repeat on every page;\n * scoping disambiguates which page's element the field binds. Absent =\n * whole-design (legacy behavior: binds across all artboards).\n */\n artboard?: string;\n /** Optional grouping label — consecutive fields sharing a group render together. */\n group?: string;\n}\n\n/**\n * A pick-one choice over designer-authored options — \"one of these 3 badges\",\n * a curated font list, preset text variants. Binds to elements by `name` and\n * swaps ONE property on them, chosen by `property`:\n *\n * - `'text'` → apply via `useTextBinding(name).setText(value)`\n * - `'imageUrl'` → apply via `useImageBinding(name).setImageUrl(value)`\n * - `'fontFamily'` → apply via `useFontBinding(name).setFontFamily(value)`\n * (values must be Google Fonts families)\n */\nexport interface TemplateSelectField {\n type: 'select';\n /** Element name (matches canvas layer `name` property). */\n name: string;\n /** Label shown to the buyer (e.g. \"Badge\"). */\n label: string;\n /** Which property of the bound element(s) the chosen value sets. */\n property: 'text' | 'imageUrl' | 'fontFamily';\n /** The designer-authored choices, in display order. */\n options: Array<{ label: string; value: string }>;\n /**\n * Artboard (page) this field is scoped to, by artboard NAME — the same\n * convention as the element `artboard` membership tag. In a multi-page\n * template (ADR-0086) the same element name can repeat on every page;\n * scoping disambiguates which page's element the field binds. Absent =\n * whole-design (legacy behavior: binds across all artboards).\n */\n artboard?: string;\n /** Optional grouping label — consecutive fields sharing a group render together. */\n group?: string;\n}\n\n/** One buyer-editable aspect of a template. */\nexport type TemplateField =\n | TemplateTextField\n | TemplateImageField\n | TemplateColorField\n | TemplateSelectField;\n\n/**\n * The key template fields are stored under on the state document.\n * Kept as `personalization` for compatibility with designs saved on snowcone.app.\n */\nexport const TEMPLATE_FIELDS_KEY = 'personalization';\n\nconst templateFieldSchema = z.discriminatedUnion('type', [\n z.object({\n type: z.literal('text'),\n name: z.string().min(1),\n label: z.string(),\n placeholder: z.string().optional(),\n maxLength: z.number().int().positive().optional(),\n artboard: z.string().min(1).optional(),\n group: z.string().optional(),\n }),\n z.object({\n type: z.literal('image'),\n name: z.string().min(1),\n label: z.string(),\n placeholder: z.string().optional(),\n fit: z.union([z.literal('cover'), z.literal('contain')]).optional(),\n artboard: z.string().min(1).optional(),\n group: z.string().optional(),\n }),\n z.object({\n type: z.literal('color'),\n color: z.string().min(1),\n label: z.string(),\n artboard: z.string().min(1).optional(),\n group: z.string().optional(),\n }),\n z.object({\n type: z.literal('select'),\n name: z.string().min(1),\n label: z.string(),\n property: z.union([z.literal('text'), z.literal('imageUrl'), z.literal('fontFamily')]),\n options: z.array(z.object({ label: z.string(), value: z.string() })).min(1),\n artboard: z.string().min(1).optional(),\n group: z.string().optional(),\n }),\n]);\n\n/**\n * Read the template fields off a parsed state document.\n *\n * Accepts any JSON value — a `CanvasState` from `onChange`, a `CanvasStateV1`\n * document, or a raw `JSON.parse` of a stored state file. Legacy fields with\n * no `type` are normalized to text fields; malformed entries are dropped.\n * Returns `[]` when the document carries no fields (a plain, non-template design).\n */\nexport function readTemplateFields(state: unknown): TemplateField[] {\n if (!state || typeof state !== 'object') return [];\n const raw = (state as Record<string, unknown>)[TEMPLATE_FIELDS_KEY];\n if (!Array.isArray(raw)) return [];\n\n const fields: TemplateField[] = [];\n for (const entry of raw) {\n if (!entry || typeof entry !== 'object') continue;\n const candidate = 'type' in entry ? entry : { ...entry, type: 'text' };\n const parsed = templateFieldSchema.safeParse(candidate);\n if (parsed.success) fields.push(parsed.data as TemplateField);\n }\n return fields;\n}\n\n/**\n * Attach template fields to a state document before persisting it.\n *\n * ```ts\n * onChange={(state) => setDraft(state)}\n * // …on save:\n * save(JSON.stringify(withTemplateFields(draft, fields)));\n * ```\n */\nexport function withTemplateFields<T extends object>(\n state: T,\n fields: TemplateField[],\n): T & { [TEMPLATE_FIELDS_KEY]: TemplateField[] } {\n return { ...state, [TEMPLATE_FIELDS_KEY]: fields };\n}\n"],"names":["textOf","el","nameOf","DesignStateStore","seed","listener","seedTexts","name","text","next","layerKindOfConfig","e","n","found","elements","EditorError","t","l","choiceLabelsOf","attr","c","label","seedSelectionOf","product","combinations","combination","selection","key","value","CommerceStateStore","toOptionAttributes","toCombinations","choice","labels","quantity","getMissingSelections","validateProductSelection","best","findBestCombination","stringAttrs","computeDisabledChoices","logger","createLogger","useCommands","context","useEditor","undo","redo","canUndo","canRedo","executeElementUpdate","executeAddElement","executeRemoveElement","executeReorderElement","executeCommandBatch","executeCreateArtboard","executeDeleteArtboard","executeUpdateArtboard","clearHistory","useCallback","clearArtboardHistory","_artboardId","useSelectedElement","selectedElement","DEAD_BINDING_GRACE_MS","HOOK_NAME","SETTER_NAME","TARGET_KIND","warned","kindOf","TextElement","ImageElement","deadBindingWarning","kind","store","tag","dead","target","sameName","kinds","other","hint","named","available","useDeadBindingWarning","isConnected","useEffect","process","timer","NOOP","EMPTY","useTextBinding","elementStore","useElementsContext","useCommandContext","textElements","useMemo","setText","newText","cloned","coverCrop","origWidth","origHeight","imageAspectRatio","placeholderAR","frameHeight","frameWidth","cropWidth","cropHeight","useImageBinding","options","fit","setElements","imageElements","origDimsRef","useRef","td","imageElementsRef","executeRef","setElementsRef","setImageUrl","url","currentElements","exec","orig","origW","origH","loadedElement","imgAR","crop","w","h","scale","normalizeHex","color","hex","slotMatches","match","elementMatchesColor","_a","_b","_c","applyColorToClone","newColor","src","dst","useColorBinding","originalColor","applied","setApplied","useState","prevOriginal","setPrevOriginal","matching","setColor","normalizedNew","useFontBinding","setFontFamily","newFamily","UnifiedFontService","FontAnalyzer","useElementByName","TEMPLATE_FIELDS_KEY","templateFieldSchema","z.discriminatedUnion","z.object","z.literal","z.string","z.number","z.union","z.array","readTemplateFields","state","raw","fields","entry","candidate","parsed","withTemplateFields"],"mappings":";;;;;;;AA0CA,SAASA,EAAOC,GAA0C;AACxD,SAAQA,EAAyB;AACnC;AAEA,SAASC,EAAOD,GAA0C;AACxD,SAAQA,EAAyB;AACnC;AAEO,MAAME,GAAiB;AAAA,EAO5B,YAAYC,GAAmB;AAF/B,SAAiB,gCAAgB,IAAA,GAcjC,KAAA,WAAW,MACF,KAAK,OAGd,KAAA,YA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