@snowcone-app/canvas 0.21.2 → 0.21.3
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.
- package/STYLING_CONTRACT.md +14 -0
- package/dist/{CanvasRenderer-B0szG0Us.js → CanvasRenderer-6_HhR4-q.js} +170 -189
- package/dist/CanvasRenderer-6_HhR4-q.js.map +1 -0
- package/dist/{ContextualToolbars-BYnovWnN.js → ContextualToolbars-BDEt9ND0.js} +1619 -1846
- package/dist/ContextualToolbars-BDEt9ND0.js.map +1 -0
- package/dist/{EditorCanvasImpl-BmLHjXe7.js → EditorCanvasImpl-M7rw1c1k.js} +5 -5
- package/dist/{EditorCanvasImpl-BmLHjXe7.js.map → EditorCanvasImpl-M7rw1c1k.js.map} +1 -1
- package/dist/ImagePanel-BwqFDKvW.js +951 -0
- package/dist/ImagePanel-BwqFDKvW.js.map +1 -0
- package/dist/{SnowconeCanvas-Bj2773ym.js → SnowconeCanvas-Cx7nXlBI.js} +19 -18
- package/dist/{SnowconeCanvas-Bj2773ym.js.map → SnowconeCanvas-Cx7nXlBI.js.map} +1 -1
- package/dist/{UnifiedFontService-C8gaspRD.js → UnifiedFontService-CC3CSmH5.js} +1042 -984
- package/dist/UnifiedFontService-CC3CSmH5.js.map +1 -0
- package/dist/advanced.mjs +97 -96
- package/dist/advanced.mjs.map +1 -1
- package/dist/components/editor/LazyImageBrowser.d.ts +7 -0
- package/dist/components/editor/commerceStore.d.ts +13 -0
- package/dist/custom-icons-BW6hqmkL.js +236 -0
- package/dist/custom-icons-BW6hqmkL.js.map +1 -0
- package/dist/{embed-pM7ZkFuz.js → embed-QBZkgWDr.js} +287 -272
- package/dist/{embed-pM7ZkFuz.js.map → embed-QBZkgWDr.js.map} +1 -1
- package/dist/embed.mjs +3 -3
- package/dist/guards-8rkFAMBs.js +24 -0
- package/dist/guards-8rkFAMBs.js.map +1 -0
- package/dist/index.mjs +5 -5
- package/dist/internals.mjs +1 -1
- package/dist/style.css +1 -1
- package/dist/{template-fields-BsnHMf1i.js → template-fields-C2pSfMBh.js} +57 -39
- package/dist/template-fields-C2pSfMBh.js.map +1 -0
- package/dist/validation-C9Fe9ahK.js +8367 -0
- package/dist/validation-C9Fe9ahK.js.map +1 -0
- package/example/package.json +1 -1
- package/package.json +1 -1
- package/dist/CanvasRenderer-B0szG0Us.js.map +0 -1
- package/dist/ContextualToolbars-BYnovWnN.js.map +0 -1
- package/dist/UnifiedFontService-C8gaspRD.js.map +0 -1
- package/dist/template-fields-BsnHMf1i.js.map +0 -1
- package/dist/validation-DdVeWnlo.js +0 -9308
- package/dist/validation-DdVeWnlo.js.map +0 -1
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { g as
|
|
1
|
+
import { g as _, u as G, c as D, b as I } from "./editorErrors-B2mb1sVN.js";
|
|
2
2
|
import { l as H } from "./design-builder-CT4DHIPe.js";
|
|
3
|
-
import { toOptionAttributes as Z, toCombinations as tt, getMissingSelections as et, validateProductSelection as nt, findBestCombination as
|
|
4
|
-
import { useCallback as v, useEffect as ot, useMemo as
|
|
5
|
-
import { c as rt, y as W, T as
|
|
6
|
-
import { U as at } from "./UnifiedFontService-
|
|
3
|
+
import { toOptionAttributes as Z, toCombinations as tt, getMissingSelections as et, validateProductSelection as nt, findBestCombination as w, computeDisabledChoices as st } from "@snowcone-app/sdk";
|
|
4
|
+
import { useCallback as v, useEffect as ot, useMemo as A, useRef as S, useState as L } from "react";
|
|
5
|
+
import { c as rt, y as W, T as k, I as q, z as it } from "./FontAnalyzer-CwIpgTGd.js";
|
|
6
|
+
import { U as at } from "./UnifiedFontService-CC3CSmH5.js";
|
|
7
7
|
import { a as ct, o as N, b as c, n as lt, l as y, u as Y, c as ft } from "./CanvasStateV1-DmZ1Qvvn.js";
|
|
8
|
-
function
|
|
8
|
+
function U(s) {
|
|
9
9
|
return s.text;
|
|
10
10
|
}
|
|
11
11
|
function O(s) {
|
|
@@ -16,7 +16,7 @@ class Ut {
|
|
|
16
16
|
this.listeners = /* @__PURE__ */ new Set(), this.getState = () => this.state, this.subscribe = (e) => (this.listeners.add(e), () => this.listeners.delete(e)), this.state = t;
|
|
17
17
|
const n = /* @__PURE__ */ new Map();
|
|
18
18
|
for (const e of t.elements) {
|
|
19
|
-
const r = O(e), o =
|
|
19
|
+
const r = O(e), o = U(e);
|
|
20
20
|
r && typeof o == "string" && n.set(r, o);
|
|
21
21
|
}
|
|
22
22
|
this.seedTextByName = n;
|
|
@@ -32,7 +32,7 @@ class Ut {
|
|
|
32
32
|
/** Current text of a named text layer, or undefined when absent. */
|
|
33
33
|
textOf(t) {
|
|
34
34
|
const n = this.state.elements.find((e) => O(e) === t);
|
|
35
|
-
return n ?
|
|
35
|
+
return n ? U(n) : void 0;
|
|
36
36
|
}
|
|
37
37
|
/** Kind of the named layer in the CURRENT state ('text' | 'image' | null
|
|
38
38
|
* for unbindable), or undefined when no layer has the name. */
|
|
@@ -53,7 +53,7 @@ class Ut {
|
|
|
53
53
|
let e = !1;
|
|
54
54
|
const r = this.state.elements.map((o) => O(o) !== t ? o : (e = !0, { ...o, text: n }));
|
|
55
55
|
if (!e)
|
|
56
|
-
throw new
|
|
56
|
+
throw new _(
|
|
57
57
|
"E_LAYER_NOT_FOUND",
|
|
58
58
|
`no layer "${t}" in the current design state. Bindable layers: ${JSON.stringify(this.bindableLayerNames())}.`,
|
|
59
59
|
{ layerName: t, validNames: this.bindableLayerNames(), docSlug: "embed-mode" }
|
|
@@ -68,7 +68,7 @@ class Ut {
|
|
|
68
68
|
const n = t.transformType;
|
|
69
69
|
if (n === "image") return !!t.imageUrl;
|
|
70
70
|
if (n === "shape" || n === "group" || n === "path") return !0;
|
|
71
|
-
const e =
|
|
71
|
+
const e = U(t);
|
|
72
72
|
return typeof e == "string" && e.trim().length > 0;
|
|
73
73
|
});
|
|
74
74
|
}
|
|
@@ -109,14 +109,14 @@ class Ft {
|
|
|
109
109
|
select(t, n) {
|
|
110
110
|
const e = this.attrs[t];
|
|
111
111
|
if (!e)
|
|
112
|
-
throw new
|
|
112
|
+
throw new _(
|
|
113
113
|
"E_UNKNOWN_OPTION",
|
|
114
114
|
`product ${this.product.productId} has no option "${t}". Valid option keys: ${JSON.stringify(Object.keys(this.attrs))}.`,
|
|
115
115
|
{ key: t, validKeys: Object.keys(this.attrs), docSlug: "embed-mode" }
|
|
116
116
|
);
|
|
117
117
|
const r = K(e);
|
|
118
118
|
if (r.length > 0 && !r.includes(n))
|
|
119
|
-
throw new
|
|
119
|
+
throw new _(
|
|
120
120
|
"E_UNKNOWN_OPTION",
|
|
121
121
|
`"${n}" is not a choice of option "${t}" on product ${this.product.productId}. Valid choices: ${JSON.stringify(r)}.`,
|
|
122
122
|
{ key: t, choice: n, validChoices: r, docSlug: "embed-mode" }
|
|
@@ -143,13 +143,31 @@ class Ft {
|
|
|
143
143
|
if (Object.keys(this.attrs).length === 0 || this.combos.length === 0)
|
|
144
144
|
return this.product.variantId;
|
|
145
145
|
if (!this.selectionValid()) return;
|
|
146
|
-
const t =
|
|
146
|
+
const t = w(this.selection, this.combos, this.attrs);
|
|
147
|
+
return (typeof (t == null ? void 0 : t.variantId) == "string" && t.variantId !== "" ? t.variantId : void 0) ?? this.product.variantId;
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* The variant (gvid) to RENDER with — deliberately looser than
|
|
151
|
+
* {@link resolvedVariantId}. That one is Buy's currency: it returns
|
|
152
|
+
* `undefined` while the selection is incomplete so completeness can gate.
|
|
153
|
+
* But the PRODUCT PHOTO must follow the shopper's picks immediately —
|
|
154
|
+
* "choose the Oak frame" should render Oak even while an unrelated axis
|
|
155
|
+
* (size, pocket) is still unselected. This resolves the best combination
|
|
156
|
+
* matching the CURRENT (possibly partial) selection, falling back to the
|
|
157
|
+
* product's initial variant. (Before this split, switching a color swatch
|
|
158
|
+
* with any axis unselected rendered nothing — the mockup silently stayed
|
|
159
|
+
* on the old color.)
|
|
160
|
+
*/
|
|
161
|
+
renderVariantId() {
|
|
162
|
+
if (Object.keys(this.attrs).length === 0 || this.combos.length === 0)
|
|
163
|
+
return this.product.variantId;
|
|
164
|
+
const t = w(this.selection, this.combos, this.attrs);
|
|
147
165
|
return (typeof (t == null ? void 0 : t.variantId) == "string" && t.variantId !== "" ? t.variantId : void 0) ?? this.product.variantId;
|
|
148
166
|
}
|
|
149
167
|
/** Price of the resolved combination, when the catalog carries one. */
|
|
150
168
|
resolvedPrice() {
|
|
151
169
|
if (!this.selectionValid()) return;
|
|
152
|
-
const t =
|
|
170
|
+
const t = w(this.selection, this.combos, this.attrs);
|
|
153
171
|
return typeof (t == null ? void 0 : t.price) == "number" ? t.price : void 0;
|
|
154
172
|
}
|
|
155
173
|
/** Choices invalid given the rest of the current selection — for hosts to
|
|
@@ -210,7 +228,7 @@ function _t() {
|
|
|
210
228
|
executeCommandBatch: l
|
|
211
229
|
};
|
|
212
230
|
}
|
|
213
|
-
function
|
|
231
|
+
function kt() {
|
|
214
232
|
const { selectedElement: s } = G();
|
|
215
233
|
return s ?? null;
|
|
216
234
|
}
|
|
@@ -226,9 +244,9 @@ const mt = 3e3, z = {
|
|
|
226
244
|
text: "text",
|
|
227
245
|
image: "image",
|
|
228
246
|
font: "text"
|
|
229
|
-
},
|
|
247
|
+
}, F = /* @__PURE__ */ new Set();
|
|
230
248
|
function X(s) {
|
|
231
|
-
return s instanceof
|
|
249
|
+
return s instanceof k ? "text" : s instanceof q ? "image" : "other";
|
|
232
250
|
}
|
|
233
251
|
function pt(s, t, n) {
|
|
234
252
|
const e = `[${z[s]}]`, r = `the binding is dead (isConnected: false, ${dt[s]} is a no-op)`, o = ht[s], i = n.getAllByName(t);
|
|
@@ -244,17 +262,17 @@ function M(s, t, n, e) {
|
|
|
244
262
|
var i;
|
|
245
263
|
if (e || typeof W > "u" || ((i = W.env) == null ? void 0 : i.NODE_ENV) === "production") return;
|
|
246
264
|
const r = `${s}:${t}`;
|
|
247
|
-
if (
|
|
265
|
+
if (F.has(r)) return;
|
|
248
266
|
const o = setTimeout(() => {
|
|
249
|
-
|
|
267
|
+
F.has(r) || (F.add(r), console.warn(pt(s, t, n)));
|
|
250
268
|
}, mt);
|
|
251
269
|
return () => clearTimeout(o);
|
|
252
270
|
}, [s, t, n, e]);
|
|
253
271
|
}
|
|
254
272
|
const gt = () => {
|
|
255
273
|
}, yt = [];
|
|
256
|
-
function
|
|
257
|
-
const { elementStore: t } = D(), { executeElementUpdate: n } =
|
|
274
|
+
function Mt(s) {
|
|
275
|
+
const { elementStore: t } = D(), { executeElementUpdate: n } = I(), e = A(() => t.getAllByName(s).filter((i) => i instanceof k), [t, s]), r = v(
|
|
258
276
|
(o) => {
|
|
259
277
|
for (const i of e) {
|
|
260
278
|
const a = i.clone();
|
|
@@ -298,7 +316,7 @@ function vt(s, t, n) {
|
|
|
298
316
|
}
|
|
299
317
|
}
|
|
300
318
|
function Pt(s, t) {
|
|
301
|
-
const n = (t == null ? void 0 : t.fit) ?? "cover", { elementStore: e, setElements: r } = D(), { executeElementUpdate: o } =
|
|
319
|
+
const n = (t == null ? void 0 : t.fit) ?? "cover", { elementStore: e, setElements: r } = D(), { executeElementUpdate: o } = I(), i = A(() => e.getAllByName(s).filter((d) => d instanceof q), [e, s]), a = S(/* @__PURE__ */ new Map());
|
|
302
320
|
for (const m of i)
|
|
303
321
|
if (!a.current.has(m.id)) {
|
|
304
322
|
const d = m.transformData;
|
|
@@ -317,14 +335,14 @@ function Pt(s, t) {
|
|
|
317
335
|
(m) => {
|
|
318
336
|
const d = u.current, $ = l.current;
|
|
319
337
|
for (const C of d) {
|
|
320
|
-
const
|
|
321
|
-
if (!
|
|
322
|
-
const { width:
|
|
338
|
+
const P = a.current.get(C.id);
|
|
339
|
+
if (!P) continue;
|
|
340
|
+
const { width: R, height: j } = P, p = C.clone();
|
|
323
341
|
p.imageLoaded = !1, p.imageElement = null, p.isCropping = !1, p.imageUrl = m, n === "cover" ? (p.preserveDimensions = !0, p.onLoadCallback = (f) => {
|
|
324
|
-
const E = f.imageAspectRatio || 1, g = vt(
|
|
342
|
+
const E = f.imageAspectRatio || 1, g = vt(R, j, E);
|
|
325
343
|
f.transformData.width = g.width, f.transformData.height = g.height, f.transformData.cropX = g.cropX, f.transformData.cropY = g.cropY, f.transformData.cropWidth = g.cropWidth, f.transformData.cropHeight = g.cropHeight, $(C, f);
|
|
326
344
|
}) : (p.preserveDimensions = !1, p.onLoadCallback = (f) => {
|
|
327
|
-
const E = f.transformData.width, g = f.transformData.height, B = Math.min(
|
|
345
|
+
const E = f.transformData.width, g = f.transformData.height, B = Math.min(R / E, j / g, 1);
|
|
328
346
|
B < 1 && (f.transformData.width = E * B, f.transformData.height = g * B), f.transformData.cropX = 0, f.transformData.cropY = 0, f.transformData.cropWidth = 1, f.transformData.cropHeight = 1, $(C, f);
|
|
329
347
|
}), p.loadImage(m);
|
|
330
348
|
}
|
|
@@ -360,9 +378,9 @@ function Nt(s, t, n) {
|
|
|
360
378
|
return x(r.color, t) && (typeof o.setColor == "function" ? o.setColor(n) : o.color = n), x((i = r.transformData) == null ? void 0 : i.fillColor, t) && (o.transformData = { ...o.transformData, fillColor: n }), x((a = r.transformData) == null ? void 0 : a.strokeColor, t) && (o.transformData = { ...o.transformData, strokeColor: n }), ((u = r.stroke) == null ? void 0 : u.enabled) === !0 && x(r.stroke.color, t) && (o.stroke = { ...o.stroke, color: n }), e;
|
|
361
379
|
}
|
|
362
380
|
function Rt(s) {
|
|
363
|
-
const { elementStore: t } = D(), { executeElementUpdate: n } =
|
|
381
|
+
const { elementStore: t } = D(), { executeElementUpdate: n } = I(), [e, r] = L(() => T(s)), [o, i] = L(s);
|
|
364
382
|
s !== o && (i(s), r(T(s)));
|
|
365
|
-
const a =
|
|
383
|
+
const a = A(
|
|
366
384
|
() => t.getAll().filter((l) => J(l, e)),
|
|
367
385
|
[t, e]
|
|
368
386
|
), u = v(
|
|
@@ -382,8 +400,8 @@ function Rt(s) {
|
|
|
382
400
|
}
|
|
383
401
|
const Ot = () => {
|
|
384
402
|
}, Dt = [];
|
|
385
|
-
function
|
|
386
|
-
const { elementStore: t } = D(), { executeElementUpdate: n } =
|
|
403
|
+
function jt(s) {
|
|
404
|
+
const { elementStore: t } = D(), { executeElementUpdate: n } = I(), e = A(() => t.getAllByName(s).filter((i) => i instanceof k), [t, s]), r = v(
|
|
387
405
|
(o) => {
|
|
388
406
|
at.loadGoogleFontByName(o);
|
|
389
407
|
for (const i of e) {
|
|
@@ -403,7 +421,7 @@ function Ht(s) {
|
|
|
403
421
|
isConnected: !0
|
|
404
422
|
};
|
|
405
423
|
}
|
|
406
|
-
function
|
|
424
|
+
function Ht(s) {
|
|
407
425
|
const { elementStore: t } = D();
|
|
408
426
|
return s ? t.getByName(s) ?? null : null;
|
|
409
427
|
}
|
|
@@ -443,7 +461,7 @@ const Q = "personalization", $t = ct("type", [
|
|
|
443
461
|
group: c().optional()
|
|
444
462
|
})
|
|
445
463
|
]);
|
|
446
|
-
function
|
|
464
|
+
function Lt(s) {
|
|
447
465
|
if (!s || typeof s != "object") return [];
|
|
448
466
|
const t = s[Q];
|
|
449
467
|
if (!Array.isArray(t)) return [];
|
|
@@ -463,14 +481,14 @@ export {
|
|
|
463
481
|
Ut as D,
|
|
464
482
|
Q as T,
|
|
465
483
|
_t as a,
|
|
466
|
-
|
|
467
|
-
|
|
484
|
+
Ht as b,
|
|
485
|
+
jt as c,
|
|
468
486
|
Pt as d,
|
|
469
|
-
|
|
470
|
-
|
|
487
|
+
kt as e,
|
|
488
|
+
Mt as f,
|
|
471
489
|
K as g,
|
|
472
|
-
|
|
490
|
+
Lt as r,
|
|
473
491
|
Rt as u,
|
|
474
492
|
Wt as w
|
|
475
493
|
};
|
|
476
|
-
//# sourceMappingURL=template-fields-
|
|
494
|
+
//# sourceMappingURL=template-fields-C2pSfMBh.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"template-fields-C2pSfMBh.js","sources":["../src/components/editor/designStateStore.ts","../src/components/editor/commerceStore.ts","../src/hooks/useCommands.ts","../src/hooks/useSelectedElement.ts","../src/hooks/useDeadBindingWarning.ts","../src/hooks/useTextBinding.ts","../src/hooks/useImageBinding.ts","../src/hooks/useColorBinding.ts","../src/hooks/useFontBinding.ts","../src/hooks/useElementByName.ts","../src/design/template-fields.ts"],"sourcesContent":["/**\n * The ONE live design-state value under an `Editor.Root` (ADR-0085 §3 / T2).\n *\n * Today's turnkey flow is two stores, one-way, one-shot: the design seeds the\n * canvas once and edits never flow back, so the seed goes stale after the\n * first edit. This store fixes that by construction — seeded from the design\n * at Root mount, updated by every canvas change AND every TextField write,\n * last-write-wins. `Editor.Buy` (and `assertRenders`, P2) read THIS, never\n * the seed, so design staleness can't corrupt an order.\n *\n * TextField ─┐\n * ├─→ DesignStateStore ─→ pushRender ─→ session ─→ Preview(s)\n * Canvas ───┘\n *\n * (With a mounted Canvas the editor document is the write authority and this\n * store derives from its `onChange`; without one, this store IS the\n * authority. The routing lives in the parts — see EditorTextField.)\n *\n * Deliberately a tiny hand-rolled external store (subscribe + snapshot for\n * `useSyncExternalStore`) — narrow subscriptions without re-rendering the\n * whole Root tree per keystroke. Alternate state libraries were considered\n * and rejected (plan decision D3-C).\n */\n\nimport type { AnyElementConfig } from '../../types/index.js';\nimport { EditorError } from '../../errors/editorError.js';\nimport { layerKindOfConfig } from '../../design/design-builder.js';\n\n/** Editor-shape design state — the same shape `design.toJSON()` produces and\n * `<SnowconeCanvas onChange>` emits (and `serializeStateForServer` accepts). */\nexport interface DesignState {\n elements: AnyElementConfig[];\n artboards: Array<{\n name: string;\n width: number;\n height: number;\n backgroundColor?: string;\n exportBackground?: boolean;\n }>;\n activeArtboard: string;\n}\n\nfunction textOf(el: AnyElementConfig): string | undefined {\n return (el as { text?: string }).text;\n}\n\nfunction nameOf(el: AnyElementConfig): string | undefined {\n return (el as { name?: string }).name;\n}\n\nexport class DesignStateStore {\n private state: DesignState;\n /** Frozen snapshot of the values the design was seeded with — Buy's\n * \"differs from seed\" completeness rule (C3) compares against this. */\n private readonly seedTextByName: ReadonlyMap<string, string>;\n private readonly listeners = new Set<() => void>();\n\n constructor(seed: DesignState) {\n this.state = seed;\n const seedTexts = new Map<string, string>();\n for (const el of seed.elements) {\n const name = nameOf(el);\n const text = textOf(el);\n if (name && typeof text === 'string') seedTexts.set(name, text);\n }\n this.seedTextByName = seedTexts;\n }\n\n // Arrow on purpose: handed bare to `useSyncExternalStore` as the snapshot.\n getState = (): DesignState => {\n return this.state;\n };\n\n subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n };\n\n /** Replace the whole state (the canvas `onChange` path). */\n setState(next: DesignState): void {\n this.state = next;\n this.emit();\n }\n\n /** The seed value of a named text layer (for completeness rule C3). */\n seedTextOf(name: string): string | undefined {\n return this.seedTextByName.get(name);\n }\n\n /** Current text of a named text layer, or undefined when absent. */\n textOf(name: string): string | undefined {\n const el = this.state.elements.find((e) => nameOf(e) === name);\n return el ? textOf(el) : undefined;\n }\n\n /** Kind of the named layer in the CURRENT state ('text' | 'image' | null\n * for unbindable), or undefined when no layer has the name. */\n layerKindOf(name: string): 'text' | 'image' | null | undefined {\n const el = this.state.elements.find((e) => nameOf(e) === name);\n return el ? layerKindOfConfig(el) : undefined;\n }\n\n /** Names of bindable layers in the current state, for error messages. */\n bindableLayerNames(): string[] {\n return this.state.elements\n .filter((e) => layerKindOfConfig(e) !== null)\n .map(nameOf)\n .filter((n): n is string => Boolean(n));\n }\n\n /**\n * Direct write path for `Editor.TextField` when NO canvas is mounted (with\n * one, writes route through the editor command path and arrive back here\n * via `setState`). Immutable update; last-write-wins.\n */\n updateTextLayer(name: string, text: string): void {\n let found = false;\n const elements = this.state.elements.map((el) => {\n if (nameOf(el) !== name) return el;\n found = true;\n return { ...el, text } as AnyElementConfig;\n });\n if (!found) {\n throw new EditorError(\n 'E_LAYER_NOT_FOUND',\n `no layer \"${name}\" in the current design state. Bindable layers: ` +\n `${JSON.stringify(this.bindableLayerNames())}.`,\n { layerName: name, validNames: this.bindableLayerNames(), docSlug: 'embed-mode' },\n );\n }\n this.setState({ ...this.state, elements });\n }\n\n /** ≥1 element with visible content (completeness rule C4): non-empty text,\n * an image with a URL, or a shape. Hidden elements don't count. */\n hasRenderableElement(): boolean {\n return this.state.elements.some((el) => {\n if ((el as { visible?: boolean }).visible === false) return false;\n const t = (el as { transformType?: string }).transformType;\n if (t === 'image') return Boolean((el as { imageUrl?: string }).imageUrl);\n if (t === 'shape') return true;\n if (t === 'group' || t === 'path') return true;\n const text = textOf(el);\n return typeof text === 'string' && text.trim().length > 0;\n });\n }\n\n private emit(): void {\n for (const l of [...this.listeners]) l();\n }\n}\n","/**\n * The ONE commerce-selection state under an `Editor.Root` (ADR-0085 §2, P2 —\n * \"Buy-owned variant + quantity state\").\n *\n * Ownership model: `Editor.Buy` OWNS this state (it gates on it and assembles\n * the cart payload from it); the HOST renders the variant-selection UI and\n * reads/writes the same state through `useProductSelection()` — parts carry\n * behavior, hosts own layout/markup (the rendering contract). The state does\n * NOT live on Root props: changing `product.variantId` up there re-keys the\n * whole RenderSession (WS teardown + re-grant + reconnect per color click),\n * which is session identity, not user selection.\n *\n * host variant UI ──select()──┐\n * ├─→ CommerceStateStore ─→ resolvedVariantId ─→ session.setProduct\n * Editor.Buy ──reads─────────┘ │ (live config, no re-key) + re-push state\n * └─→ completeness (C1/C5) + cart payload\n *\n * Selection resolution is the SDK's: `validateProductSelection` +\n * `findBestCombination` (the C1 amendment: full resolution replaces the\n * color-axis-only gate). Like `DesignStateStore`, this is a tiny hand-rolled\n * external store — narrow `useSyncExternalStore` subscriptions, no state lib.\n */\n\nimport {\n computeDisabledChoices,\n findBestCombination,\n getMissingSelections,\n toCombinations,\n toOptionAttributes,\n validateProductSelection,\n type Combination,\n type OptionAttribute,\n type OptionSelection,\n type RenderProduct,\n} from '@snowcone-app/sdk';\nimport { EditorError } from '../../errors/editorError.js';\n\n/**\n * One choice of a variant attribute as the commerce store HANDS IT OUT —\n * always the catalog's choice OBJECT (`toOptionAttributes` normalizes bare\n * strings to `{ label }`). A `hex` marks a color-axis choice (render it as a\n * swatch). NOTE the currency mismatch this type exists to make honest: the\n * SDK's `OptionAttribute` declares `choices: string[]` for its selection\n * math, but the runtime objects flowing through this store are these.\n */\nexport interface ProductOptionChoice {\n label?: string;\n hex?: string;\n [key: string]: unknown;\n}\n\n/** An attribute as `useProductSelection().attributes` returns it: the SDK\n * shape with the choices typed as the objects they actually are. The\n * CURRENCY for `select()` / `selection` / `disabledChoices` is the choice's\n * `label` STRING — pass `choice.label`, never the object. */\nexport interface ProductSelectionAttribute extends Omit<OptionAttribute, 'choices'> {\n choices: ProductOptionChoice[];\n}\n\n/** The label strings of an attribute's choices (legacy attrs may carry bare\n * strings; normalized attrs carry `{ label, hex?, … }` objects). */\nexport function choiceLabelsOf(attr: OptionAttribute | ProductSelectionAttribute): string[] {\n return ((attr.choices ?? []) as Array<string | ProductOptionChoice>)\n .map((c) => (typeof c === 'string' ? c : (c.label ?? '')))\n .filter((label) => label !== '');\n}\n\n/** Derive the seed selection from the product's initial `variantId` — the\n * combination it resolves to pins one value per variant-affecting attribute.\n * No `variantId` (or no match) seeds an empty selection. */\nexport function seedSelectionOf(product: RenderProduct, combinations: Combination[]): OptionSelection {\n if (!product.variantId) return {};\n const combination = combinations.find((c) => c.variantId === product.variantId);\n if (!combination) return {};\n const selection: OptionSelection = {};\n for (const [key, value] of Object.entries(combination)) {\n if (key === 'variantId' || key === 'price') continue;\n if (typeof value === 'string') selection[key] = value;\n else if (typeof value === 'number') selection[key] = String(value);\n }\n return selection;\n}\n\nexport class CommerceStateStore {\n private product: RenderProduct;\n private attrs: Record<string, OptionAttribute>;\n private combos: Combination[];\n private selection: OptionSelection;\n private quantity = 1;\n private version = 0;\n private readonly listeners = new Set<() => void>();\n\n constructor(product: RenderProduct) {\n this.product = product;\n this.attrs = toOptionAttributes({ options: product.options } as Parameters<typeof toOptionAttributes>[0]);\n this.combos = toCombinations({ options: product.options } as Parameters<typeof toCombinations>[0]);\n this.selection = seedSelectionOf(product, this.combos);\n }\n\n // Arrows on purpose: handed bare to `useSyncExternalStore`.\n getVersion = (): number => this.version;\n\n subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n };\n\n getAttributes(): Record<string, ProductSelectionAttribute> {\n // `toOptionAttributes` always normalizes choices to objects (bare strings\n // become `{ label }`), so this narrowing is true by construction. The SDK\n // type's `choices: string[]` describes its selection-math currency, not\n // the runtime shape — hence the through-unknown cast.\n return this.attrs as unknown as Record<string, ProductSelectionAttribute>;\n }\n\n getSelection(): OptionSelection {\n return this.selection;\n }\n\n getQuantity(): number {\n return this.quantity;\n }\n\n /**\n * Select a choice for a variant attribute. Strict + loud (D4/E3): an\n * attribute key or choice that doesn't exist on the product is a wiring\n * mistake, not user state — throws `E_UNKNOWN_OPTION` listing what IS valid.\n */\n select(key: string, choice: string): void {\n const attr = this.attrs[key];\n if (!attr) {\n throw new EditorError(\n 'E_UNKNOWN_OPTION',\n `product ${this.product.productId} has no option \"${key}\". ` +\n `Valid option keys: ${JSON.stringify(Object.keys(this.attrs))}.`,\n { key, validKeys: Object.keys(this.attrs), docSlug: 'embed-mode' },\n );\n }\n const labels = choiceLabelsOf(attr);\n if (labels.length > 0 && !labels.includes(choice)) {\n throw new EditorError(\n 'E_UNKNOWN_OPTION',\n `\"${choice}\" is not a choice of option \"${key}\" on product ${this.product.productId}. ` +\n `Valid choices: ${JSON.stringify(labels)}.`,\n { key, choice, validChoices: labels, docSlug: 'embed-mode' },\n );\n }\n if (this.selection[key] === choice) return;\n this.selection = { ...this.selection, [key]: choice };\n this.bump();\n }\n\n /** Quantity is USER state (completeness rule C5 gates on it) — never throws. */\n setQuantity(quantity: number): void {\n if (this.quantity === quantity) return;\n this.quantity = quantity;\n this.bump();\n }\n\n /** Attribute keys still required (non-optional) but unselected — Buy's\n * `option:<key>` reason codes. */\n missingOptionKeys(): string[] {\n if (Object.keys(this.attrs).length === 0) return [];\n return getMissingSelections(this.attrs, this.selection);\n }\n\n /** Full selection resolution (the C1 amendment): true when every required\n * attribute is selected AND the selection matches a valid combination. */\n selectionValid(): boolean {\n if (Object.keys(this.attrs).length === 0) return true;\n return validateProductSelection(this.attrs, this.selection, this.combos);\n }\n\n /** The variant (gvid) the current selection resolves to. Falls back to the\n * product's initial `variantId` while nothing has been selected. */\n resolvedVariantId(): string | undefined {\n if (Object.keys(this.attrs).length === 0 || this.combos.length === 0) {\n return this.product.variantId;\n }\n if (!this.selectionValid()) return undefined;\n const best = findBestCombination(this.selection, this.combos, this.attrs);\n return (typeof best?.variantId === 'string' && best.variantId !== '' ? best.variantId : undefined) ?? this.product.variantId;\n }\n\n /**\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","/**\n * useCommands - Hook for undo/redo and command history operations\n *\n * Provides a clean interface to command history functionality\n * Must be used within EditorProvider\n *\n * @example\n * ```tsx\n * function UndoRedoToolbar() {\n * const { undo, redo, canUndo, canRedo, clearHistory } = useCommands();\n *\n * return (\n * <div className=\"toolbar\">\n * <button onClick={undo} disabled={!canUndo}>\n * Undo (⌘Z)\n * </button>\n * <button onClick={redo} disabled={!canRedo}>\n * Redo (⌘⇧Z)\n * </button>\n * <button onClick={clearHistory}>\n * Clear History\n * </button>\n * </div>\n * );\n * }\n * ```\n */\n\nimport { useCallback } from 'react';\nimport { useEditor } from '../contexts/EditorContext.js';\nimport { createLogger } from '../utils/logger.js';\n\nconst logger = createLogger('useCommands');\n\nexport interface UseCommandsReturn {\n // Undo/Redo\n undo: () => void;\n redo: () => void;\n canUndo: boolean;\n canRedo: boolean;\n\n // History management\n clearHistory: () => void;\n clearArtboardHistory: (artboardId: string) => void;\n\n // Command execution\n executeElementUpdate: ReturnType<typeof useEditor>['executeElementUpdate'];\n executeAddElement: ReturnType<typeof useEditor>['executeAddElement'];\n executeRemoveElement: ReturnType<typeof useEditor>['executeRemoveElement'];\n executeReorderElement: ReturnType<typeof useEditor>['executeReorderElement'];\n executeCreateArtboard: ReturnType<typeof useEditor>['executeCreateArtboard'];\n executeDeleteArtboard: ReturnType<typeof useEditor>['executeDeleteArtboard'];\n executeUpdateArtboard: ReturnType<typeof useEditor>['executeUpdateArtboard'];\n\n // Batch execution\n executeCommandBatch: (commands: Array<{ execute: () => void; undo: () => void }>) => void;\n}\n\n/**\n * Hook for accessing command history and undo/redo functionality\n * Must be used within EditorProvider\n *\n * @example\n * ```tsx\n * function MyComponent() {\n * const { undo, redo, canUndo, canRedo } = useCommands();\n * const { selectedElement } = useEditor();\n *\n * const handleDelete = () => {\n * if (selectedElement) {\n * executeRemoveElement(selectedElement);\n * }\n * };\n *\n * return (\n * <div>\n * <button onClick={undo} disabled={!canUndo}>Undo</button>\n * <button onClick={redo} disabled={!canRedo}>Redo</button>\n * <button onClick={handleDelete}>Delete</button>\n * </div>\n * );\n * }\n * ```\n */\nexport function useCommands(): UseCommandsReturn {\n const context = useEditor();\n\n // Extract command history methods\n const {\n undo,\n redo,\n canUndo,\n canRedo,\n executeElementUpdate,\n executeAddElement,\n executeRemoveElement,\n executeReorderElement,\n executeCommandBatch,\n executeCreateArtboard,\n executeDeleteArtboard,\n executeUpdateArtboard,\n } = context;\n\n // Clear all history (not exposed in EditorContext yet, so create a placeholder)\n const clearHistory = useCallback(() => {\n logger.warn('[useCommands] clearHistory is not yet implemented in EditorContext');\n }, []);\n\n // Clear artboard-specific history (not exposed in EditorContext yet, so create a placeholder)\n const clearArtboardHistory = useCallback((_artboardId: string) => {\n logger.warn('[useCommands] clearArtboardHistory is not yet implemented in EditorContext');\n }, []);\n\n return {\n // Undo/Redo\n undo,\n redo,\n canUndo,\n canRedo,\n\n // History management\n clearHistory,\n clearArtboardHistory,\n\n // Command execution\n executeElementUpdate,\n executeAddElement,\n executeRemoveElement,\n executeReorderElement,\n executeCreateArtboard,\n executeDeleteArtboard,\n executeUpdateArtboard,\n\n // Batch execution\n executeCommandBatch,\n };\n}\n","import { useEditor } from '../contexts/EditorContext.js';\nimport type { EditorElement } from '../contexts/EditorContext.js';\n\n/**\n * Returns the currently selected element, or null if nothing is selected.\n *\n * This is a convenience wrapper around `useEditor()` that only extracts\n * selection state, keeping consumer components focused on what they need.\n *\n * @example\n * ```tsx\n * function PropertiesPanel() {\n * const selected = useSelectedElement();\n * if (!selected) return <p>Nothing selected</p>;\n * return <p>Selected: {selected.id}</p>;\n * }\n * ```\n */\nexport function useSelectedElement(): EditorElement | null {\n const { selectedElement } = useEditor();\n return selectedElement ?? null;\n}\n","/**\n * useDeadBindingWarning - Dev-only diagnostic for \"dead\" binding hooks.\n *\n * `useTextBinding('typo')` / `useImageBinding('typo')` on a layer name that\n * matches no element returns `isConnected: false` with no-op setters — by\n * design. But with no diagnostic, a typo'd layer name produces a dead control\n * with ZERO console output (the silent-failure finding from the embed-SDK DX\n * evaluation). This hook emits a one-time, dev-only `console.warn` naming the\n * requested layer and listing the canvas's named layers — the same\n * silent-blank-guard pattern as the SDK's `warnImagelessElements` /\n * `[RealtimeEmbed]` validateEmbed warnings.\n *\n * Timing is settle-aware: elements may legitimately arrive late\n * (`initialElements` seeding, an async state load), so warning on first render\n * would false-fire constantly. The `ElementStore` is immutable — every mutation\n * hands the context a NEW store instance, which re-runs the effect — so the\n * grace timer re-arms on every element change and only fires once the element\n * set has been quiet for {@link DEAD_BINDING_GRACE_MS} with still no match.\n * Connecting (or unmounting — StrictMode's throwaway first mount included)\n * clears the pending timer.\n *\n * @module\n */\n\nimport { useEffect } from 'react';\nimport type { ElementStore, StoreElement } from '../core/ElementStore.js';\nimport { TextElement } from '../core/TextElement.js';\nimport { ImageElement } from '../core/ImageElement.js';\n\n/** The binding hook flavor (font binds to TEXT layers — see TARGET_KIND). */\nexport type BindingKind = 'text' | 'image' | 'font';\n\n/**\n * How long the element set must be SETTLED (no store changes) with the binding\n * still unmatched before the warning fires. Long enough for `initialElements`\n * seeding and async state loads to land; short enough to surface a typo well\n * before the user gives up on the dead control.\n */\nexport const DEAD_BINDING_GRACE_MS = 3000;\n\nconst HOOK_NAME: Record<BindingKind, string> = {\n text: 'useTextBinding',\n image: 'useImageBinding',\n font: 'useFontBinding',\n};\n\nconst SETTER_NAME: Record<BindingKind, string> = {\n text: 'setText',\n image: 'setImageUrl',\n font: 'setFontFamily',\n};\n\n/** The element flavor each hook actually matches (font targets text layers). */\nconst TARGET_KIND: Record<BindingKind, 'text' | 'image'> = {\n text: 'text',\n image: 'image',\n font: 'text',\n};\n\n/** Layer names already warned about — the warning is one-time per page load. */\nconst warned = new Set<string>();\n\n/** Test-only: forget which dead bindings have already been warned about. */\nexport function resetDeadBindingWarnings(): void {\n warned.clear();\n}\n\nfunction kindOf(el: StoreElement): string {\n if (el instanceof TextElement) return 'text';\n if (el instanceof ImageElement) return 'image';\n return 'other';\n}\n\n/**\n * Build the dead-binding warning message. Exported for tests; the message\n * distinguishes the two failure shapes:\n * - the name matches a layer of the WRONG type → point at the right hook\n * - the name matches nothing → list the available named layers (or explain\n * how to name one when none carry a name)\n */\nexport function deadBindingWarning(kind: BindingKind, name: string, store: ElementStore): string {\n const tag = `[${HOOK_NAME[kind]}]`;\n const dead = `the binding is dead (isConnected: false, ${SETTER_NAME[kind]} is a no-op)`;\n\n const target = TARGET_KIND[kind];\n const sameName = store.getAllByName(name);\n if (sameName.length > 0) {\n const kinds = [...new Set(sameName.map(kindOf))];\n const other = target === 'text' ? 'image' : 'text';\n const hint =\n kinds.length === 1 && kinds[0] === other\n ? ` Bind it with ${HOOK_NAME[other]}(\"${name}\") instead.`\n : '';\n return (\n `${tag} the layer named \"${name}\" is ${kinds.join('/')}, not ${target} — ` +\n `${dead}.${hint}`\n );\n }\n\n const named = store\n .getAll()\n .filter((el) => el.name)\n .map((el) => `\"${el.name}\" (${kindOf(el)})`);\n const available = named.length\n ? `Named layers on this canvas: ${named.join(', ')}. Check the name for a typo.`\n : `No element on this canvas has a name — name one via design().${target}(…, ` +\n `{ name: '${name}' }) or the element's \\`name\\` property.`;\n return `${tag} no ${target} layer named \"${name}\" exists — ${dead}. ${available}`;\n}\n\n/**\n * Emit the one-time dead-binding warning once the element set settles with the\n * binding still disconnected. Used by `useTextBinding` / `useImageBinding`;\n * dev-only (compiled out of production via the `NODE_ENV` guard) and never\n * throws.\n */\nexport function useDeadBindingWarning(\n kind: BindingKind,\n name: string,\n store: ElementStore,\n isConnected: boolean,\n): void {\n useEffect(() => {\n if (isConnected) return;\n if (typeof process === 'undefined' || process.env?.NODE_ENV === 'production') return;\n const key = `${kind}:${name}`;\n if (warned.has(key)) return;\n\n // The store is immutable, so any element change re-runs this effect with a\n // new instance — re-arming the timer. It fires only once the element set\n // has been quiet for the full grace period with still no match.\n const timer = setTimeout(() => {\n if (warned.has(key)) return; // another component already warned for this name\n warned.add(key);\n console.warn(deadBindingWarning(kind, name, store));\n }, DEAD_BINDING_GRACE_MS);\n return () => clearTimeout(timer);\n }, [kind, name, store, isConnected]);\n}\n","/**\n * useTextBinding - Bidirectional text binding between HTML inputs and canvas text elements.\n *\n * Links an external input to one or more canvas text elements by their `name` property.\n * Multiple elements can share the same name — `setText` updates all of them.\n * Changes flow both ways: input → canvas via `setText`, and canvas edits\n * propagate back through the element store re-render.\n *\n * @example\n * ```tsx\n * function NameInput() {\n * const { text, setText, isConnected } = useTextBinding('headline');\n * return (\n * <input\n * value={text}\n * onChange={(e) => setText(e.target.value)}\n * disabled={!isConnected}\n * />\n * );\n * }\n * ```\n *\n * @module\n */\n\nimport { useMemo, useCallback } from 'react';\nimport { useElementsContext } from '../contexts/ElementsContext.js';\nimport { useCommandContext } from '../contexts/CommandContext.js';\nimport { TextElement } from '../core/TextElement.js';\nimport type { EditorElement } from '../contexts/EditorContext.js';\nimport { useDeadBindingWarning } from './useDeadBindingWarning.js';\n\n/** Result returned by {@link useTextBinding}. */\nexport interface TextBindingResult {\n /** Current plain text content (from first bound element). Empty string if disconnected. */\n text: string;\n /** Update text on all bound elements. No-op if disconnected. */\n setText: (text: string) => void;\n /** The first bound element, or null if no matching text element exists. */\n element: EditorElement | null;\n /** All bound text elements (empty array if disconnected). */\n elements: readonly EditorElement[];\n /** Whether at least one matching text element exists. */\n isConnected: boolean;\n}\n\nconst NOOP = () => {};\nconst EMPTY: readonly EditorElement[] = [];\n\n/**\n * Bind an HTML input to canvas text elements by their `name` property.\n *\n * Multiple elements can share the same name — `setText` updates all of them.\n * Text is read from the first matching element (render order).\n *\n * Must be used within an `EditorProvider`.\n *\n * @param name - The element name to bind to.\n * @returns Text value, setter, element references, and connection status.\n */\nexport function useTextBinding(name: string): TextBindingResult {\n const { elementStore } = useElementsContext();\n const { executeElementUpdate } = useCommandContext();\n\n const textElements = useMemo(() => {\n const all = elementStore.getAllByName(name);\n return all.filter((el): el is TextElement => el instanceof TextElement);\n }, [elementStore, name]);\n\n const setText = useCallback(\n (newText: string) => {\n for (const el of textElements) {\n const cloned = el.clone() as TextElement;\n cloned.setText(newText);\n executeElementUpdate(el, cloned);\n }\n },\n [textElements, executeElementUpdate],\n );\n\n // Dev-only: a name that never matches produces a dead control with no-op\n // setters — warn once the element set settles so a typo isn't silent.\n useDeadBindingWarning('text', name, elementStore, textElements.length > 0);\n\n if (textElements.length === 0) {\n return { text: '', setText: NOOP, element: null, elements: EMPTY, isConnected: false };\n }\n\n return {\n text: textElements[0].getText(),\n setText,\n element: textElements[0],\n elements: textElements,\n isConnected: true,\n };\n}\n","/**\n * useImageBinding - Bidirectional image URL binding between external inputs and canvas image elements.\n *\n * Links an external input to one or more canvas image elements by their `name` property.\n * Multiple elements can share the same name — `setImageUrl` updates all of them.\n * Changes flow both ways: input → canvas via `setImageUrl`, and canvas edits\n * propagate back through the element store re-render.\n *\n * @example\n * ```tsx\n * function LogoUpload() {\n * const { imageUrl, setImageUrl, isConnected } = useImageBinding('logo');\n * return (\n * <input\n * type=\"url\"\n * value={imageUrl}\n * onChange={(e) => setImageUrl(e.target.value)}\n * disabled={!isConnected}\n * />\n * );\n * }\n * ```\n *\n * @module\n */\n\nimport { useMemo, useCallback, useRef } from 'react';\nimport { useElementsContext } from '../contexts/ElementsContext.js';\nimport { useCommandContext } from '../contexts/CommandContext.js';\nimport { ImageElement } from '../core/ImageElement.js';\nimport type { EditorElement } from '../contexts/EditorContext.js';\nimport { useDeadBindingWarning } from './useDeadBindingWarning.js';\n\n/** How the image fits the element bounds. */\nexport type ImageFitMode = 'cover' | 'contain';\n\n/** Options for {@link useImageBinding}. */\nexport interface ImageBindingOptions {\n /** How the image fits the element bounds. Default: \"cover\". */\n fit?: ImageFitMode;\n}\n\n/** Result returned by {@link useImageBinding}. */\nexport interface ImageBindingResult {\n /** Current image URL (from first bound element). Empty string if disconnected. */\n imageUrl: string;\n /** Update image URL on all bound elements. No-op if disconnected. */\n setImageUrl: (url: string) => void;\n /** The first bound element, or null if no matching image element exists. */\n element: EditorElement | null;\n /** All bound image elements (empty array if disconnected). */\n elements: readonly EditorElement[];\n /** Whether at least one matching image element exists. */\n isConnected: boolean;\n}\n\nconst NOOP = () => {};\nconst EMPTY: readonly EditorElement[] = [];\n\n/**\n * Calculate center-crop values so the visible area fills the original element bounds.\n */\nfunction coverCrop(\n origWidth: number,\n origHeight: number,\n imageAspectRatio: number,\n) {\n const placeholderAR = origWidth / origHeight;\n\n if (imageAspectRatio >= placeholderAR) {\n // Image is wider — match height, crop width\n const frameHeight = origHeight;\n const frameWidth = frameHeight * imageAspectRatio;\n const cropWidth = origWidth / frameWidth;\n return {\n width: frameWidth,\n height: frameHeight,\n cropX: (1 - cropWidth) / 2,\n cropY: 0,\n cropWidth,\n cropHeight: 1,\n };\n } else {\n // Image is taller — match width, crop height\n const frameWidth = origWidth;\n const frameHeight = frameWidth / imageAspectRatio;\n const cropHeight = origHeight / frameHeight;\n return {\n width: frameWidth,\n height: frameHeight,\n cropX: 0,\n cropY: (1 - cropHeight) / 2,\n cropWidth: 1,\n cropHeight,\n };\n }\n}\n\n/**\n * Bind an external input to canvas image elements by their `name` property.\n *\n * Multiple elements can share the same name — `setImageUrl` updates all of them.\n * The image URL is read from the first matching element (render order).\n *\n * Must be used within an `EditorProvider`.\n *\n * @param name - The element name to bind to.\n * @param options - Optional configuration (fit mode, etc.).\n * @returns Image URL value, setter, element references, and connection status.\n */\nexport function useImageBinding(name: string, options?: ImageBindingOptions): ImageBindingResult {\n const fit = options?.fit ?? 'cover';\n const { elementStore, setElements } = useElementsContext();\n const { executeElementUpdate } = useCommandContext();\n\n const imageElements = useMemo(() => {\n const all = elementStore.getAllByName(name);\n return all.filter((el): el is ImageElement => el instanceof ImageElement);\n }, [elementStore, name]);\n\n // Capture the original placeholder dimensions once (from the first time we see each element).\n // All subsequent image replacements fit within this fixed box.\n const origDimsRef = useRef<Map<string, { width: number; height: number }>>(new Map());\n for (const el of imageElements) {\n if (!origDimsRef.current.has(el.id)) {\n const td = el.transformData;\n origDimsRef.current.set(el.id, {\n width: td.width * td.cropWidth,\n height: td.height * td.cropHeight,\n });\n }\n }\n\n // Use refs for values that change on every element update to keep setImageUrl stable.\n // Without this, setImageUrl gets a new identity after every executeElementUpdate call,\n // which causes infinite loops when used in useEffect dependency arrays.\n const imageElementsRef = useRef(imageElements);\n imageElementsRef.current = imageElements;\n const executeRef = useRef(executeElementUpdate);\n executeRef.current = executeElementUpdate;\n const setElementsRef = useRef(setElements);\n setElementsRef.current = setElements;\n\n const setImageUrl = useCallback(\n (url: string) => {\n const currentElements = imageElementsRef.current;\n const exec = executeRef.current;\n\n for (const el of currentElements) {\n const orig = origDimsRef.current.get(el.id);\n if (!orig) continue;\n const { width: origW, height: origH } = orig;\n\n const cloned = el.clone() as ImageElement;\n cloned.imageLoaded = false;\n cloned.imageElement = null;\n cloned.isCropping = false;\n cloned.imageUrl = url;\n\n if (fit === 'cover') {\n cloned.preserveDimensions = true;\n\n cloned.onLoadCallback = (loadedElement) => {\n const imgAR = loadedElement.imageAspectRatio || 1;\n const crop = coverCrop(origW, origH, imgAR);\n\n loadedElement.transformData.width = crop.width;\n loadedElement.transformData.height = crop.height;\n loadedElement.transformData.cropX = crop.cropX;\n loadedElement.transformData.cropY = crop.cropY;\n loadedElement.transformData.cropWidth = crop.cropWidth;\n loadedElement.transformData.cropHeight = crop.cropHeight;\n\n // Single atomic update: command history + element store.\n // This ensures auto-export only sees the final cropped state,\n // not an intermediate unloaded state that would produce wrong mockups.\n exec(el, loadedElement);\n };\n } else {\n cloned.preserveDimensions = false;\n\n cloned.onLoadCallback = (loadedElement) => {\n const w = loadedElement.transformData.width;\n const h = loadedElement.transformData.height;\n const scale = Math.min(origW / w, origH / h, 1);\n if (scale < 1) {\n loadedElement.transformData.width = w * scale;\n loadedElement.transformData.height = h * scale;\n }\n loadedElement.transformData.cropX = 0;\n loadedElement.transformData.cropY = 0;\n loadedElement.transformData.cropWidth = 1;\n loadedElement.transformData.cropHeight = 1;\n\n exec(el, loadedElement);\n };\n }\n\n // Start loading — onLoadCallback will update the store via exec()\n // once the image is ready with final dimensions/crop.\n cloned.loadImage(url);\n }\n },\n [fit], // Stable deps only — imageElements/executeElementUpdate/setElements accessed via refs\n );\n\n // Dev-only: a name that never matches produces a dead control with no-op\n // setters — warn once the element set settles so a typo isn't silent.\n useDeadBindingWarning('image', name, elementStore, imageElements.length > 0);\n\n if (imageElements.length === 0) {\n return { imageUrl: '', setImageUrl: NOOP, element: null, elements: EMPTY, isConnected: false };\n }\n\n return {\n imageUrl: imageElements[0].imageUrl,\n setImageUrl,\n element: imageElements[0],\n elements: imageElements,\n isConnected: true,\n };\n}\n","/**\n * useColorBinding - Bind an external color control to every element painted a given color.\n *\n * Unlike `useTextBinding` / `useImageBinding` (which bind by element `name`),\n * a color binding matches by VALUE: every element whose text color, shape\n * fill, path stroke color, or stroke-effect color equals the bound color is\n * updated together. This is how an editable template exposes \"Accent Color\" —\n * the designer picks a color once, and the buyer's swatch repaints every\n * element that used it.\n *\n * The hook tracks the *currently applied* color: after `setColor('#00FF00')`,\n * subsequent matches (and the next `setColor`) are computed against the new\n * color, so repeated changes keep following the same set of elements.\n *\n * @example\n * ```tsx\n * function AccentSwatch({ field }: { field: { color: string; label: string } }) {\n * const { color, setColor, isConnected } = useColorBinding(field.color);\n * return (\n * <input\n * type=\"color\"\n * value={color}\n * onChange={(e) => setColor(e.target.value)}\n * disabled={!isConnected}\n * />\n * );\n * }\n * ```\n *\n * @module\n */\n\nimport { useMemo, useState, useCallback } from 'react';\nimport { useElementsContext } from '../contexts/ElementsContext.js';\nimport { useCommandContext } from '../contexts/CommandContext.js';\nimport type { EditorElement } from '../contexts/EditorContext.js';\n\n/** Result returned by {@link useColorBinding}. */\nexport interface ColorBindingResult {\n /** The currently applied color (normalized uppercase hex). */\n color: string;\n /** Repaint all matching elements. No-op if the value is unchanged. */\n setColor: (color: string) => void;\n /** All elements currently matching the applied color. */\n elements: readonly EditorElement[];\n /** Whether at least one element currently carries the applied color. */\n isConnected: boolean;\n}\n\nconst EMPTY: readonly EditorElement[] = [];\n\n/** Normalize any hex color to uppercase 6-digit form (#RGB → #RRGGBB). */\nfunction normalizeHex(color: string): string {\n let hex = color.trim().toUpperCase();\n if (hex.length === 4 && hex.startsWith('#')) {\n hex = '#' + hex[1] + hex[1] + hex[2] + hex[2] + hex[3] + hex[3];\n }\n return hex;\n}\n\n/** The color-carrying slots a canvas element may have. */\ninterface ColorCarrier {\n color?: unknown;\n setColor?: (c: string) => void;\n transformData?: { fillColor?: unknown; strokeColor?: unknown };\n stroke?: { enabled?: boolean; color?: unknown };\n}\n\nfunction slotMatches(value: unknown, match: string): boolean {\n return typeof value === 'string' && normalizeHex(value) === match;\n}\n\n/** Whether any color slot on the element equals `match` (normalized hex). */\nfunction elementMatchesColor(el: EditorElement, match: string): boolean {\n const c = el as unknown as ColorCarrier;\n return (\n slotMatches(c.color, match) ||\n slotMatches(c.transformData?.fillColor, match) ||\n slotMatches(c.transformData?.strokeColor, match) ||\n (c.stroke?.enabled === true && slotMatches(c.stroke.color, match))\n );\n}\n\n/**\n * Repaint every matching slot on a clone of `el`. Returns the clone if any\n * slot matched, or null if the element doesn't carry the color.\n */\nfunction applyColorToClone(\n el: EditorElement,\n match: string,\n newColor: string,\n): EditorElement | null {\n if (!elementMatchesColor(el, match)) return null;\n\n const cloned = el.clone() as EditorElement;\n const src = el as unknown as ColorCarrier;\n const dst = cloned as unknown as ColorCarrier;\n\n // Text elements: use setColor so richText spans update too.\n if (slotMatches(src.color, match)) {\n if (typeof dst.setColor === 'function') {\n dst.setColor(newColor);\n } else {\n dst.color = newColor;\n }\n }\n\n // Shape/Path elements: fill and stroke colors live in transformData.\n if (slotMatches(src.transformData?.fillColor, match)) {\n dst.transformData = { ...dst.transformData, fillColor: newColor };\n }\n if (slotMatches(src.transformData?.strokeColor, match)) {\n dst.transformData = { ...dst.transformData, strokeColor: newColor };\n }\n\n // Stroke effect (outline) color.\n if (src.stroke?.enabled === true && slotMatches(src.stroke.color, match)) {\n dst.stroke = { ...dst.stroke, color: newColor };\n }\n\n return cloned;\n}\n\n/**\n * Bind an external color control to all elements painted `originalColor`.\n *\n * Must be used within an `EditorProvider`.\n *\n * @param originalColor - The hex color to match (the template field's `color`).\n * @returns Applied color, setter, matching elements, and connection status.\n */\nexport function useColorBinding(originalColor: string): ColorBindingResult {\n const { elementStore } = useElementsContext();\n const { executeElementUpdate } = useCommandContext();\n\n const [applied, setApplied] = useState(() => normalizeHex(originalColor));\n\n // If the hook is re-bound to a different template field, restart tracking.\n const [prevOriginal, setPrevOriginal] = useState(originalColor);\n if (originalColor !== prevOriginal) {\n setPrevOriginal(originalColor);\n setApplied(normalizeHex(originalColor));\n }\n\n // ElementStore is immutable — every mutation hands the context a new store\n // instance, so this memo recomputes whenever elements change.\n const matching = useMemo(\n () => elementStore.getAll().filter((el) => elementMatchesColor(el, applied)),\n [elementStore, applied],\n );\n\n const setColor = useCallback(\n (newColor: string) => {\n const normalizedNew = normalizeHex(newColor);\n if (normalizedNew === applied) return;\n\n for (const el of elementStore.getAll()) {\n const cloned = applyColorToClone(el, applied, newColor);\n if (cloned) executeElementUpdate(el, cloned);\n }\n setApplied(normalizedNew);\n },\n [elementStore, applied, executeElementUpdate],\n );\n\n if (matching.length === 0) {\n return { color: applied, setColor, elements: EMPTY, isConnected: false };\n }\n\n return { color: applied, setColor, elements: matching, isConnected: true };\n}\n","/**\n * useFontBinding - Bind an external font picker to canvas text elements.\n *\n * Links a control to one or more canvas TEXT elements by their `name` property\n * (same matching as `useTextBinding`). `setFontFamily` updates all of them and\n * loads the Google Font into the document, so a family the page hasn't used\n * yet still renders. This is how an editable template exposes a\n * designer-curated font choice (a `select` template field with\n * `property: 'fontFamily'`).\n *\n * Fonts must be on Google Fonts — the picker ecosystem is Google-only so\n * designs render identically across platforms (system fonts are deny-listed).\n *\n * @example\n * ```tsx\n * function FontPicker({ options }: { options: string[] }) {\n * const { fontFamily, setFontFamily, isConnected } = useFontBinding('headline');\n * if (!isConnected) return null;\n * return (\n * <select value={fontFamily} onChange={(e) => setFontFamily(e.target.value)}>\n * {options.map((f) => <option key={f} value={f}>{f}</option>)}\n * </select>\n * );\n * }\n * ```\n *\n * @module\n */\n\nimport { useMemo, useCallback } from 'react';\nimport { useElementsContext } from '../contexts/ElementsContext.js';\nimport { useCommandContext } from '../contexts/CommandContext.js';\nimport { TextElement } from '../core/TextElement.js';\nimport type { EditorElement } from '../contexts/EditorContext.js';\nimport { FontAnalyzer } from '../utils/FontAnalyzer.js';\nimport { UnifiedFontService } from '../utils/UnifiedFontService.js';\nimport { useDeadBindingWarning } from './useDeadBindingWarning.js';\n\n/** Result returned by {@link useFontBinding}. */\nexport interface FontBindingResult {\n /** Current font family (from first bound element). Empty string if disconnected. */\n fontFamily: string;\n /** Update the font family on all bound text elements. No-op if disconnected. */\n setFontFamily: (fontFamily: string) => void;\n /** The first bound element, or null if no matching text element exists. */\n element: EditorElement | null;\n /** All bound text elements (empty array if disconnected). */\n elements: readonly EditorElement[];\n /** Whether at least one matching text element exists. */\n isConnected: boolean;\n}\n\nconst NOOP = () => {};\nconst EMPTY: readonly EditorElement[] = [];\n\n/**\n * Bind a font control to canvas text elements by their `name` property.\n *\n * Must be used within an `EditorProvider`.\n *\n * @param name - The element name to bind to.\n * @returns Font family, setter, element references, and connection status.\n */\nexport function useFontBinding(name: string): FontBindingResult {\n const { elementStore } = useElementsContext();\n const { executeElementUpdate } = useCommandContext();\n\n const textElements = useMemo(() => {\n const all = elementStore.getAllByName(name);\n return all.filter((el): el is TextElement => el instanceof TextElement);\n }, [elementStore, name]);\n\n const setFontFamily = useCallback(\n (newFamily: string) => {\n // Make sure the family is actually available in the document — a buyer\n // picking a font the page never used would otherwise see the fallback.\n UnifiedFontService.loadGoogleFontByName(newFamily);\n\n for (const el of textElements) {\n if (el.fontFamily === newFamily) continue;\n // Old-family glyph caches are per-font and large on iOS — drop them\n // when switching, same as the editor's own font picker.\n FontAnalyzer.clearCache(el.fontFamily);\n const cloned = el.clone() as TextElement;\n cloned.fontFamily = newFamily;\n executeElementUpdate(el, cloned);\n }\n },\n [textElements, executeElementUpdate],\n );\n\n useDeadBindingWarning('font', name, elementStore, textElements.length > 0);\n\n if (textElements.length === 0) {\n return { fontFamily: '', setFontFamily: NOOP, element: null, elements: EMPTY, isConnected: false };\n }\n\n return {\n fontFamily: textElements[0].fontFamily,\n setFontFamily,\n element: textElements[0],\n elements: textElements,\n isConnected: true,\n };\n}\n","/**\n * useElementByName - Look up an element by its `name` property.\n *\n * General-purpose complement to {@link useElementById}. Returns the first\n * element whose `name` matches, following render order.\n *\n * @example\n * ```tsx\n * function ElementInspector({ elementName }: { elementName: string }) {\n * const element = useElementByName(elementName);\n * if (!element) return <p>Element not found</p>;\n * return <p>Position: ({element.x}, {element.y})</p>;\n * }\n * ```\n *\n * @module\n */\n\nimport { useElementsContext } from '../contexts/ElementsContext.js';\nimport type { EditorElement } from '../contexts/EditorContext.js';\n\n/**\n * Returns the first element matching the given name, or null.\n *\n * Must be used within an `EditorProvider`.\n *\n * @param name - The element name to look up, or null to skip the lookup.\n * @returns The matching element, or null if no element matches.\n */\nexport function useElementByName(name: string | null): EditorElement | null {\n const { elementStore } = useElementsContext();\n if (!name) return null;\n return elementStore.getByName(name) ?? null;\n}\n","/**\n * Template fields — the manifest that turns a saved design into an editable template.\n *\n * An editable template is a saved canvas state plus a list of {@link TemplateField}s\n * describing which parts a buyer may change. Text and image fields reference\n * elements by their `name` property (the same names `useTextBinding` /\n * `useImageBinding` bind to); color fields match by value (`useColorBinding`).\n *\n * The fields are stored ON the state document itself under the\n * {@link TEMPLATE_FIELDS_KEY} key (`personalization`) — the same convention\n * snowcone.app's own editor uses, so a template authored in a host app\n * round-trips through Edit / Remix / the PDP unchanged:\n *\n * ```json\n * {\n * \"elements\": [...],\n * \"artboards\": [...],\n * \"activeArtboard\": \"Front\",\n * \"personalization\": [\n * { \"type\": \"text\", \"name\": \"headline\", \"label\": \"Your name\" }\n * ]\n * }\n * ```\n *\n * Write with {@link withTemplateFields}, read back with {@link readTemplateFields}.\n *\n * @module\n */\n\nimport { z } from 'zod';\nimport type { ImageFitMode } from '../hooks/useImageBinding.js';\n\n/** A buyer-editable text slot, bound to elements by their `name` property. */\nexport interface TemplateTextField {\n type: 'text';\n /** Element name (matches canvas layer `name` property). */\n name: string;\n /** Label shown to the buyer (e.g. \"Your name\"). */\n label: string;\n /** Placeholder text for the input. */\n placeholder?: string;\n /**\n * Designer's length limit for the buyer's text — long names overflow fixed\n * layouts. Intent, not enforcement: your control applies it (an input's\n * `maxLength`); the canvas itself doesn't truncate.\n */\n maxLength?: number;\n /**\n * Artboard (page) this field is scoped to, by artboard NAME — the same\n * convention as the element `artboard` membership tag. In a multi-page\n * template (ADR-0086) the same element name can repeat on every page;\n * scoping disambiguates which page's element the field binds. Absent =\n * whole-design (legacy behavior: binds across all artboards).\n */\n artboard?: string;\n /** Optional grouping label — consecutive fields sharing a group render together. */\n group?: string;\n}\n\n/** A buyer-swappable image slot, bound to elements by their `name` property. */\nexport interface TemplateImageField {\n type: 'image';\n /** Element name (matches canvas layer `name` property). */\n name: string;\n /** Label shown to the buyer (e.g. \"Upload your logo\"). */\n label: string;\n /** Placeholder text for the input. */\n placeholder?: string;\n /** How the buyer's image fits the original element bounds. Default: \"cover\". */\n fit?: ImageFitMode;\n /**\n * Artboard (page) this field is scoped to, by artboard NAME — the same\n * convention as the element `artboard` membership tag. In a multi-page\n * template (ADR-0086) the same element name can repeat on every page;\n * scoping disambiguates which page's element the field binds. Absent =\n * whole-design (legacy behavior: binds across all artboards).\n */\n artboard?: string;\n /** Optional grouping label — consecutive fields sharing a group render together. */\n group?: string;\n}\n\n/** A buyer-editable color, matched by value across all elements that use it. */\nexport interface TemplateColorField {\n type: 'color';\n /** Original hex color to match (e.g. \"#FF0000\"). */\n color: string;\n /** Label shown to the buyer (e.g. \"Accent color\"). */\n label: string;\n /**\n * Artboard (page) this field is scoped to, by artboard NAME — the same\n * convention as the element `artboard` membership tag. In a multi-page\n * template (ADR-0086) the same element name can repeat on every page;\n * scoping disambiguates which page's element the field binds. Absent =\n * whole-design (legacy behavior: binds across all artboards).\n */\n artboard?: string;\n /** Optional grouping label — consecutive fields sharing a group render together. */\n group?: string;\n}\n\n/**\n * A pick-one choice over designer-authored options — \"one of these 3 badges\",\n * a curated font list, preset text variants. Binds to elements by `name` and\n * swaps ONE property on them, chosen by `property`:\n *\n * - `'text'` → apply via `useTextBinding(name).setText(value)`\n * - `'imageUrl'` → apply via `useImageBinding(name).setImageUrl(value)`\n * - `'fontFamily'` → apply via `useFontBinding(name).setFontFamily(value)`\n * (values must be Google Fonts families)\n */\nexport interface TemplateSelectField {\n type: 'select';\n /** Element name (matches canvas layer `name` property). */\n name: string;\n /** Label shown to the buyer (e.g. \"Badge\"). */\n label: string;\n /** Which property of the bound element(s) the chosen value sets. */\n property: 'text' | 'imageUrl' | 'fontFamily';\n /** The designer-authored choices, in display order. */\n options: Array<{ label: string; value: string }>;\n /**\n * Artboard (page) this field is scoped to, by artboard NAME — the same\n * convention as the element `artboard` membership tag. In a multi-page\n * template (ADR-0086) the same element name can repeat on every page;\n * scoping disambiguates which page's element the field binds. Absent =\n * whole-design (legacy behavior: binds across all artboards).\n */\n artboard?: string;\n /** Optional grouping label — consecutive fields sharing a group render together. */\n group?: string;\n}\n\n/** One buyer-editable aspect of a template. */\nexport type TemplateField =\n | TemplateTextField\n | TemplateImageField\n | TemplateColorField\n | TemplateSelectField;\n\n/**\n * The key template fields are stored under on the state document.\n * Kept as `personalization` for compatibility with designs saved on snowcone.app.\n */\nexport const TEMPLATE_FIELDS_KEY = 'personalization';\n\nconst templateFieldSchema = z.discriminatedUnion('type', [\n z.object({\n type: z.literal('text'),\n name: z.string().min(1),\n label: z.string(),\n placeholder: z.string().optional(),\n maxLength: z.number().int().positive().optional(),\n artboard: z.string().min(1).optional(),\n group: z.string().optional(),\n }),\n z.object({\n type: z.literal('image'),\n name: z.string().min(1),\n label: z.string(),\n placeholder: z.string().optional(),\n fit: z.union([z.literal('cover'), z.literal('contain')]).optional(),\n artboard: z.string().min(1).optional(),\n group: z.string().optional(),\n }),\n z.object({\n type: z.literal('color'),\n color: z.string().min(1),\n label: z.string(),\n artboard: z.string().min(1).optional(),\n group: z.string().optional(),\n }),\n z.object({\n type: z.literal('select'),\n name: z.string().min(1),\n label: z.string(),\n property: z.union([z.literal('text'), z.literal('imageUrl'), z.literal('fontFamily')]),\n options: z.array(z.object({ label: z.string(), value: z.string() })).min(1),\n artboard: z.string().min(1).optional(),\n group: z.string().optional(),\n }),\n]);\n\n/**\n * Read the template fields off a parsed state document.\n *\n * Accepts any JSON value — a `CanvasState` from `onChange`, a `CanvasStateV1`\n * document, or a raw `JSON.parse` of a stored state file. Legacy fields with\n * no `type` are normalized to text fields; malformed entries are dropped.\n * Returns `[]` when the document carries no fields (a plain, non-template design).\n */\nexport function readTemplateFields(state: unknown): TemplateField[] {\n if (!state || typeof state !== 'object') return [];\n const raw = (state as Record<string, unknown>)[TEMPLATE_FIELDS_KEY];\n if (!Array.isArray(raw)) return [];\n\n const fields: TemplateField[] = [];\n for (const entry of raw) {\n if (!entry || typeof entry !== 'object') continue;\n const candidate = 'type' in entry ? entry : { ...entry, type: 'text' };\n const parsed = templateFieldSchema.safeParse(candidate);\n if (parsed.success) fields.push(parsed.data as TemplateField);\n }\n return fields;\n}\n\n/**\n * Attach template fields to a state document before persisting it.\n *\n * ```ts\n * onChange={(state) => setDraft(state)}\n * // …on save:\n * save(JSON.stringify(withTemplateFields(draft, fields)));\n * ```\n */\nexport function withTemplateFields<T extends object>(\n state: T,\n fields: TemplateField[],\n): T & { [TEMPLATE_FIELDS_KEY]: TemplateField[] } {\n return { ...state, [TEMPLATE_FIELDS_KEY]: fields };\n}\n"],"names":["textOf","el","nameOf","DesignStateStore","seed","listener","seedTexts","name","text","next","layerKindOfConfig","e","n","found","elements","EditorError","t","l","choiceLabelsOf","attr","c","label","seedSelectionOf","product","combinations","combination","selection","key","value","CommerceStateStore","toOptionAttributes","toCombinations","choice","labels","quantity","getMissingSelections","validateProductSelection","best","findBestCombination","stringAttrs","computeDisabledChoices","logger","createLogger","useCommands","context","useEditor","undo","redo","canUndo","canRedo","executeElementUpdate","executeAddElement","executeRemoveElement","executeReorderElement","executeCommandBatch","executeCreateArtboard","executeDeleteArtboard","executeUpdateArtboard","clearHistory","useCallback","clearArtboardHistory","_artboardId","useSelectedElement","selectedElement","DEAD_BINDING_GRACE_MS","HOOK_NAME","SETTER_NAME","TARGET_KIND","warned","kindOf","TextElement","ImageElement","deadBindingWarning","kind","store","tag","dead","target","sameName","kinds","other","hint","named","available","useDeadBindingWarning","isConnected","useEffect","process","timer","NOOP","EMPTY","useTextBinding","elementStore","useElementsContext","useCommandContext","textElements","useMemo","setText","newText","cloned","coverCrop","origWidth","origHeight","imageAspectRatio","placeholderAR","frameHeight","frameWidth","cropWidth","cropHeight","useImageBinding","options","fit","setElements","imageElements","origDimsRef","useRef","td","imageElementsRef","executeRef","setElementsRef","setImageUrl","url","currentElements","exec","orig","origW","origH","loadedElement","imgAR","crop","w","h","scale","normalizeHex","color","hex","slotMatches","match","elementMatchesColor","_a","_b","_c","applyColorToClone","newColor","src","dst","useColorBinding","originalColor","applied","setApplied","useState","prevOriginal","setPrevOriginal","matching","setColor","normalizedNew","useFontBinding","setFontFamily","newFamily","UnifiedFontService","FontAnalyzer","useElementByName","TEMPLATE_FIELDS_KEY","templateFieldSchema","z.discriminatedUnion","z.object","z.literal","z.string","z.number","z.union","z.array","readTemplateFields","state","raw","fields","entry","candidate","parsed","withTemplateFields"],"mappings":";;;;;;;AA0CA,SAASA,EAAOC,G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