@snowcone-app/canvas 0.19.1 → 0.21.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 (86) hide show
  1. package/README.md +124 -13
  2. package/STYLING_CONTRACT.md +427 -0
  3. package/dist/{CanvasRenderer-DUc-MOeR.js → CanvasRenderer-CwiYq8qg.js} +3 -3
  4. package/dist/{CanvasRenderer-DUc-MOeR.js.map → CanvasRenderer-CwiYq8qg.js.map} +1 -1
  5. package/dist/{CanvasStateV1-Bq48qhv5.js → CanvasStateV1-BFabcAKC.js} +35 -30
  6. package/dist/{CanvasStateV1-Bq48qhv5.js.map → CanvasStateV1-BFabcAKC.js.map} +1 -1
  7. package/dist/{ContextualToolbars-CkLjHNPn.js → ContextualToolbars--vTtorNg.js} +5 -5
  8. package/dist/{ContextualToolbars-CkLjHNPn.js.map → ContextualToolbars--vTtorNg.js.map} +1 -1
  9. package/dist/{EditorCanvasImpl-_3xCnLkx.js → EditorCanvasImpl-2ZgIUVpK.js} +18 -17
  10. package/dist/{EditorCanvasImpl-_3xCnLkx.js.map → EditorCanvasImpl-2ZgIUVpK.js.map} +1 -1
  11. package/dist/{ImportManager-D--7JnvW.js → ExportManager-DK7CdI-G.js} +24758 -24758
  12. package/dist/ExportManager-DK7CdI-G.js.map +1 -0
  13. package/dist/{FontAnalyzer-DIlqmyuf.js → FontAnalyzer-BpsTYowD.js} +5 -2
  14. package/dist/FontAnalyzer-BpsTYowD.js.map +1 -0
  15. package/dist/SnowconeCanvas-DqZicdxK.js +1172 -0
  16. package/dist/SnowconeCanvas-DqZicdxK.js.map +1 -0
  17. package/dist/{MenuButton-CeoEAtzP.js → UnifiedFontService-B1PGVu8O.js} +3704 -3429
  18. package/dist/UnifiedFontService-B1PGVu8O.js.map +1 -0
  19. package/dist/advanced.mjs +13 -13
  20. package/dist/api/embed.d.ts +3 -1
  21. package/dist/api/stable.d.ts +2 -2
  22. package/dist/components/editor/EditorAdd.d.ts +2 -1
  23. package/dist/components/editor/EditorBuy.d.ts +2 -1
  24. package/dist/components/editor/EditorCanvas.d.ts +2 -1
  25. package/dist/components/editor/EditorControls.d.ts +2 -1
  26. package/dist/components/editor/EditorHistory.d.ts +2 -1
  27. package/dist/components/editor/EditorLayers.d.ts +2 -1
  28. package/dist/components/editor/EditorMenu.d.ts +2 -1
  29. package/dist/components/editor/EditorPreview.d.ts +2 -1
  30. package/dist/components/editor/EditorRoot.d.ts +2 -1
  31. package/dist/components/editor/EditorTextField.d.ts +2 -1
  32. package/dist/components/editor/useProductSelection.d.ts +2 -1
  33. package/dist/components/embed/SnowconeCanvas.d.ts +10 -2
  34. package/dist/components/embed-realtime/context.d.ts +1 -1
  35. package/dist/contexts/EditorContext.d.ts +1 -1
  36. package/dist/core/ArtboardElement.d.ts +2 -1
  37. package/dist/default-editor/SnowconeEditor.d.ts +40 -0
  38. package/dist/design/design-builder.d.ts +46 -21
  39. package/dist/design/template-fields.d.ts +32 -0
  40. package/dist/design-builder-CPF60RU2.js +367 -0
  41. package/dist/design-builder-CPF60RU2.js.map +1 -0
  42. package/dist/{EditorContext-5QpqAhjh.js → editorErrors-CK1RISFa.js} +382 -358
  43. package/dist/editorErrors-CK1RISFa.js.map +1 -0
  44. package/dist/embed-2tp6Ue90.js +1117 -0
  45. package/dist/embed-2tp6Ue90.js.map +1 -0
  46. package/dist/embed.mjs +33 -31
  47. package/dist/hooks/useArtboards.d.ts +2 -1
  48. package/dist/index.mjs +8 -8
  49. package/dist/internals.mjs +5 -5
  50. package/dist/kits/sections.d.ts +11 -7
  51. package/dist/rendering/serialize-for-server.d.ts +3 -0
  52. package/dist/state/CanvasStateV1.d.ts +12 -0
  53. package/dist/template-fields-FgImixyv.js +476 -0
  54. package/dist/template-fields-FgImixyv.js.map +1 -0
  55. package/dist/testing/assertRenders.d.ts +2 -1
  56. package/dist/testing.mjs +8 -8
  57. package/dist/testing.mjs.map +1 -1
  58. package/dist/types/index.d.ts +10 -0
  59. package/dist/{usePieceGuideBundle-DVOISsB1.js → usePieceGuideBundle-Ctnu5k2D.js} +2 -2
  60. package/dist/{usePieceGuideBundle-DVOISsB1.js.map → usePieceGuideBundle-Ctnu5k2D.js.map} +1 -1
  61. package/dist/{validation-0IscSfRb.js → validation-3YEMnKLB.js} +467 -463
  62. package/dist/validation-3YEMnKLB.js.map +1 -0
  63. package/example/README.md +179 -0
  64. package/example/index.html +12 -0
  65. package/example/package.json +24 -0
  66. package/example/src/Widget.tsx +62 -0
  67. package/example/src/main.tsx +9 -0
  68. package/example/tsconfig.json +14 -0
  69. package/example/vite.config.ts +11 -0
  70. package/llms.txt +45 -0
  71. package/package.json +11 -6
  72. package/dist/EditorContext-5QpqAhjh.js.map +0 -1
  73. package/dist/FontAnalyzer-DIlqmyuf.js.map +0 -1
  74. package/dist/ImportManager-D--7JnvW.js.map +0 -1
  75. package/dist/MenuButton-CeoEAtzP.js.map +0 -1
  76. package/dist/SnowconeCanvas-3PA17na3.js +0 -1166
  77. package/dist/SnowconeCanvas-3PA17na3.js.map +0 -1
  78. package/dist/design-builder-v4935TeS.js +0 -343
  79. package/dist/design-builder-v4935TeS.js.map +0 -1
  80. package/dist/editorErrors-DXNfVXtD.js +0 -29
  81. package/dist/editorErrors-DXNfVXtD.js.map +0 -1
  82. package/dist/embed-D2QOpJXG.js +0 -1090
  83. package/dist/embed-D2QOpJXG.js.map +0 -1
  84. package/dist/template-fields-Dr3fMItw.js +0 -329
  85. package/dist/template-fields-Dr3fMItw.js.map +0 -1
  86. package/dist/validation-0IscSfRb.js.map +0 -1
@@ -1,329 +0,0 @@
1
- import { jsxs as q, jsx as M } from "react/jsx-runtime";
2
- import { p as O, o as P, U as J } from "./MenuButton-CeoEAtzP.js";
3
- import { d as Q, u as X, c as $, b as B } from "./EditorContext-5QpqAhjh.js";
4
- import { useCallback as D, useEffect as Z, useMemo as F, useRef as U, useState as W } from "react";
5
- import { c as ee, y as Y, T as w, I as G, z as te } from "./FontAnalyzer-DIlqmyuf.js";
6
- import { a as ne, o as E, b as f, n as oe, l as x, u as _, c as re } from "./CanvasStateV1-Bq48qhv5.js";
7
- const Ae = () => {
8
- const { undo: t, redo: e, canUndo: r, canRedo: n } = Q();
9
- return /* @__PURE__ */ q("div", { className: "sc-undo-redo", style: { display: "inline-flex", gap: 4 }, children: [
10
- /* @__PURE__ */ M(
11
- O,
12
- {
13
- icon: P.undo,
14
- onClick: t,
15
- disabled: !r,
16
- tooltip: "Undo",
17
- "aria-label": "Undo"
18
- }
19
- ),
20
- /* @__PURE__ */ M(
21
- O,
22
- {
23
- icon: P.redo,
24
- onClick: e,
25
- disabled: !n,
26
- tooltip: "Redo",
27
- "aria-label": "Redo"
28
- }
29
- )
30
- ] });
31
- }, j = ee("useCommands");
32
- function Ue() {
33
- const t = X(), {
34
- undo: e,
35
- redo: r,
36
- canUndo: n,
37
- canRedo: a,
38
- executeElementUpdate: o,
39
- executeAddElement: s,
40
- executeRemoveElement: i,
41
- executeReorderElement: m,
42
- executeCommandBatch: c,
43
- executeCreateArtboard: p,
44
- executeDeleteArtboard: y,
45
- executeUpdateArtboard: u
46
- } = t, d = D(() => {
47
- j.warn("[useCommands] clearHistory is not yet implemented in EditorContext");
48
- }, []), T = D((b) => {
49
- j.warn("[useCommands] clearArtboardHistory is not yet implemented in EditorContext");
50
- }, []);
51
- return {
52
- // Undo/Redo
53
- undo: e,
54
- redo: r,
55
- canUndo: n,
56
- canRedo: a,
57
- // History management
58
- clearHistory: d,
59
- clearArtboardHistory: T,
60
- // Command execution
61
- executeElementUpdate: o,
62
- executeAddElement: s,
63
- executeRemoveElement: i,
64
- executeReorderElement: m,
65
- executeCreateArtboard: p,
66
- executeDeleteArtboard: y,
67
- executeUpdateArtboard: u,
68
- // Batch execution
69
- executeCommandBatch: c
70
- };
71
- }
72
- function Ne() {
73
- const { selectedElement: t } = X();
74
- return t ?? null;
75
- }
76
- const se = 3e3, L = {
77
- text: "useTextBinding",
78
- image: "useImageBinding",
79
- font: "useFontBinding"
80
- }, ae = {
81
- text: "setText",
82
- image: "setImageUrl",
83
- font: "setFontFamily"
84
- }, ie = {
85
- text: "text",
86
- image: "image",
87
- font: "text"
88
- }, R = /* @__PURE__ */ new Set();
89
- function z(t) {
90
- return t instanceof w ? "text" : t instanceof G ? "image" : "other";
91
- }
92
- function ce(t, e, r) {
93
- const n = `[${L[t]}]`, a = `the binding is dead (isConnected: false, ${ae[t]} is a no-op)`, o = ie[t], s = r.getAllByName(e);
94
- if (s.length > 0) {
95
- const c = [...new Set(s.map(z))], p = o === "text" ? "image" : "text", y = c.length === 1 && c[0] === p ? ` Bind it with ${L[p]}("${e}") instead.` : "";
96
- return `${n} the layer named "${e}" is ${c.join("/")}, not ${o} — ${a}.${y}`;
97
- }
98
- const i = r.getAll().filter((c) => c.name).map((c) => `"${c.name}" (${z(c)})`), m = i.length ? `Named layers on this canvas: ${i.join(", ")}. Check the name for a typo.` : `No element on this canvas has a name — name one via design().${o}(…, { name: '${e}' }) or the element's \`name\` property.`;
99
- return `${n} no ${o} layer named "${e}" exists — ${a}. ${m}`;
100
- }
101
- function k(t, e, r, n) {
102
- Z(() => {
103
- var s;
104
- if (n || typeof Y > "u" || ((s = Y.env) == null ? void 0 : s.NODE_ENV) === "production") return;
105
- const a = `${t}:${e}`;
106
- if (R.has(a)) return;
107
- const o = setTimeout(() => {
108
- R.has(a) || (R.add(a), console.warn(ce(t, e, r)));
109
- }, se);
110
- return () => clearTimeout(o);
111
- }, [t, e, r, n]);
112
- }
113
- const le = () => {
114
- }, fe = [];
115
- function Be(t) {
116
- const { elementStore: e } = $(), { executeElementUpdate: r } = B(), n = F(() => e.getAllByName(t).filter((s) => s instanceof w), [e, t]), a = D(
117
- (o) => {
118
- for (const s of n) {
119
- const i = s.clone();
120
- i.setText(o), r(s, i);
121
- }
122
- },
123
- [n, r]
124
- );
125
- return k("text", t, e, n.length > 0), n.length === 0 ? { text: "", setText: le, element: null, elements: fe, isConnected: !1 } : {
126
- text: n[0].getText(),
127
- setText: a,
128
- element: n[0],
129
- elements: n,
130
- isConnected: !0
131
- };
132
- }
133
- const me = () => {
134
- }, ue = [];
135
- function de(t, e, r) {
136
- const n = t / e;
137
- if (r >= n) {
138
- const a = e, o = a * r, s = t / o;
139
- return {
140
- width: o,
141
- height: a,
142
- cropX: (1 - s) / 2,
143
- cropY: 0,
144
- cropWidth: s,
145
- cropHeight: 1
146
- };
147
- } else {
148
- const a = t, o = a / r, s = e / o;
149
- return {
150
- width: a,
151
- height: o,
152
- cropX: 0,
153
- cropY: (1 - s) / 2,
154
- cropWidth: 1,
155
- cropHeight: s
156
- };
157
- }
158
- }
159
- function Fe(t, e) {
160
- const r = (e == null ? void 0 : e.fit) ?? "cover", { elementStore: n, setElements: a } = $(), { executeElementUpdate: o } = B(), s = F(() => n.getAllByName(t).filter((d) => d instanceof G), [n, t]), i = U(/* @__PURE__ */ new Map());
161
- for (const u of s)
162
- if (!i.current.has(u.id)) {
163
- const d = u.transformData;
164
- i.current.set(u.id, {
165
- width: d.width * d.cropWidth,
166
- height: d.height * d.cropHeight
167
- });
168
- }
169
- const m = U(s);
170
- m.current = s;
171
- const c = U(o);
172
- c.current = o;
173
- const p = U(a);
174
- p.current = a;
175
- const y = D(
176
- (u) => {
177
- const d = m.current, T = c.current;
178
- for (const b of d) {
179
- const H = i.current.get(b.id);
180
- if (!H) continue;
181
- const { width: S, height: I } = H, g = b.clone();
182
- g.imageLoaded = !1, g.imageElement = null, g.isCropping = !1, g.imageUrl = u, r === "cover" ? (g.preserveDimensions = !0, g.onLoadCallback = (l) => {
183
- const A = l.imageAspectRatio || 1, h = de(S, I, A);
184
- l.transformData.width = h.width, l.transformData.height = h.height, l.transformData.cropX = h.cropX, l.transformData.cropY = h.cropY, l.transformData.cropWidth = h.cropWidth, l.transformData.cropHeight = h.cropHeight, T(b, l);
185
- }) : (g.preserveDimensions = !1, g.onLoadCallback = (l) => {
186
- const A = l.transformData.width, h = l.transformData.height, v = Math.min(S / A, I / h, 1);
187
- v < 1 && (l.transformData.width = A * v, l.transformData.height = h * v), l.transformData.cropX = 0, l.transformData.cropY = 0, l.transformData.cropWidth = 1, l.transformData.cropHeight = 1, T(b, l);
188
- }), g.loadImage(u);
189
- }
190
- },
191
- [r]
192
- // Stable deps only — imageElements/executeElementUpdate/setElements accessed via refs
193
- );
194
- return k("image", t, n, s.length > 0), s.length === 0 ? { imageUrl: "", setImageUrl: me, element: null, elements: ue, isConnected: !1 } : {
195
- imageUrl: s[0].imageUrl,
196
- setImageUrl: y,
197
- element: s[0],
198
- elements: s,
199
- isConnected: !0
200
- };
201
- }
202
- const pe = [];
203
- function N(t) {
204
- let e = t.trim().toUpperCase();
205
- return e.length === 4 && e.startsWith("#") && (e = "#" + e[1] + e[1] + e[2] + e[2] + e[3] + e[3]), e;
206
- }
207
- function C(t, e) {
208
- return typeof t == "string" && N(t) === e;
209
- }
210
- function K(t, e) {
211
- var n, a, o;
212
- const r = t;
213
- return C(r.color, e) || C((n = r.transformData) == null ? void 0 : n.fillColor, e) || C((a = r.transformData) == null ? void 0 : a.strokeColor, e) || ((o = r.stroke) == null ? void 0 : o.enabled) === !0 && C(r.stroke.color, e);
214
- }
215
- function ge(t, e, r) {
216
- var s, i, m;
217
- if (!K(t, e)) return null;
218
- const n = t.clone(), a = t, o = n;
219
- return C(a.color, e) && (typeof o.setColor == "function" ? o.setColor(r) : o.color = r), C((s = a.transformData) == null ? void 0 : s.fillColor, e) && (o.transformData = { ...o.transformData, fillColor: r }), C((i = a.transformData) == null ? void 0 : i.strokeColor, e) && (o.transformData = { ...o.transformData, strokeColor: r }), ((m = a.stroke) == null ? void 0 : m.enabled) === !0 && C(a.stroke.color, e) && (o.stroke = { ...o.stroke, color: r }), n;
220
- }
221
- function ve(t) {
222
- const { elementStore: e } = $(), { executeElementUpdate: r } = B(), [n, a] = W(() => N(t)), [o, s] = W(t);
223
- t !== o && (s(t), a(N(t)));
224
- const i = F(
225
- () => e.getAll().filter((c) => K(c, n)),
226
- [e, n]
227
- ), m = D(
228
- (c) => {
229
- const p = N(c);
230
- if (p !== n) {
231
- for (const y of e.getAll()) {
232
- const u = ge(y, n, c);
233
- u && r(y, u);
234
- }
235
- a(p);
236
- }
237
- },
238
- [e, n, r]
239
- );
240
- return i.length === 0 ? { color: n, setColor: m, elements: pe, isConnected: !1 } : { color: n, setColor: m, elements: i, isConnected: !0 };
241
- }
242
- const he = () => {
243
- }, xe = [];
244
- function Re(t) {
245
- const { elementStore: e } = $(), { executeElementUpdate: r } = B(), n = F(() => e.getAllByName(t).filter((s) => s instanceof w), [e, t]), a = D(
246
- (o) => {
247
- J.loadGoogleFontByName(o);
248
- for (const s of n) {
249
- if (s.fontFamily === o) continue;
250
- te.clearCache(s.fontFamily);
251
- const i = s.clone();
252
- i.fontFamily = o, r(s, i);
253
- }
254
- },
255
- [n, r]
256
- );
257
- return k("font", t, e, n.length > 0), n.length === 0 ? { fontFamily: "", setFontFamily: he, element: null, elements: xe, isConnected: !1 } : {
258
- fontFamily: n[0].fontFamily,
259
- setFontFamily: a,
260
- element: n[0],
261
- elements: n,
262
- isConnected: !0
263
- };
264
- }
265
- function we(t) {
266
- const { elementStore: e } = $();
267
- return t ? e.getByName(t) ?? null : null;
268
- }
269
- const V = "personalization", ye = ne("type", [
270
- E({
271
- type: x("text"),
272
- name: f().min(1),
273
- label: f(),
274
- placeholder: f().optional(),
275
- maxLength: oe().int().positive().optional(),
276
- group: f().optional()
277
- }),
278
- E({
279
- type: x("image"),
280
- name: f().min(1),
281
- label: f(),
282
- placeholder: f().optional(),
283
- fit: _([x("cover"), x("contain")]).optional(),
284
- group: f().optional()
285
- }),
286
- E({
287
- type: x("color"),
288
- color: f().min(1),
289
- label: f(),
290
- group: f().optional()
291
- }),
292
- E({
293
- type: x("select"),
294
- name: f().min(1),
295
- label: f(),
296
- property: _([x("text"), x("imageUrl"), x("fontFamily")]),
297
- options: re(E({ label: f(), value: f() })).min(1),
298
- group: f().optional()
299
- })
300
- ]);
301
- function ke(t) {
302
- if (!t || typeof t != "object") return [];
303
- const e = t[V];
304
- if (!Array.isArray(e)) return [];
305
- const r = [];
306
- for (const n of e) {
307
- if (!n || typeof n != "object") continue;
308
- const a = "type" in n ? n : { ...n, type: "text" }, o = ye.safeParse(a);
309
- o.success && r.push(o.data);
310
- }
311
- return r;
312
- }
313
- function He(t, e) {
314
- return { ...t, [V]: e };
315
- }
316
- export {
317
- V as T,
318
- Ae as U,
319
- Ue as a,
320
- we as b,
321
- Re as c,
322
- Fe as d,
323
- Ne as e,
324
- Be as f,
325
- ke as r,
326
- ve as u,
327
- He as w
328
- };
329
- //# sourceMappingURL=template-fields-Dr3fMItw.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"template-fields-Dr3fMItw.js","sources":["../src/components/embed/UndoRedoControls.tsx","../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 * UndoRedoControls — a tiny topbar control pair for undo/redo.\n *\n * Registered as the `undo-redo-controls` kit section (referenced by the\n * `pro-studio` preset) and wrapped by `Editor.History` (ADR-0085). Reads\n * command state from the NARROW history sub-context — not the fat\n * `useEditor()` — so it only re-renders when undo/redo availability actually\n * changes (re-render containment, D3).\n */\n\nimport React from 'react';\nimport { ToolbarButton } from '../ui/toolbar-button.js';\nimport { icons } from '../ui/icons.js';\nimport { useHistoryContext } from '../../contexts/HistoryContext.js';\n\nexport const UndoRedoControls: React.FC = () => {\n const { undo, redo, canUndo, canRedo } = useHistoryContext();\n return (\n <div className=\"sc-undo-redo\" style={{ display: 'inline-flex', gap: 4 }}>\n <ToolbarButton\n icon={icons.undo}\n onClick={undo}\n disabled={!canUndo}\n tooltip=\"Undo\"\n aria-label=\"Undo\"\n />\n <ToolbarButton\n icon={icons.redo}\n onClick={redo}\n disabled={!canRedo}\n tooltip=\"Redo\"\n aria-label=\"Redo\"\n />\n </div>\n );\n};\n\nexport default UndoRedoControls;\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 /** 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 /** 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 /** 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 /** 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 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 group: z.string().optional(),\n }),\n z.object({\n type: z.literal('color'),\n color: z.string().min(1),\n label: z.string(),\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 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":["UndoRedoControls","undo","redo","canUndo","canRedo","useHistoryContext","jsxs","jsx","ToolbarButton","icons","logger","createLogger","useCommands","context","useEditor","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","el","TextElement","ImageElement","deadBindingWarning","kind","name","store","tag","dead","target","sameName","kinds","other","hint","named","available","useDeadBindingWarning","isConnected","useEffect","process","key","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","scale","normalizeHex","color","hex","slotMatches","value","match","elementMatchesColor","c","_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":";;;;;;AAeO,MAAMA,KAA6B,MAAM;AAC9C,QAAM,EAAE,MAAAC,GAAM,MAAAC,GAAM,SAAAC,GAAS,SAAAC,EAAA,IAAYC,EAAA;AACzC,SACE,gBAAAC,EAAC,OAAA,EAAI,WAAU,gBAAe,OAAO,EAAE,SAAS,eAAe,KAAK,EAAA,GAClE,UAAA;AAAA,IAAA,gBAAAC;AAAA,MAACC;AAAA,MAAA;AAAA,QACC,MAAMC,EAAM;AAAA,QACZ,SAASR;AAAA,QACT,UAAU,CAACE;AAAA,QACX,SAAQ;AAAA,QACR,cAAW;AAAA,MAAA;AAAA,IAAA;AAAA,IAEb,gBAAAI;AAAA,MAACC;AAAA,MAAA;AAAA,QACC,MAAMC,EAAM;AAAA,QACZ,SAASP;AAAA,QACT,UAAU,CAACE;AAAA,QACX,SAAQ;AAAA,QACR,cAAW;AAAA,MAAA;AAAA,IAAA;AAAA,EACb,GACF;AAEJ,GCHMM,IAASC,GAAa,aAAa;AAoDlC,SAASC,KAAiC;AAC/C,QAAMC,IAAUC,EAAA,GAGV;AAAA,IACJ,MAAAb;AAAA,IACA,MAAAC;AAAA,IACA,SAAAC;AAAA,IACA,SAAAC;AAAA,IACA,sBAAAW;AAAA,IACA,mBAAAC;AAAA,IACA,sBAAAC;AAAA,IACA,uBAAAC;AAAA,IACA,qBAAAC;AAAA,IACA,uBAAAC;AAAA,IACA,uBAAAC;AAAA,IACA,uBAAAC;AAAA,EAAA,IACET,GAGEU,IAAeC,EAAY,MAAM;AACrC,IAAAd,EAAO,KAAK,oEAAoE;AAAA,EAClF,GAAG,CAAA,CAAE,GAGCe,IAAuBD,EAAY,CAACE,MAAwB;AAChE,IAAAhB,EAAO,KAAK,4EAA4E;AAAA,EAC1F,GAAG,CAAA,CAAE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