@snowcone-app/canvas 0.38.0 → 0.39.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 (33) hide show
  1. package/dist/{CanvasRenderer-D-E5WWLm.js → CanvasRenderer-COO5UXtZ.js} +704 -669
  2. package/dist/CanvasRenderer-COO5UXtZ.js.map +1 -0
  3. package/dist/{CanvasStateV1-C9LQt2J0.js → CanvasStateV1-CJJff7Ci.js} +315 -314
  4. package/dist/{CanvasStateV1-C9LQt2J0.js.map → CanvasStateV1-CJJff7Ci.js.map} +1 -1
  5. package/dist/{EditorCanvasImpl-BnxEbr2p.js → EditorCanvasImpl-C_72UKu3.js} +3 -3
  6. package/dist/{EditorCanvasImpl-BnxEbr2p.js.map → EditorCanvasImpl-C_72UKu3.js.map} +1 -1
  7. package/dist/FontAnalyzer-DWHS41ba.js.map +1 -1
  8. package/dist/{SnowconeCanvas-CWSPyqqj.js → SnowconeCanvas-C-YbGCcQ.js} +4 -4
  9. package/dist/{SnowconeCanvas-CWSPyqqj.js.map → SnowconeCanvas-C-YbGCcQ.js.map} +1 -1
  10. package/dist/advanced.mjs +358 -360
  11. package/dist/advanced.mjs.map +1 -1
  12. package/dist/components/VisualGuideOverlay.d.ts +4 -1
  13. package/dist/components/embed-realtime/usePieceGuideBundle.d.ts +2 -0
  14. package/dist/{embed-SOFUZlGB.js → embed-DtlgX9iG.js} +5 -5
  15. package/dist/{embed-SOFUZlGB.js.map → embed-DtlgX9iG.js.map} +1 -1
  16. package/dist/embed.mjs +3 -3
  17. package/dist/index.mjs +4 -4
  18. package/dist/internals.mjs +2 -2
  19. package/dist/rendering/PieceGuideRenderer.d.ts +4 -1
  20. package/dist/state/CanvasStateV1.d.ts +3 -3
  21. package/dist/{template-fields-CBLHgW7G.js → template-fields-Dltc4Ztb.js} +2 -2
  22. package/dist/{template-fields-CBLHgW7G.js.map → template-fields-Dltc4Ztb.js.map} +1 -1
  23. package/dist/types/index.d.ts +2 -1
  24. package/dist/{usePieceGuideBundle-C7r06a_x.js → usePieceGuideBundle-Cab2gRnn.js} +19 -16
  25. package/dist/usePieceGuideBundle-Cab2gRnn.js.map +1 -0
  26. package/dist/utils/pieceRotation.d.ts +35 -0
  27. package/dist/{validation-BG-V98h0.js → validation-Dh9sVEb9.js} +1428 -1430
  28. package/dist/validation-Dh9sVEb9.js.map +1 -0
  29. package/example/package.json +1 -1
  30. package/package.json +1 -1
  31. package/dist/CanvasRenderer-D-E5WWLm.js.map +0 -1
  32. package/dist/usePieceGuideBundle-C7r06a_x.js.map +0 -1
  33. package/dist/validation-BG-V98h0.js.map +0 -1
package/dist/embed.mjs CHANGED
@@ -1,10 +1,10 @@
1
1
  import { C as a, g as t, h as o, K as r, N as i, O as n, P as d, Q as m, R as u, b as l, a as E, j as c, k as p, l as g } from "./useCommands-x8J7_Mzy.js";
2
- import { E as C, R as S, a as T, b as f, S as P, c as R, d as b, e as B, f as F, g as v, i as y, h, p as k, s as D, j as I, k as L, l as K, v as w } from "./embed-SOFUZlGB.js";
2
+ import { E as C, R as S, a as T, b as f, S as P, c as R, d as b, e as B, f as F, g as v, i as y, h, p as k, s as D, j as I, k as L, l as K, v as w } from "./embed-DtlgX9iG.js";
3
3
  import { t as M, V as j } from "./FontAnalyzer-DWHS41ba.js";
4
4
  import { D as N, e as V, h as _, i as z, b as H } from "./design-builder-CoCtjIwj.js";
5
- import { D as O, T as Q, r as Y, u as q, a as U, b as W, c as X, d as Z, e as $, w as ee } from "./template-fields-CBLHgW7G.js";
5
+ import { D as O, T as Q, r as Y, u as q, a as U, b as W, c as X, d as Z, e as $, w as ee } from "./template-fields-Dltc4Ztb.js";
6
6
  import { F as ae, G as te, H as oe, J as re } from "./ExportManager-BbBfO22S.js";
7
- import { s as ne } from "./CanvasStateV1-C9LQt2J0.js";
7
+ import { s as ne } from "./CanvasStateV1-CJJff7Ci.js";
8
8
  export {
9
9
  a as CanvasServicesProvider,
10
10
  N as DesignBuilder,
package/dist/index.mjs CHANGED
@@ -1,13 +1,13 @@
1
1
  import { e as u } from "./useCommands-x8J7_Mzy.js";
2
2
  import { C as c, f as x, g as I, h as v, b as A, a as g, j as T, k as B, l as F } from "./useCommands-x8J7_Mzy.js";
3
- import { E as y, S as L, S as _, u as O, a as R } from "./SnowconeCanvas-CWSPyqqj.js";
3
+ import { E as y, S as L, S as _, u as O, a as R } from "./SnowconeCanvas-C-YbGCcQ.js";
4
4
  import { b as m, d } from "./design-builder-CoCtjIwj.js";
5
5
  import { C as z, D as w, e as D, s as K } from "./design-builder-CoCtjIwj.js";
6
- import { T as V, r as b, u as h, a as G, b as H, c as U, d as Y, e as Z, w as j } from "./template-fields-CBLHgW7G.js";
7
- import { A as J, C as q, E as Q, M as W, P as X, r as $, v as ee } from "./validation-BG-V98h0.js";
6
+ import { T as V, r as b, u as h, a as G, b as H, c as U, d as Y, e as Z, w as j } from "./template-fields-Dltc4Ztb.js";
7
+ import { A as J, C as q, E as Q, M as W, P as X, r as $, v as ee } from "./validation-Dh9sVEb9.js";
8
8
  import { F as ae, G as te, H as oe, J as re } from "./ExportManager-BbBfO22S.js";
9
9
  import { c as ie, e as ue } from "./compose-DtQL_oit.js";
10
- import { d as de, m as Ce, s as Se, v as Ee } from "./CanvasStateV1-C9LQt2J0.js";
10
+ import { d as de, m as Ce, s as Se, v as Ee } from "./CanvasStateV1-CJJff7Ci.js";
11
11
  function E() {
12
12
  const { isCanvasReady: e } = m();
13
13
  return e;
@@ -1,9 +1,9 @@
1
- import { A as rr, a as or, C as sr, I as er, R as nr, S as tr, T as ir } from "./CanvasRenderer-D-E5WWLm.js";
1
+ import { A as rr, a as or, C as sr, I as er, R as nr, S as tr, T as ir } from "./CanvasRenderer-COO5UXtZ.js";
2
2
  import { r as k } from "./ExportManager-BbBfO22S.js";
3
3
  import { D as hr, a as cr, I as dr, W as fr, b as gr, c as lr, d as ur, e as pr, f as yr, g as kr, h as vr, i as wr, j as Mr, k as Tr, l as Cr, m as Sr, n as br, o as Pr, p as Ir, q as mr, s as Ar, t as Rr, u as Wr, v as Er, w as Or, x as Hr, y as jr, z as Fr, A as Lr, B as Xr, C as zr } from "./ExportManager-BbBfO22S.js";
4
4
  import { i as H, a as j, c as F, r as L, b as X } from "./FontAnalyzer-DWHS41ba.js";
5
5
  import { d as _r, e as Br, f as Kr, C as Ur, g as Yr, E as Jr, F as Vr, H as qr, L as Gr, h as Qr, W as Zr, j as $r, k as xr, l as Dr, m as ro, n as oo, o as so, s as eo, w as no } from "./FontAnalyzer-DWHS41ba.js";
6
- import { A as io, a as ao, C as ho, S as co } from "./CanvasStateV1-C9LQt2J0.js";
6
+ import { A as io, a as ao, C as ho, S as co } from "./CanvasStateV1-CJJff7Ci.js";
7
7
  const z = F("image-adjustments"), v = 1e-3;
8
8
  function N(r, o) {
9
9
  const { brightness: i, contrast: s, saturation: h } = o, e = i * s, n = 127.5 * (1 - s), f = Math.abs(e - 1) > v || Math.abs(n) > v, a = new Uint8ClampedArray(256);
@@ -17,8 +17,11 @@ export interface PieceGuideRendererPiece {
17
17
  * legacy centered-inset fallback; otherwise omit.
18
18
  */
19
19
  safeAreaInsetPx?: number;
20
- /** Clockwise rotation in degrees about the piece center. Default 0. */
20
+ /** Clockwise rotation in degrees about the piece center (any multiple of 45). Default 0. */
21
21
  rotation?: number;
22
+ /** Natural (unrotated) size; required when `rotation` isn't a right angle (utils/pieceRotation.ts). */
23
+ naturalWidth?: number;
24
+ naturalHeight?: number;
22
25
  }
23
26
  export interface PieceGuideRendererStyle {
24
27
  /**
@@ -238,7 +238,7 @@ declare const ClipShapeSchema: z.ZodUnion<readonly [z.ZodLiteral<"rectangle">, z
238
238
  d: z.ZodString;
239
239
  x: z.ZodNumber;
240
240
  y: z.ZodNumber;
241
- rotation: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<0>, z.ZodLiteral<90>, z.ZodLiteral<180>, z.ZodLiteral<270>]>>;
241
+ rotation: z.ZodOptional<z.ZodNumber>;
242
242
  baseWidth: z.ZodOptional<z.ZodNumber>;
243
243
  baseHeight: z.ZodOptional<z.ZodNumber>;
244
244
  }, z.core.$strip>>;
@@ -270,7 +270,7 @@ declare const SerializedArtboardSchema: z.ZodObject<{
270
270
  d: z.ZodString;
271
271
  x: z.ZodNumber;
272
272
  y: z.ZodNumber;
273
- rotation: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<0>, z.ZodLiteral<90>, z.ZodLiteral<180>, z.ZodLiteral<270>]>>;
273
+ rotation: z.ZodOptional<z.ZodNumber>;
274
274
  baseWidth: z.ZodOptional<z.ZodNumber>;
275
275
  baseHeight: z.ZodOptional<z.ZodNumber>;
276
276
  }, z.core.$strip>>;
@@ -336,7 +336,7 @@ declare const CanvasStateV1Schema: z.ZodObject<{
336
336
  d: z.ZodString;
337
337
  x: z.ZodNumber;
338
338
  y: z.ZodNumber;
339
- rotation: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<0>, z.ZodLiteral<90>, z.ZodLiteral<180>, z.ZodLiteral<270>]>>;
339
+ rotation: z.ZodOptional<z.ZodNumber>;
340
340
  baseWidth: z.ZodOptional<z.ZodNumber>;
341
341
  baseHeight: z.ZodOptional<z.ZodNumber>;
342
342
  }, z.core.$strip>>;
@@ -3,7 +3,7 @@ import { l as G, b as ot, i as it, u as O, a as B, h as rt } from "./design-buil
3
3
  import { toOptionAttributes as at, toCombinations as ct, getMissingSelections as lt, validateProductSelection as mt, findBestCombination as F, computeDisabledChoices as ft } from "@snowcone-app/sdk";
4
4
  import { useEffect as ut, useContext as Z, useId as dt, useLayoutEffect as ht, useRef as C, useMemo as A, useCallback as _, useState as q } from "react";
5
5
  import { E as tt, U as gt } from "./useCommands-x8J7_Mzy.js";
6
- import { b as pt, o as $, c as f, n as bt, l as p, u as J, e as yt } from "./CanvasStateV1-C9LQt2J0.js";
6
+ import { b as pt, o as $, c as f, n as bt, l as p, u as J, e as yt } from "./CanvasStateV1-CJJff7Ci.js";
7
7
  function R(s) {
8
8
  return s.text;
9
9
  }
@@ -553,4 +553,4 @@ export {
553
553
  Vt as u,
554
554
  Xt as w
555
555
  };
556
- //# sourceMappingURL=template-fields-CBLHgW7G.js.map
556
+ //# sourceMappingURL=template-fields-Dltc4Ztb.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"template-fields-CBLHgW7G.js","sources":["../src/components/editor/designStateStore.ts","../src/components/editor/commerceStore.ts","../src/hooks/useSelectedElement.ts","../src/hooks/useDeadBindingWarning.ts","../src/hooks/bindingGuards.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 /** Artboard names in author order — the first is the base (ADR-0101). */\n artboardNames(): string[] {\n return this.state.artboards.map((a) => a.name);\n }\n\n /**\n * Split a placement out of the base (ADR-0101): clone the FIRST artboard\n * and every element on it into a new artboard named `label`. Elements get\n * fresh ids and the new artboard's membership tag. No-op when `label`\n * already has an artboard. Used when NO canvas is mounted — with one, the\n * editor document does the same through the CanvasBridge and the result\n * lands here via `setState`.\n */\n splitArtboard(label: string): void {\n const { artboards, elements } = this.state;\n const base = artboards[0];\n if (!base || artboards.some((a) => a.name === label)) return;\n const baseName = base.name;\n const onBase = (el: AnyElementConfig) => {\n const tag = (el as { artboard?: string }).artboard;\n return tag === undefined || tag === baseName;\n };\n const cloned = elements\n .filter(onBase)\n .map((el, i) => ({\n ...el,\n id: `${String((el as { id?: string }).id ?? 'el')}__${label}__${i}`,\n artboard: label,\n })) as AnyElementConfig[];\n this.setState({\n ...this.state,\n artboards: [...artboards, { ...base, name: label }],\n elements: [...elements, ...cloned],\n });\n }\n\n /**\n * Re-link a placement (ADR-0101): drop the artboard named `label` and every\n * element tagged to it, so the placement inherits the base again. No-op for\n * an unknown label. Refuses the base itself — that is what the others\n * inherit (`E_LINK_BASE`).\n */\n removeArtboard(label: string): void {\n const { artboards, elements } = this.state;\n if (artboards[0]?.name === label) {\n throw new EditorError(\n 'E_LINK_BASE',\n `\"${label}\" is the base artboard — every linked placement inherits it, so it ` +\n `cannot be re-linked. Link a split placement instead, or call linkAll(). ` +\n `Artboards: ${JSON.stringify(this.artboardNames())}.`,\n { artboardName: label, validNames: this.artboardNames().slice(1), docSlug: 'embed-mode' },\n );\n }\n if (!artboards.some((a) => a.name === label)) return;\n this.setState({\n ...this.state,\n artboards: artboards.filter((a) => a.name !== label),\n elements: elements.filter((el) => (el as { artboard?: string }).artboard !== label),\n activeArtboard: this.state.activeArtboard === label ? artboards[0]!.name : this.state.activeArtboard,\n });\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 /**\n * The variant (gvid) to RENDER with — deliberately looser than\n * {@link resolvedVariantId}. That one is Buy's currency: it returns\n * `undefined` while the selection is incomplete so completeness can gate.\n * But the PRODUCT PHOTO must follow the shopper's picks immediately —\n * \"choose the Oak frame\" should render Oak even while an unrelated axis\n * (size, pocket) is still unselected. This resolves the best combination\n * matching the CURRENT (possibly partial) selection, falling back to the\n * product's initial variant. (Before this split, switching a color swatch\n * with any axis unselected rendered nothing — the mockup silently stayed\n * on the old color.)\n */\n renderVariantId(): string | undefined {\n if (Object.keys(this.attrs).length === 0 || this.combos.length === 0) {\n return this.product.variantId;\n }\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","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 * Shared fail-loud guards for the chrome-binding hooks (`useTextBinding`,\n * `useImageBinding`, `useFontBinding`, `useColorBinding`) when they run under\n * an `<Editor.Root>` (ADR-0085 compositions). Outside a Root — legacy chrome\n * inside a raw `EditorProvider`, `<RealtimeCanvas>` overlay children — both\n * guards are inert and the hooks keep their historical warn-only behavior.\n *\n * Guard 1 — canvas requirement: the bindings mutate the editor document via\n * the command path, and only a mounted `Editor.Canvas` syncs that document to\n * the design store / live renders. In a canvas-free composition the document\n * is EMPTY (Root seeds only the artboard), so every binding is a dead control\n * with no-op setters — a silent failure an agent cannot see. Registering with\n * the Root's parts registry turns it into the existing `E_REQUIRES_CANVAS`\n * mount throw (agentic-DX P0, docs/dx/agentic-editor-dx.md finding #1).\n *\n * Guard 2 — token validation: with a `design.layer()` token (a validated\n * claim, ADR-0085 §1) the dead-binding console.warn upgrades to a throw.\n * Elements reach Root's document only when the canvas chunk seeds it, so\n * validation runs once against the FIRST non-empty element snapshot: token\n * name absent → `E_LAYER_NOT_FOUND`; present with the wrong kind →\n * `E_LAYER_WRONG_KIND`. Render-time on purpose — Root's boundary contains\n * it, dev AND prod (strict-loud-failures house rule).\n */\n\nimport { useContext, useId, useLayoutEffect, useRef } from 'react';\nimport { EditorRootInternalsContext } from '../components/editor/RootInternals.js';\nimport { EditorError } from '../errors/editorError.js';\nimport { isLayerToken, type LayerKind, type LayerToken } from '../design/design-builder.js';\nimport type { ElementStore, StoreElement } from '../core/ElementStore.js';\nimport { TextElement } from '../core/TextElement.js';\nimport { ImageElement } from '../core/ImageElement.js';\n\n/**\n * Under `<Editor.Root>`, declare that this binding hook needs a mounted\n * `Editor.Canvas` — Root's registry validation throws `E_REQUIRES_CANVAS`\n * (its existing single validation point) when none is in the composition.\n * No-op outside a Root.\n */\nexport function useBindingRequiresCanvas(hookName: string): void {\n const internals = useContext(EditorRootInternalsContext);\n const instanceId = useId();\n useLayoutEffect(() => {\n if (!internals) return undefined;\n return internals.registry.requireCanvas(instanceId, hookName);\n }, [internals, instanceId, hookName]);\n}\n\nfunction elementKind(el: StoreElement): LayerKind | null {\n if (el instanceof TextElement) return 'text';\n if (el instanceof ImageElement) return 'image';\n return null;\n}\n\nconst HOOK_BY_KIND: Record<LayerKind, string> = {\n text: 'useTextBinding / useFontBinding',\n image: 'useImageBinding',\n};\n\n/**\n * Accept a binding hook's `string | LayerToken` argument and return the bare\n * layer name. With a token under `<Editor.Root>`, mount-validate it against\n * the first non-empty element snapshot (see module doc). Bare strings keep\n * the settle-aware dead-binding console.warn instead.\n */\nexport function useValidatedBindingLayer(\n layerOrName: string | LayerToken,\n expectedKind: LayerKind,\n elementStore: ElementStore,\n): string {\n const isToken = isLayerToken(layerOrName);\n const name = isToken ? layerOrName.name : layerOrName;\n const internals = useContext(EditorRootInternalsContext);\n const validatedRef = useRef<string | null>(null);\n\n if (isToken && layerOrName.kind !== expectedKind) {\n throw new EditorError(\n 'E_LAYER_WRONG_KIND',\n `layer \"${name}\" is a ${layerOrName.kind} token — this hook binds ${expectedKind} ` +\n `layers only (use ${HOOK_BY_KIND[layerOrName.kind]}).`,\n { layerName: name, actualKind: layerOrName.kind, expectedKind, docSlug: 'embed-mode' },\n );\n }\n\n // Token + under Root: validate once, against the first snapshot that has\n // elements at all (the canvas chunk seeds Root's document asynchronously —\n // an empty store is \"not loaded yet\", never \"your token is wrong\").\n if (isToken && internals && validatedRef.current !== name) {\n const all = elementStore.getAll();\n if (all.length > 0) {\n const matches = elementStore.getAllByName(name);\n if (matches.length === 0) {\n const named = all\n .map((el) => ({ name: (el as { name?: string }).name, kind: elementKind(el) }))\n .filter((e): e is { name: string; kind: LayerKind } => Boolean(e.name) && e.kind !== null);\n throw new EditorError(\n 'E_LAYER_NOT_FOUND',\n `no layer \"${name}\" in this Root's document — the token was minted from a ` +\n `different design than the one passed to <Editor.Root design={…}>, or the ` +\n `layer was deleted. Bindable layers here: ${JSON.stringify(named.map((e) => e.name))}.`,\n { layerName: name, validNames: named.map((e) => e.name), docSlug: 'embed-mode' },\n );\n }\n if (!matches.some((el) => elementKind(el) === expectedKind)) {\n const actual = elementKind(matches[0]!) ?? 'unbindable';\n throw new EditorError(\n 'E_LAYER_WRONG_KIND',\n `layer \"${name}\" is ${actual === 'unbindable' ? 'not a bindable kind' : `an ${actual} layer`} — ` +\n `this hook binds ${expectedKind} layers only.`,\n { layerName: name, actualKind: actual, expectedKind, docSlug: 'embed-mode' },\n );\n }\n validatedRef.current = name;\n }\n }\n\n return name;\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';\nimport type { LayerToken } from '../design/design-builder.js';\nimport { useBindingRequiresCanvas, useValidatedBindingLayer } from './bindingGuards.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(layer: string | LayerToken<'text'>): TextBindingResult {\n const { elementStore } = useElementsContext();\n useBindingRequiresCanvas('useTextBinding()');\n const name = useValidatedBindingLayer(layer, 'text', elementStore);\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';\nimport type { LayerToken } from '../design/design-builder.js';\nimport { useBindingRequiresCanvas, useValidatedBindingLayer } from './bindingGuards.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(layer: string | LayerToken<'image'>, options?: ImageBindingOptions): ImageBindingResult {\n useBindingRequiresCanvas('useImageBinding()');\n const fit = options?.fit ?? 'cover';\n const { elementStore, setElements } = useElementsContext();\n const name = useValidatedBindingLayer(layer, 'image', elementStore);\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 { isColorToken, type ColorToken } from '../design/design-builder.js';\nimport { useBindingRequiresCanvas } from './bindingGuards.js';\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(original: string | ColorToken): ColorBindingResult {\n // `design.color('role')` tokens carry the role's value — one source of\n // truth for the chip and the painted elements (agentic-DX finding #2).\n const originalColor = isColorToken(original) ? original.value : original;\n const { elementStore } = useElementsContext();\n const { executeElementUpdate } = useCommandContext();\n\n // Under <Editor.Root>, a canvas-free composition makes every color binding\n // a silent dead control — fail loud instead (E_REQUIRES_CANVAS).\n useBindingRequiresCanvas('useColorBinding()');\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';\nimport type { LayerToken } from '../design/design-builder.js';\nimport { useBindingRequiresCanvas, useValidatedBindingLayer } from './bindingGuards.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(layer: string | LayerToken<'text'>): FontBindingResult {\n const { elementStore } = useElementsContext();\n useBindingRequiresCanvas('useFontBinding()');\n const name = useValidatedBindingLayer(layer, 'text', elementStore);\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","e","layerKindOfConfig","n","found","elements","EditorError","a","label","artboards","base","baseName","onBase","tag","cloned","i","_a","t","l","choiceLabelsOf","attr","c","seedSelectionOf","product","combinations","combination","selection","key","value","CommerceStateStore","toOptionAttributes","toCombinations","choice","labels","quantity","getMissingSelections","validateProductSelection","best","findBestCombination","stringAttrs","computeDisabledChoices","useSelectedElement","selectedElement","useEditor","DEAD_BINDING_GRACE_MS","HOOK_NAME","SETTER_NAME","TARGET_KIND","warned","kindOf","TextElement","ImageElement","deadBindingWarning","kind","store","dead","target","sameName","kinds","other","hint","named","available","useDeadBindingWarning","isConnected","useEffect","process","timer","useBindingRequiresCanvas","hookName","internals","useContext","EditorRootInternalsContext","instanceId","useId","useLayoutEffect","elementKind","HOOK_BY_KIND","useValidatedBindingLayer","layerOrName","expectedKind","elementStore","isToken","isLayerToken","validatedRef","useRef","all","matches","actual","NOOP","EMPTY","useTextBinding","layer","useElementsContext","executeElementUpdate","useCommandContext","textElements","useMemo","setText","useCallback","newText","coverCrop","origWidth","origHeight","imageAspectRatio","placeholderAR","frameHeight","frameWidth","cropWidth","cropHeight","useImageBinding","options","fit","setElements","imageElements","origDimsRef","td","imageElementsRef","executeRef","setElementsRef","setImageUrl","url","currentElements","exec","orig","origW","origH","loadedElement","imgAR","crop","w","h","scale","normalizeHex","color","hex","slotMatches","match","elementMatchesColor","_b","_c","applyColorToClone","newColor","src","dst","useColorBinding","original","originalColor","isColorToken","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,YAAY,CAACC,OACX,KAAK,UAAU,IAAIA,CAAQ,GACpB,MAAM,KAAK,UAAU,OAAOA,CAAQ,IAjB3C,KAAK,QAAQD;AACb,UAAME,wBAAgB,IAAA;AACtB,eAAWL,KAAMG,EAAK,UAAU;AAC9B,YAAMG,IAAOL,EAAOD,CAAE,GAChBO,IAAOR,EAAOC,CAAE;AACtB,MAAIM,KAAQ,OAAOC,KAAS,YAAUF,EAAU,IAAIC,GAAMC,CAAI;AAAA,IAChE;AACA,SAAK,iBAAiBF;AAAA,EACxB;AAAA;AAAA,EAaA,SAASG,GAAyB;AAChC,SAAK,QAAQA,GACb,KAAK,KAAA;AAAA,EACP;AAAA;AAAA,EAGA,WAAWF,GAAkC;AAC3C,WAAO,KAAK,eAAe,IAAIA,CAAI;A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,OAAOA,KAAU,iBAAiB,CAAA;AAChD,QAAMC,IAAOD,EAAkCV,EAAmB;AAClE,MAAI,CAAC,MAAM,QAAQW,CAAG,UAAU,CAAA;AAEhC,QAAMC,IAA0B,CAAA;AAChC,aAAWC,KAASF,GAAK;AACvB,QAAI,CAACE,KAAS,OAAOA,KAAU,SAAU;AACzC,UAAMC,IAAY,UAAUD,IAAQA,IAAQ,EAAE,GAAGA,GAAO,MAAM,OAAA,GACxDE,IAASd,GAAoB,UAAUa,CAAS;AACtD,IAAIC,EAAO,WAASH,EAAO,KAAKG,EAAO,IAAqB;AAAA,EAC9D;AACA,SAAOH;AACT;AAWO,SAASI,GACdN,GACAE,GACgD;AAChD,SAAO,EAAE,GAAGF,GAAO,CAACV,EAAmB,GAAGY,EAAA;AAC5C;"}
1
+ {"version":3,"file":"template-fields-Dltc4Ztb.js","sources":["../src/components/editor/designStateStore.ts","../src/components/editor/commerceStore.ts","../src/hooks/useSelectedElement.ts","../src/hooks/useDeadBindingWarning.ts","../src/hooks/bindingGuards.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 /** Artboard names in author order — the first is the base (ADR-0101). */\n artboardNames(): string[] {\n return this.state.artboards.map((a) => a.name);\n }\n\n /**\n * Split a placement out of the base (ADR-0101): clone the FIRST artboard\n * and every element on it into a new artboard named `label`. Elements get\n * fresh ids and the new artboard's membership tag. No-op when `label`\n * already has an artboard. Used when NO canvas is mounted — with one, the\n * editor document does the same through the CanvasBridge and the result\n * lands here via `setState`.\n */\n splitArtboard(label: string): void {\n const { artboards, elements } = this.state;\n const base = artboards[0];\n if (!base || artboards.some((a) => a.name === label)) return;\n const baseName = base.name;\n const onBase = (el: AnyElementConfig) => {\n const tag = (el as { artboard?: string }).artboard;\n return tag === undefined || tag === baseName;\n };\n const cloned = elements\n .filter(onBase)\n .map((el, i) => ({\n ...el,\n id: `${String((el as { id?: string }).id ?? 'el')}__${label}__${i}`,\n artboard: label,\n })) as AnyElementConfig[];\n this.setState({\n ...this.state,\n artboards: [...artboards, { ...base, name: label }],\n elements: [...elements, ...cloned],\n });\n }\n\n /**\n * Re-link a placement (ADR-0101): drop the artboard named `label` and every\n * element tagged to it, so the placement inherits the base again. No-op for\n * an unknown label. Refuses the base itself — that is what the others\n * inherit (`E_LINK_BASE`).\n */\n removeArtboard(label: string): void {\n const { artboards, elements } = this.state;\n if (artboards[0]?.name === label) {\n throw new EditorError(\n 'E_LINK_BASE',\n `\"${label}\" is the base artboard — every linked placement inherits it, so it ` +\n `cannot be re-linked. Link a split placement instead, or call linkAll(). ` +\n `Artboards: ${JSON.stringify(this.artboardNames())}.`,\n { artboardName: label, validNames: this.artboardNames().slice(1), docSlug: 'embed-mode' },\n );\n }\n if (!artboards.some((a) => a.name === label)) return;\n this.setState({\n ...this.state,\n artboards: artboards.filter((a) => a.name !== label),\n elements: elements.filter((el) => (el as { artboard?: string }).artboard !== label),\n activeArtboard: this.state.activeArtboard === label ? artboards[0]!.name : this.state.activeArtboard,\n });\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 /**\n * The variant (gvid) to RENDER with — deliberately looser than\n * {@link resolvedVariantId}. That one is Buy's currency: it returns\n * `undefined` while the selection is incomplete so completeness can gate.\n * But the PRODUCT PHOTO must follow the shopper's picks immediately —\n * \"choose the Oak frame\" should render Oak even while an unrelated axis\n * (size, pocket) is still unselected. This resolves the best combination\n * matching the CURRENT (possibly partial) selection, falling back to the\n * product's initial variant. (Before this split, switching a color swatch\n * with any axis unselected rendered nothing — the mockup silently stayed\n * on the old color.)\n */\n renderVariantId(): string | undefined {\n if (Object.keys(this.attrs).length === 0 || this.combos.length === 0) {\n return this.product.variantId;\n }\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","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 * Shared fail-loud guards for the chrome-binding hooks (`useTextBinding`,\n * `useImageBinding`, `useFontBinding`, `useColorBinding`) when they run under\n * an `<Editor.Root>` (ADR-0085 compositions). Outside a Root — legacy chrome\n * inside a raw `EditorProvider`, `<RealtimeCanvas>` overlay children — both\n * guards are inert and the hooks keep their historical warn-only behavior.\n *\n * Guard 1 — canvas requirement: the bindings mutate the editor document via\n * the command path, and only a mounted `Editor.Canvas` syncs that document to\n * the design store / live renders. In a canvas-free composition the document\n * is EMPTY (Root seeds only the artboard), so every binding is a dead control\n * with no-op setters — a silent failure an agent cannot see. Registering with\n * the Root's parts registry turns it into the existing `E_REQUIRES_CANVAS`\n * mount throw (agentic-DX P0, docs/dx/agentic-editor-dx.md finding #1).\n *\n * Guard 2 — token validation: with a `design.layer()` token (a validated\n * claim, ADR-0085 §1) the dead-binding console.warn upgrades to a throw.\n * Elements reach Root's document only when the canvas chunk seeds it, so\n * validation runs once against the FIRST non-empty element snapshot: token\n * name absent → `E_LAYER_NOT_FOUND`; present with the wrong kind →\n * `E_LAYER_WRONG_KIND`. Render-time on purpose — Root's boundary contains\n * it, dev AND prod (strict-loud-failures house rule).\n */\n\nimport { useContext, useId, useLayoutEffect, useRef } from 'react';\nimport { EditorRootInternalsContext } from '../components/editor/RootInternals.js';\nimport { EditorError } from '../errors/editorError.js';\nimport { isLayerToken, type LayerKind, type LayerToken } from '../design/design-builder.js';\nimport type { ElementStore, StoreElement } from '../core/ElementStore.js';\nimport { TextElement } from '../core/TextElement.js';\nimport { ImageElement } from '../core/ImageElement.js';\n\n/**\n * Under `<Editor.Root>`, declare that this binding hook needs a mounted\n * `Editor.Canvas` — Root's registry validation throws `E_REQUIRES_CANVAS`\n * (its existing single validation point) when none is in the composition.\n * No-op outside a Root.\n */\nexport function useBindingRequiresCanvas(hookName: string): void {\n const internals = useContext(EditorRootInternalsContext);\n const instanceId = useId();\n useLayoutEffect(() => {\n if (!internals) return undefined;\n return internals.registry.requireCanvas(instanceId, hookName);\n }, [internals, instanceId, hookName]);\n}\n\nfunction elementKind(el: StoreElement): LayerKind | null {\n if (el instanceof TextElement) return 'text';\n if (el instanceof ImageElement) return 'image';\n return null;\n}\n\nconst HOOK_BY_KIND: Record<LayerKind, string> = {\n text: 'useTextBinding / useFontBinding',\n image: 'useImageBinding',\n};\n\n/**\n * Accept a binding hook's `string | LayerToken` argument and return the bare\n * layer name. With a token under `<Editor.Root>`, mount-validate it against\n * the first non-empty element snapshot (see module doc). Bare strings keep\n * the settle-aware dead-binding console.warn instead.\n */\nexport function useValidatedBindingLayer(\n layerOrName: string | LayerToken,\n expectedKind: LayerKind,\n elementStore: ElementStore,\n): string {\n const isToken = isLayerToken(layerOrName);\n const name = isToken ? layerOrName.name : layerOrName;\n const internals = useContext(EditorRootInternalsContext);\n const validatedRef = useRef<string | null>(null);\n\n if (isToken && layerOrName.kind !== expectedKind) {\n throw new EditorError(\n 'E_LAYER_WRONG_KIND',\n `layer \"${name}\" is a ${layerOrName.kind} token — this hook binds ${expectedKind} ` +\n `layers only (use ${HOOK_BY_KIND[layerOrName.kind]}).`,\n { layerName: name, actualKind: layerOrName.kind, expectedKind, docSlug: 'embed-mode' },\n );\n }\n\n // Token + under Root: validate once, against the first snapshot that has\n // elements at all (the canvas chunk seeds Root's document asynchronously —\n // an empty store is \"not loaded yet\", never \"your token is wrong\").\n if (isToken && internals && validatedRef.current !== name) {\n const all = elementStore.getAll();\n if (all.length > 0) {\n const matches = elementStore.getAllByName(name);\n if (matches.length === 0) {\n const named = all\n .map((el) => ({ name: (el as { name?: string }).name, kind: elementKind(el) }))\n .filter((e): e is { name: string; kind: LayerKind } => Boolean(e.name) && e.kind !== null);\n throw new EditorError(\n 'E_LAYER_NOT_FOUND',\n `no layer \"${name}\" in this Root's document — the token was minted from a ` +\n `different design than the one passed to <Editor.Root design={…}>, or the ` +\n `layer was deleted. Bindable layers here: ${JSON.stringify(named.map((e) => e.name))}.`,\n { layerName: name, validNames: named.map((e) => e.name), docSlug: 'embed-mode' },\n );\n }\n if (!matches.some((el) => elementKind(el) === expectedKind)) {\n const actual = elementKind(matches[0]!) ?? 'unbindable';\n throw new EditorError(\n 'E_LAYER_WRONG_KIND',\n `layer \"${name}\" is ${actual === 'unbindable' ? 'not a bindable kind' : `an ${actual} layer`} — ` +\n `this hook binds ${expectedKind} layers only.`,\n { layerName: name, actualKind: actual, expectedKind, docSlug: 'embed-mode' },\n );\n }\n validatedRef.current = name;\n }\n }\n\n return name;\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';\nimport type { LayerToken } from '../design/design-builder.js';\nimport { useBindingRequiresCanvas, useValidatedBindingLayer } from './bindingGuards.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(layer: string | LayerToken<'text'>): TextBindingResult {\n const { elementStore } = useElementsContext();\n useBindingRequiresCanvas('useTextBinding()');\n const name = useValidatedBindingLayer(layer, 'text', elementStore);\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';\nimport type { LayerToken } from '../design/design-builder.js';\nimport { useBindingRequiresCanvas, useValidatedBindingLayer } from './bindingGuards.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(layer: string | LayerToken<'image'>, options?: ImageBindingOptions): ImageBindingResult {\n useBindingRequiresCanvas('useImageBinding()');\n const fit = options?.fit ?? 'cover';\n const { elementStore, setElements } = useElementsContext();\n const name = useValidatedBindingLayer(layer, 'image', elementStore);\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 { isColorToken, type ColorToken } from '../design/design-builder.js';\nimport { useBindingRequiresCanvas } from './bindingGuards.js';\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(original: string | ColorToken): ColorBindingResult {\n // `design.color('role')` tokens carry the role's value — one source of\n // truth for the chip and the painted elements (agentic-DX finding #2).\n const originalColor = isColorToken(original) ? original.value : original;\n const { elementStore } = useElementsContext();\n const { executeElementUpdate } = useCommandContext();\n\n // Under <Editor.Root>, a canvas-free composition makes every color binding\n // a silent dead control — fail loud instead (E_REQUIRES_CANVAS).\n useBindingRequiresCanvas('useColorBinding()');\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';\nimport type { LayerToken } from '../design/design-builder.js';\nimport { useBindingRequiresCanvas, useValidatedBindingLayer } from './bindingGuards.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(layer: string | LayerToken<'text'>): FontBindingResult {\n const { elementStore } = useElementsContext();\n useBindingRequiresCanvas('useFontBinding()');\n const name = useValidatedBindingLayer(layer, 'text', elementStore);\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","e","layerKindOfConfig","n","found","elements","EditorError","a","label","artboards","base","baseName","onBase","tag","cloned","i","_a","t","l","choiceLabelsOf","attr","c","seedSelectionOf","product","combinations","combination","selection","key","value","CommerceStateStore","toOptionAttributes","toCombinations","choice","labels","quantity","getMissingSelections","validateProductSelection","best","findBestCombination","stringAttrs","computeDisabledChoices","useSelectedElement","selectedElement","useEditor","DEAD_BINDING_GRACE_MS","HOOK_NAME","SETTER_NAME","TARGET_KIND","warned","kindOf","TextElement","ImageElement","deadBindingWarning","kind","store","dead","target","sameName","kinds","other","hint","named","available","useDeadBindingWarning","isConnected","useEffect","process","timer","useBindingRequiresCanvas","hookName","internals","useContext","EditorRootInternalsContext","instanceId","useId","useLayoutEffect","elementKind","HOOK_BY_KIND","useValidatedBindingLayer","layerOrName","expectedKind","elementStore","isToken","isLayerToken","validatedRef","useRef","all","matches","actual","NOOP","EMPTY","useTextBinding","layer","useElementsContext","executeElementUpdate","useCommandContext","textElements","useMemo","setText","useCallback","newText","coverCrop","origWidth","origHeight","imageAspectRatio","placeholderAR","frameHeight","frameWidth","cropWidth","cropHeight","useImageBinding","options","fit","setElements","imageElements","origDimsRef","td","imageElementsRef","executeRef","setElementsRef","setImageUrl","url","currentElements","exec","orig","origW","origH","loadedElement","imgAR","crop","w","h","scale","normalizeHex","color","hex","slotMatches","match","elementMatchesColor","_b","_c","applyColorToClone","newColor","src","dst","useColorBinding","original","originalColor","isColorToken","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,YAAY,CAACC,OACX,KAAK,UAAU,IAAIA,CAAQ,GACpB,MAAM,KAAK,UAAU,OAAOA,CAAQ,IAjB3C,KAAK,QAAQD;AACb,UAAME,wBAAgB,IAAA;AACtB,eAAWL,KAAMG,E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AM,GAAGA,EAAU,UAAU,GAAGA,EAAU,YAAY,CAAC,CAAC;AAAA,IACrF,SAASI,GAAQL,EAAS,EAAE,OAAOE,EAAE,GAAU,OAAOA,EAAE,EAAO,CAAG,CAAC,EAAE,IAAI,CAAC;AAAA,IAC1E,UAAUA,EAAE,EAAS,IAAI,CAAC,EAAE,SAAA;AAAA,IAC5B,OAAOA,EAAE,EAAS,SAAA;AAAA,EAAS,CAC5B;AACH,CAAC;AAUM,SAASI,GAAmBC,GAAiC;AAClE,MAAI,CAACA,KAAS,OAAOA,KAAU,iBAAiB,CAAA;AAChD,QAAMC,IAAOD,EAAkCV,EAAmB;AAClE,MAAI,CAAC,MAAM,QAAQW,CAAG,UAAU,CAAA;AAEhC,QAAMC,IAA0B,CAAA;AAChC,aAAWC,KAASF,GAAK;AACvB,QAAI,CAACE,KAAS,OAAOA,KAAU,SAAU;AACzC,UAAMC,IAAY,UAAUD,IAAQA,IAAQ,EAAE,GAAGA,GAAO,MAAM,OAAA,GACxDE,IAASd,GAAoB,UAAUa,CAAS;AACtD,IAAIC,EAAO,WAASH,EAAO,KAAKG,EAAO,IAAqB;AAAA,EAC9D;AACA,SAAOH;AACT;AAWO,SAASI,GACdN,GACAE,GACgD;AAChD,SAAO,EAAE,GAAGF,GAAO,CAACV,EAAmB,GAAGY,EAAA;AAC5C;"}
@@ -685,7 +685,8 @@ export type ClipShape = 'rectangle' | 'circle' | {
685
685
  d: string;
686
686
  x: number;
687
687
  y: number;
688
- rotation?: 0 | 90 | 180 | 270;
688
+ /** degrees clockwise, any multiple of 45 */
689
+ rotation?: number;
689
690
  baseWidth?: number;
690
691
  baseHeight?: number;
691
692
  }>;