@snowcone-app/ui 0.12.2 → 0.13.2

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/personalization/PersonalizationBridge.tsx","../../src/personalization/utils.ts"],"sourcesContent":["\"use client\";\n\n/**\n * PersonalizationBridge — rendered inside SnowconeCanvas overlay (EditorProvider context).\n * Syncs external personalization values into canvas elements.\n *\n * INTERNAL: Not exported from the package. Used by PersonalizationProvider only.\n *\n * Text fields: finds elements by name, calls setText().\n * Color fields: finds all elements matching the original color, updates them.\n * Image fields: uses useImageBinding to update image by name.\n *\n * Key design: effects depend ONLY on the input value (text string / hex color).\n * Callbacks and element arrays are accessed via refs to avoid effect churn from\n * the canvas re-rendering after each update.\n */\n\nimport { useRef, useEffect } from \"react\";\nimport { useEditor, useCommands, useImageBinding } from \"@snowcone-app/canvas\";\nimport type { ImageFitMode } from \"@snowcone-app/canvas\";\nimport type {\n PersonalizationField,\n PersonalizationValues,\n} from \"./types\";\nimport { normalizeHex, isValidImageUrl, useDebouncedValue } from \"./utils\";\n\n// ---------------------------------------------------------------------------\n// TextBinder — syncs a single text personalization value into canvas\n// ---------------------------------------------------------------------------\n\nfunction TextBinder({ name, value }: { name: string; value: string }) {\n const { elements } = useEditor();\n const { executeElementUpdate } = useCommands();\n\n const elementsRef = useRef(elements);\n elementsRef.current = elements;\n const executeRef = useRef(executeElementUpdate);\n executeRef.current = executeElementUpdate;\n\n const hasUserInput = useRef(false);\n\n useEffect(() => {\n if (value == null) return;\n // Skip initial empty value to preserve the designer's original text\n if (value === \"\" && !hasUserInput.current) return;\n hasUserInput.current = true;\n\n const currentElements = elementsRef.current;\n const exec = executeRef.current;\n\n for (const el of currentElements) {\n if (el.name !== name) continue;\n if (!(\"setText\" in el) || typeof (el as any).setText !== \"function\")\n continue;\n const cloned = el.clone();\n (cloned as any).setText(value);\n exec(el, cloned);\n }\n }, [value, name, elements.length]); // Re-run when elements become available\n\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// ColorBinder — updates all elements matching originalColor to newColor\n// ---------------------------------------------------------------------------\n\nfunction ColorBinder({\n originalColor,\n newColor,\n}: {\n originalColor: string;\n newColor: string;\n}) {\n const { elements } = useEditor();\n const { executeElementUpdate } = useCommands();\n\n const elementsRef = useRef(elements);\n elementsRef.current = elements;\n const executeRef = useRef(executeElementUpdate);\n executeRef.current = executeElementUpdate;\n\n const appliedColorRef = useRef(normalizeHex(originalColor));\n\n useEffect(() => {\n const normalizedNew = normalizeHex(newColor);\n if (normalizedNew === appliedColorRef.current) return;\n\n const matchColor = appliedColorRef.current;\n const currentElements = elementsRef.current;\n const exec = executeRef.current;\n\n for (const el of currentElements) {\n let needsUpdate = false;\n const cloned = el.clone();\n\n // Text elements: check .color\n if (\"color\" in el && typeof (el as any).color === \"string\") {\n if (normalizeHex((el as any).color) === matchColor) {\n if (typeof (cloned as any).setColor === \"function\") {\n (cloned as any).setColor(newColor);\n } else {\n (cloned as any).color = newColor;\n }\n needsUpdate = true;\n }\n }\n\n // Shape/Path elements: check transformData.fillColor\n if (\n normalizeHex((el as any).transformData?.fillColor ?? \"\") === matchColor\n ) {\n (cloned as any).transformData = {\n ...(cloned as any).transformData,\n fillColor: newColor,\n };\n needsUpdate = true;\n }\n\n // Path elements: check transformData.strokeColor\n if (\n normalizeHex((el as any).transformData?.strokeColor ?? \"\") ===\n matchColor\n ) {\n (cloned as any).transformData = {\n ...(cloned as any).transformData,\n strokeColor: newColor,\n };\n needsUpdate = true;\n }\n\n // Stroke color\n if (\n (el as any).stroke?.enabled &&\n normalizeHex((el as any).stroke?.color ?? \"\") === matchColor\n ) {\n (cloned as any).stroke = {\n ...(cloned as any).stroke,\n color: newColor,\n };\n needsUpdate = true;\n }\n\n if (needsUpdate) {\n exec(el, cloned);\n }\n }\n\n appliedColorRef.current = normalizedNew;\n }, [newColor, elements.length]); // Re-run when elements become available\n\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// ImageBinder — uses useImageBinding hook from @snowcone-app/canvas\n// ---------------------------------------------------------------------------\n\nfunction ImageBinder({\n name,\n value,\n fit = \"cover\",\n}: {\n name: string;\n value: string;\n fit?: \"cover\" | \"contain\";\n}) {\n const { setImageUrl } = useImageBinding(name, {\n fit: fit as ImageFitMode,\n });\n const hasUserInput = useRef(false);\n const debouncedValue = useDebouncedValue(value, 500);\n\n const setImageUrlRef = useRef(setImageUrl);\n setImageUrlRef.current = setImageUrl;\n\n useEffect(() => {\n if (debouncedValue == null) return;\n if (debouncedValue === \"\" && !hasUserInput.current) return;\n hasUserInput.current = true;\n if (debouncedValue !== \"\" && !isValidImageUrl(debouncedValue)) return;\n\n setImageUrlRef.current(debouncedValue);\n }, [debouncedValue]);\n\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// PersonalizationBridge — maps personalization fields to binder components\n// ---------------------------------------------------------------------------\n\nexport function PersonalizationBridge({\n fields,\n values,\n}: {\n fields: PersonalizationField[];\n values: PersonalizationValues;\n}) {\n return (\n <>\n {fields.map((field) => {\n if (field.type === \"text\") {\n return (\n <TextBinder\n key={`text-${field.name}`}\n name={field.name}\n value={values[field.name] ?? \"\"}\n />\n );\n }\n if (field.type === \"color\") {\n return (\n <ColorBinder\n key={`color-${field.color}`}\n originalColor={field.color}\n newColor={values[field.color] ?? field.color}\n />\n );\n }\n if (field.type === \"image\") {\n return (\n <ImageBinder\n key={`image-${field.name}`}\n name={field.name}\n value={values[field.name] ?? \"\"}\n fit={field.fit ?? \"cover\"}\n />\n );\n }\n return null;\n })}\n </>\n );\n}\n","\"use client\";\n\n/**\n * Personalization Utilities\n */\n\nimport { useEffect, useState } from \"react\";\n\n/** Normalize any hex color to uppercase 6-digit form (#RGB → #RRGGBB) */\nexport function 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/** Check if a string looks like a complete, loadable URL */\nexport function isValidImageUrl(url: string): boolean {\n if (!url || url.length < 10) return false;\n try {\n const parsed = new URL(url);\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") return false;\n if (!parsed.hostname.includes(\".\")) return false;\n if (parsed.pathname.length <= 1) return false;\n return true;\n } catch {\n return false;\n }\n}\n\n/** Debounce a string value — only emits after `delay` ms of inactivity */\nexport function useDebouncedValue(value: string, delay: number): string {\n const [debounced, setDebounced] = useState(value);\n useEffect(() => {\n const timer = setTimeout(() => setDebounced(value), delay);\n return () => clearTimeout(timer);\n }, [value, delay]);\n return debounced;\n}\n\n/**\n * Scroll an input to sit just above the iOS keyboard after it appears.\n * Uses visualViewport.height to determine the visible area above the keyboard.\n */\nexport function scrollInputAboveKeyboard(input: HTMLElement) {\n const position = () => {\n const rect = input.getBoundingClientRect();\n const visibleBottom =\n window.visualViewport?.height || window.innerHeight * 0.5;\n const target = visibleBottom - rect.height - 20;\n const delta = rect.top - target;\n if (Math.abs(delta) > 10) {\n window.scrollBy({ top: delta, behavior: \"smooth\" });\n }\n };\n setTimeout(position, 400);\n window.visualViewport?.addEventListener(\"resize\", position, { once: true });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAiBA,IAAAA,gBAAkC;AAClC,oBAAwD;;;ACZxD,mBAAoC;AAG7B,SAAS,aAAa,OAAuB;AAClD,MAAI,MAAM,MAAM,KAAK,EAAE,YAAY;AACnC,MAAI,IAAI,WAAW,KAAK,IAAI,WAAW,GAAG,GAAG;AAC3C,UAAM,MAAM,IAAI,CAAC,IAAI,IAAI,CAAC,IAAI,IAAI,CAAC,IAAI,IAAI,CAAC,IAAI,IAAI,CAAC,IAAI,IAAI,CAAC;AAAA,EAChE;AACA,SAAO;AACT;AAGO,SAAS,gBAAgB,KAAsB;AACpD,MAAI,CAAC,OAAO,IAAI,SAAS,GAAI,QAAO;AACpC,MAAI;AACF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UACZ,OAAO,OAAO,MAAM,IAAI,KAAK;AAAA,UAC7B,KAAK,MAAM,OAAO;AAAA;AAAA,QAHb,SAAS,MAAM,IAAI;AAAA,MAI1B;AAAA,IAEJ;AACA,WAAO;AAAA,EACT,CAAC,GACH;AAEJ;","names":["import_react"]}
1
+ {"version":3,"sources":["../../src/personalization/PersonalizationBridge.tsx","../../src/personalization/utils.ts"],"sourcesContent":["\"use client\";\n\n/**\n * PersonalizationBridge — rendered inside SnowconeCanvas overlay (EditorProvider context).\n * Syncs external personalization values into canvas elements.\n *\n * INTERNAL: Not exported from the package. Used by PersonalizationProvider only.\n *\n * Text fields: finds elements by name, calls setText().\n * Color fields: finds all elements matching the original color, updates them.\n * Image fields: uses useImageBinding to update image by name.\n *\n * Key design: effects depend ONLY on the input value (text string / hex color).\n * Callbacks and element arrays are accessed via refs to avoid effect churn from\n * the canvas re-rendering after each update.\n */\n\nimport { useRef, useEffect } from \"react\";\nimport { useEditor, useCommands, useImageBinding } from \"@snowcone-app/canvas\";\nimport type { ImageFitMode } from \"@snowcone-app/canvas\";\nimport type {\n PersonalizationField,\n PersonalizationValues,\n} from \"./types\";\nimport { normalizeHex, isValidImageUrl, useDebouncedValue } from \"./utils\";\n\n// ---------------------------------------------------------------------------\n// TextBinder — syncs a single text personalization value into canvas\n// ---------------------------------------------------------------------------\n\nfunction TextBinder({ name, value }: { name: string; value: string }) {\n const { elements } = useEditor();\n const { executeElementUpdate } = useCommands();\n\n const elementsRef = useRef(elements);\n elementsRef.current = elements;\n const executeRef = useRef(executeElementUpdate);\n executeRef.current = executeElementUpdate;\n\n const hasUserInput = useRef(false);\n\n useEffect(() => {\n if (value == null) return;\n // Skip initial empty value to preserve the designer's original text\n if (value === \"\" && !hasUserInput.current) return;\n hasUserInput.current = true;\n\n const currentElements = elementsRef.current;\n const exec = executeRef.current;\n\n for (const el of currentElements) {\n if (el.name !== name) continue;\n if (!(\"setText\" in el) || typeof (el as any).setText !== \"function\")\n continue;\n const cloned = el.clone();\n (cloned as any).setText(value);\n exec(el, cloned);\n }\n }, [value, name, elements.length]); // Re-run when elements become available\n\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// ColorBinder — updates all elements matching originalColor to newColor\n// ---------------------------------------------------------------------------\n\nfunction ColorBinder({\n originalColor,\n newColor,\n}: {\n originalColor: string;\n newColor: string;\n}) {\n const { elements } = useEditor();\n const { executeElementUpdate } = useCommands();\n\n const elementsRef = useRef(elements);\n elementsRef.current = elements;\n const executeRef = useRef(executeElementUpdate);\n executeRef.current = executeElementUpdate;\n\n const appliedColorRef = useRef(normalizeHex(originalColor));\n\n useEffect(() => {\n const normalizedNew = normalizeHex(newColor);\n if (normalizedNew === appliedColorRef.current) return;\n\n const matchColor = appliedColorRef.current;\n const currentElements = elementsRef.current;\n const exec = executeRef.current;\n\n for (const el of currentElements) {\n let needsUpdate = false;\n const cloned = el.clone();\n\n // Text elements: check .color\n if (\"color\" in el && typeof (el as any).color === \"string\") {\n if (normalizeHex((el as any).color) === matchColor) {\n if (typeof (cloned as any).setColor === \"function\") {\n (cloned as any).setColor(newColor);\n } else {\n (cloned as any).color = newColor;\n }\n needsUpdate = true;\n }\n }\n\n // Shape/Path elements: check transformData.fillColor\n if (\n normalizeHex((el as any).transformData?.fillColor ?? \"\") === matchColor\n ) {\n (cloned as any).transformData = {\n ...(cloned as any).transformData,\n fillColor: newColor,\n };\n needsUpdate = true;\n }\n\n // Path elements: check transformData.strokeColor\n if (\n normalizeHex((el as any).transformData?.strokeColor ?? \"\") ===\n matchColor\n ) {\n (cloned as any).transformData = {\n ...(cloned as any).transformData,\n strokeColor: newColor,\n };\n needsUpdate = true;\n }\n\n // Stroke color\n if (\n (el as any).stroke?.enabled &&\n normalizeHex((el as any).stroke?.color ?? \"\") === matchColor\n ) {\n (cloned as any).stroke = {\n ...(cloned as any).stroke,\n color: newColor,\n };\n needsUpdate = true;\n }\n\n if (needsUpdate) {\n exec(el, cloned);\n }\n }\n\n appliedColorRef.current = normalizedNew;\n }, [newColor, elements.length]); // Re-run when elements become available\n\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// ImageBinder — uses useImageBinding hook from @snowcone-app/canvas\n// ---------------------------------------------------------------------------\n\nfunction ImageBinder({\n name,\n value,\n fit = \"cover\",\n}: {\n name: string;\n value: string;\n fit?: \"cover\" | \"contain\";\n}) {\n const { setImageUrl } = useImageBinding(name, {\n fit: fit as ImageFitMode,\n });\n const hasUserInput = useRef(false);\n const debouncedValue = useDebouncedValue(value, 500);\n\n const setImageUrlRef = useRef(setImageUrl);\n setImageUrlRef.current = setImageUrl;\n\n useEffect(() => {\n if (debouncedValue == null) return;\n if (debouncedValue === \"\" && !hasUserInput.current) return;\n hasUserInput.current = true;\n if (debouncedValue !== \"\" && !isValidImageUrl(debouncedValue)) return;\n\n setImageUrlRef.current(debouncedValue);\n }, [debouncedValue]);\n\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// PersonalizationBridge — maps personalization fields to binder components\n// ---------------------------------------------------------------------------\n\nexport function PersonalizationBridge({\n fields,\n values,\n}: {\n fields: PersonalizationField[];\n values: PersonalizationValues;\n}) {\n return (\n <>\n {fields.map((field) => {\n if (field.type === \"text\") {\n return (\n <TextBinder\n key={`text-${field.name}`}\n name={field.name}\n value={values[field.name] ?? \"\"}\n />\n );\n }\n if (field.type === \"color\") {\n return (\n <ColorBinder\n key={`color-${field.color}`}\n originalColor={field.color}\n newColor={values[field.color] ?? field.color}\n />\n );\n }\n if (field.type === \"image\") {\n return (\n <ImageBinder\n key={`image-${field.name}`}\n name={field.name}\n value={values[field.name] ?? \"\"}\n fit={field.fit ?? \"cover\"}\n />\n );\n }\n return null;\n })}\n </>\n );\n}\n","\"use client\";\n\n/**\n * Personalization Utilities\n */\n\nimport { useEffect, useState } from \"react\";\nimport type { PersonalizationField, PersonalizationTextField, PersonalizationValues } from \"./types\";\n\n/** Normalize any hex color to uppercase 6-digit form (#RGB → #RRGGBB) */\nexport function 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/** Check if a string looks like a complete, loadable URL */\nexport function isValidImageUrl(url: string): boolean {\n if (!url || url.length < 10) return false;\n try {\n const parsed = new URL(url);\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") return false;\n if (!parsed.hostname.includes(\".\")) return false;\n if (parsed.pathname.length <= 1) return false;\n return true;\n } catch {\n return false;\n }\n}\n\n/** Has the buyer typed into any TEXT field of the design (any non-blank text)? */\nexport function anyTyped(fields: readonly PersonalizationField[], values: PersonalizationValues): boolean {\n return fields.some((f) => f.type === \"text\" && typeof values[f.name] === \"string\" && values[f.name].trim().length > 0);\n}\n\n/**\n * What a text field's elements draw: its box's text, or null = the element's own (designed) text. A `sample` field draws\n * its sample until anything is typed in any field, then exactly its box (empty = nothing). Any other field draws its\n * box's text (\"\" until typed into, which the binder leaves alone).\n */\nexport function textValueFor(field: PersonalizationTextField, values: PersonalizationValues, typed = false): string | null {\n const v = values[field.name] ?? \"\";\n if (field.sample) return typed ? v : null;\n return v;\n}\n\n/** The font a text element draws with: the canvas's own CSS font shorthand (canvas TextMetrics buildFontString). */\nexport interface TextLineStyle {\n fontSize: number;\n fontFamily: string;\n bold?: boolean;\n italic?: boolean;\n /** Extra advance after each character, px (canvas letterSpacing). */\n letterSpacing?: number;\n}\n\n/** The canvas font shorthand for a style at a size, exactly as the canvas builds it (\"italic bold 72px Oswald\"). */\nexport function canvasFontString(style: TextLineStyle, fontSize = style.fontSize): string {\n return [style.italic ? \"italic\" : \"\", style.bold ? \"bold\" : \"\", `${fontSize}px`, style.fontFamily].filter(Boolean).join(\" \");\n}\n\n/** A share of the box kept free when fitting: measurement differs by a hair between renderers (browser, server raster). */\nexport const FIT_MARGIN = 0.03;\n\n/**\n * The font size one line of `text` is drawn at to fit `maxWidth`: `style.fontSize` when it already fits, else the\n * largest smaller size that does (text width is linear in the font size, plus a fixed letter spacing per character).\n * Never larger than the style's size; never below 1 px. `measure(text, fontSize)` is the line's width at a size.\n */\nexport function shrinkFontSizeToFit(\n text: string,\n style: TextLineStyle,\n maxWidth: number,\n measure: (text: string, fontSize: number) => number,\n): number {\n const limit = maxWidth * (1 - FIT_MARGIN);\n if (!text || !(limit > 0)) return style.fontSize;\n const at = measure(text, style.fontSize);\n if (at <= limit) return style.fontSize;\n const spacing = (style.letterSpacing ?? 0) * text.length;\n let size = Math.max(1, (style.fontSize * Math.max(1, limit - spacing)) / Math.max(1, at - spacing));\n // measurement rounding (hinting, kerning) can leave a hair over: step down until it truly fits\n for (let i = 0; i < 40 && size > 1 && measure(text, size) > limit; i++) size *= 0.98;\n return Math.max(1, Math.floor(size * 2) / 2);\n}\n\nlet measureCtx: CanvasRenderingContext2D | null = null;\n\n/** One line's width in a browser, with the canvas's own font shorthand (0 where no 2D canvas exists, e.g. on a server). */\nexport function measureTextLine(text: string, style: TextLineStyle, fontSize = style.fontSize): number {\n if (typeof document === \"undefined\") return 0;\n measureCtx ??= document.createElement(\"canvas\").getContext(\"2d\");\n if (!measureCtx) return 0;\n measureCtx.font = canvasFontString(style, fontSize);\n return measureCtx.measureText(text).width + (style.letterSpacing ?? 0) * text.length;\n}\n\n/** Debounce a string value — only emits after `delay` ms of inactivity */\nexport function useDebouncedValue(value: string, delay: number): string {\n const [debounced, setDebounced] = useState(value);\n useEffect(() => {\n const timer = setTimeout(() => setDebounced(value), delay);\n return () => clearTimeout(timer);\n }, [value, delay]);\n return debounced;\n}\n\n/**\n * Scroll an input to sit just above the iOS keyboard after it appears.\n * Uses visualViewport.height to determine the visible area above the keyboard.\n */\nexport function scrollInputAboveKeyboard(input: HTMLElement) {\n const position = () => {\n const rect = input.getBoundingClientRect();\n const visibleBottom =\n window.visualViewport?.height || window.innerHeight * 0.5;\n const target = visibleBottom - rect.height - 20;\n const delta = rect.top - target;\n if (Math.abs(delta) > 10) {\n window.scrollBy({ top: delta, behavior: \"smooth\" });\n }\n };\n setTimeout(position, 400);\n window.visualViewport?.addEventListener(\"resize\", position, { once: true });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAiBA,IAAAA,gBAAkC;AAClC,oBAAwD;;;ACZxD,mBAAoC;AAI7B,SAAS,aAAa,OAAuB;AAClD,MAAI,MAAM,MAAM,KAAK,EAAE,YAAY;AACnC,MAAI,IAAI,WAAW,KAAK,IAAI,WAAW,GAAG,GAAG;AAC3C,UAAM,MAAM,IAAI,CAAC,IAAI,IAAI,CAAC,IAAI,IAAI,CAAC,IAAI,IAAI,CAAC,IAAI,IAAI,CAAC,IAAI,IAAI,CAAC;AAAA,EAChE;AACA,SAAO;AACT;AAGO,SAAS,gBAAgB,KAAsB;AACpD,MAAI,CAAC,OAAO,IAAI,SAAS,GAAI,QAAO;AACpC,MAAI;AACF,UAAM,SAAS,IAAI,IAAI,GAAG;AAC1B,QAAI,OAAO,aAAa,WAAW,OAAO,aAAa,SAAU,QAAO;AACxE,QAAI,CAAC,OAAO,SAAS,SAAS,GAAG,EAAG,QAAO;AAC3C,QAAI,OAAO,SAAS,UAAU,EAAG,QAAO;AACxC,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAsEO,SAAS,kBAAkB,OAAe,OAAuB;AACtE,QAAM,CAAC,WAAW,YAAY,QAAI,uBAAS,KAAK;AAChD,8BAAU,MAAM;AACd,UAAM,QAAQ,WAAW,MAAM,aAAa,KAAK,GAAG,KAAK;AACzD,WAAO,MAAM,aAAa,KAAK;AAAA,EACjC,GAAG,CAAC,OAAO,KAAK,CAAC;AACjB,SAAO;AACT;;;AD6FI;AA1KJ,SAAS,WAAW,EAAE,MAAM,MAAM,GAAoC;AACpE,QAAM,EAAE,SAAS,QAAI,yBAAU;AAC/B,QAAM,EAAE,qBAAqB,QAAI,2BAAY;AAE7C,QAAM,kBAAc,sBAAO,QAAQ;AACnC,cAAY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O,SAAS,sBAAsB;AAAA,EACpC;AAAA,EACA;AACF,GAGG;AACD,SACE,2EACG,iBAAO,IAAI,CAAC,UAAU;AACrB,QAAI,MAAM,SAAS,QAAQ;AACzB,aACE;AAAA,QAAC;AAAA;AAAA,UAEC,MAAM,MAAM;AAAA,UACZ,OAAO,OAAO,MAAM,IAAI,KAAK;AAAA;AAAA,QAFxB,QAAQ,MAAM,IAAI;AAAA,MAGzB;AAAA,IAEJ;AACA,QAAI,MAAM,SAAS,SAAS;AAC1B,aACE;AAAA,QAAC;AAAA;AAAA,UAEC,eAAe,MAAM;AAAA,UACrB,UAAU,OAAO,MAAM,KAAK,KAAK,MAAM;AAAA;AAAA,QAFlC,SAAS,MAAM,KAAK;AAAA,MAG3B;AAAA,IAEJ;AACA,QAAI,MAAM,SAAS,SAAS;AAC1B,aACE;AAAA,QAAC;AAAA;AAAA,UAEC,MAAM,MAAM;AAAA,UACZ,OAAO,OAAO,MAAM,IAAI,KAAK;AAAA,UAC7B,KAAK,MAAM,OAAO;AAAA;AAAA,QAHb,SAAS,MAAM,IAAI;AAAA,MAI1B;AAAA,IAEJ;AACA,WAAO;AAAA,EACT,CAAC,GACH;AAEJ;","names":["import_react"]}
@@ -1,5 +1,5 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
- import { P as PersonalizationField, a as PersonalizationValues } from '../types-CNJT8FUd.cjs';
2
+ import { P as PersonalizationField, a as PersonalizationValues } from '../types-BObPMwP5.cjs';
3
3
 
4
4
  declare function PersonalizationBridge({ fields, values, }: {
5
5
  fields: PersonalizationField[];
@@ -1,5 +1,5 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
- import { P as PersonalizationField, a as PersonalizationValues } from '../types-CNJT8FUd.js';
2
+ import { P as PersonalizationField, a as PersonalizationValues } from '../types-BObPMwP5.js';
3
3
 
4
4
  declare function PersonalizationBridge({ fields, values, }: {
5
5
  fields: PersonalizationField[];
@@ -3,7 +3,7 @@ import {
3
3
  isValidImageUrl,
4
4
  normalizeHex,
5
5
  useDebouncedValue
6
- } from "../chunk-WDOT4BST.js";
6
+ } from "../chunk-GY6TC6M6.js";
7
7
 
8
8
  // src/personalization/PersonalizationBridge.tsx
9
9
  import { useRef, useEffect } from "react";
@@ -13,6 +13,22 @@ interface PersonalizationTextField {
13
13
  label: string;
14
14
  /** Input placeholder */
15
15
  placeholder?: string;
16
+ /** The longest text the input takes (the input's `maxLength`): the designer's limit for the layout. */
17
+ maxLength?: number;
18
+ /**
19
+ * How the buyer's text meets the element's box. `"shrink"`: the text is set at the element's own size and made
20
+ * smaller (never larger) until one line of it fits the box width (a custom text element's `transformData.width`), so
21
+ * a long name never runs past the design's edge or wraps onto a line the layout has no room for. Absent: the text
22
+ * keeps the element's size and wraps or overflows as the element does.
23
+ */
24
+ fit?: "shrink";
25
+ /**
26
+ * The element's own text is a SAMPLE ("YOUR NAME"): it shows only until the buyer types into ANY field of the design;
27
+ * from then on this field draws exactly what is in its box, nothing when it is empty (so "Kevin" typed on line 1 of a
28
+ * three-line sample is engraved alone, not as "Kevin / NAME / HERE"). Every box cleared again: the samples come back.
29
+ * Absent: the element's own text stays until this field itself is typed into.
30
+ */
31
+ sample?: boolean;
16
32
  }
17
33
  /** Color field — buyer can change a color throughout the design */
18
34
  interface PersonalizationColorField {
@@ -39,4 +55,4 @@ type PersonalizationField = PersonalizationTextField | PersonalizationColorField
39
55
  /** Buyer's current personalization values. Keys are field names (text/image) or original hex colors (color). */
40
56
  type PersonalizationValues = Record<string, string>;
41
57
 
42
- export type { PersonalizationField as P, PersonalizationValues as a, PersonalizationColorField as b, PersonalizationImageField as c, PersonalizationTextField as d };
58
+ export type { PersonalizationField as P, PersonalizationValues as a, PersonalizationTextField as b, PersonalizationColorField as c, PersonalizationImageField as d };
@@ -13,6 +13,22 @@ interface PersonalizationTextField {
13
13
  label: string;
14
14
  /** Input placeholder */
15
15
  placeholder?: string;
16
+ /** The longest text the input takes (the input's `maxLength`): the designer's limit for the layout. */
17
+ maxLength?: number;
18
+ /**
19
+ * How the buyer's text meets the element's box. `"shrink"`: the text is set at the element's own size and made
20
+ * smaller (never larger) until one line of it fits the box width (a custom text element's `transformData.width`), so
21
+ * a long name never runs past the design's edge or wraps onto a line the layout has no room for. Absent: the text
22
+ * keeps the element's size and wraps or overflows as the element does.
23
+ */
24
+ fit?: "shrink";
25
+ /**
26
+ * The element's own text is a SAMPLE ("YOUR NAME"): it shows only until the buyer types into ANY field of the design;
27
+ * from then on this field draws exactly what is in its box, nothing when it is empty (so "Kevin" typed on line 1 of a
28
+ * three-line sample is engraved alone, not as "Kevin / NAME / HERE"). Every box cleared again: the samples come back.
29
+ * Absent: the element's own text stays until this field itself is typed into.
30
+ */
31
+ sample?: boolean;
16
32
  }
17
33
  /** Color field — buyer can change a color throughout the design */
18
34
  interface PersonalizationColorField {
@@ -39,4 +55,4 @@ type PersonalizationField = PersonalizationTextField | PersonalizationColorField
39
55
  /** Buyer's current personalization values. Keys are field names (text/image) or original hex colors (color). */
40
56
  type PersonalizationValues = Record<string, string>;
41
57
 
42
- export type { PersonalizationField as P, PersonalizationValues as a, PersonalizationColorField as b, PersonalizationImageField as c, PersonalizationTextField as d };
58
+ export type { PersonalizationField as P, PersonalizationValues as a, PersonalizationTextField as b, PersonalizationColorField as c, PersonalizationImageField as d };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@snowcone-app/ui",
3
- "version": "0.12.2",
3
+ "version": "0.13.2",
4
4
  "description": "React components for merchandise visualization and customization",
5
5
  "keywords": [
6
6
  "react",
@@ -76,6 +76,37 @@ function heroSize(
76
76
  return { width };
77
77
  }
78
78
 
79
+ /**
80
+ * How a hero picture changes from the one on screen to the next (both already decoded, so never through a blank):
81
+ * - `instant`: a LIVE frame (a realtime render, a `blob:` URL) replacing a picture. Frames arrive several a second while
82
+ * a shopper types into a personalization box; a 400 ms crossfade per frame smeared each frame over the last and,
83
+ * restarted mid-fade, faded the older frame back in (snowcone.app engraved tumbler, 2026-12-01: "flash like crazy").
84
+ * - `crossfade`: any other change (another design, another size): the old picture fades out over the new.
85
+ */
86
+ export function pictureSwapOf(shownUrl: string | null, nextUrl: string): "instant" | "crossfade" {
87
+ if (!shownUrl) return "instant";
88
+ return nextUrl.startsWith("blob:") || shownUrl.startsWith("blob:") ? "instant" : "crossfade";
89
+ }
90
+
91
+ /**
92
+ * Resolves once `img` is loaded AND decoded (HTMLImageElement.decode), so the swap that follows paints the new picture
93
+ * in the same frame; rejects when it cannot be shown. Without decode() (old browsers, jsdom) the load event stands in.
94
+ */
95
+ export function decodedPicture(img: HTMLImageElement): Promise<void> {
96
+ if (typeof img.decode === "function") {
97
+ return img.decode().catch((e) => {
98
+ // decode() can reject for a picture that DID load (a decode cancelled by a src change elsewhere): show it anyway.
99
+ if (img.complete && img.naturalWidth > 0) return;
100
+ throw e;
101
+ });
102
+ }
103
+ return new Promise<void>((resolve, reject) => {
104
+ if (img.complete) return resolve();
105
+ img.onload = () => resolve();
106
+ img.onerror = () => reject(new Error("E_FRAME_UNAVAILABLE"));
107
+ });
108
+ }
109
+
79
110
  import { useImageTransition } from "../hooks/useImageTransition";
80
111
  import { useContainerWidth } from "../hooks/viewport/useContainerWidth";
81
112
  import { observe } from "../hooks/visibility/observerPool";
@@ -429,7 +460,22 @@ export const HeroProductImage = memo(function HeroProductImage({
429
460
  // Track previous artwork src to detect changes and clear cache
430
461
  const prevArtworkSrcRef = useRef<string | undefined>(undefined);
431
462
  // Track which artwork the current realtimeUrl is for (to detect stale realtime URLs)
432
- const realtimeArtworkSrcRef = useRef<string | undefined>(undefined);
463
+ const artIdentityRef = useRef<string | undefined>(undefined);
464
+ artIdentityRef.current = artIdentity(artworkSrc || selectedArtworkSrc, placementArtKey);
465
+ // A picture MOUNTED with a realtimeUrl (the phone carousel mounts a slide as it nears the screen, handing it the live
466
+ // frame the session already rendered) shows that frame of the CURRENT art: without this the static effect below took
467
+ // it for stale and replaced the shopper's typed name with the store default (engraved opener CFKWA6, picture 3,
468
+ // 2026-12-01: it kept "YOUR NAME" after typing while its stamp said current).
469
+ // Only a LIVE frame counts (a blob:, or the session's own newest frame): the carousel also hands back a static
470
+ // picture this slide made earlier (maybe of another variant), and that one is still replaced by this design's.
471
+ const mountedOnLiveFrame =
472
+ !!realtimeUrl &&
473
+ (realtimeUrl.startsWith("blob:") || (!!actualMockupId && realtimeUrl === realtimeContext?.getMockupUrl?.(actualMockupId)));
474
+ const realtimeArtworkSrcRef = useRef<string | undefined>(
475
+ mountedOnLiveFrame ? artIdentity(artworkSrc || selectedArtworkSrc, placementArtKey) : undefined
476
+ );
477
+ // Whether the art-change effect has seen this picture's first art (its first run is the mount, not a change).
478
+ const artSeenRef = useRef(false);
433
479
  // Track whether we've received a realtime result (for auto mode to switch from static to realtime)
434
480
  const hasReceivedRealtimeRef = useRef(false);
435
481
  // Track whether there's a pending export (to skip static URL generation during realtime updates)
@@ -533,8 +579,9 @@ export const HeroProductImage = memo(function HeroProductImage({
533
579
  }) => {
534
580
  if (!result?.imageUrl) return;
535
581
 
536
- // Mark that we've received a realtime result (for auto mode)
582
+ // Mark that we've received a realtime result (for auto mode), of the art on the page now
537
583
  hasReceivedRealtimeRef.current = true;
584
+ realtimeArtworkSrcRef.current = artIdentityRef.current;
538
585
  // Clear pending flag - realtime result has arrived
539
586
  isPendingExportRef.current = false;
540
587
 
@@ -616,9 +663,16 @@ export const HeroProductImage = memo(function HeroProductImage({
616
663
  };
617
664
  }, [actualMockupId, releaseBlobConsumer]);
618
665
  const frameErrorRef = useRef<string | null>(null);
666
+ // What the main <img> just painted decides the stamp, exactly: a picture that is not a live frame (the static
667
+ // picture) puts it back to 0, an older frame to its own version. Only ever raising it stamped a static picture laid
668
+ // over a v2 frame "current" at v2 (CFKWA6 picture 3, 2026-12-01).
619
669
  const showVersionOf = useCallback((url: string) => {
620
670
  const e = versionByUrlRef.current.get(url);
621
- if (!e || e.v < renderVersionRef.current) return;
671
+ if (!e) {
672
+ renderVersionRef.current = 0;
673
+ renderVersionsRef.current = null;
674
+ return;
675
+ }
622
676
  renderVersionRef.current = e.v;
623
677
  renderVersionsRef.current = e.versions;
624
678
  frameErrorRef.current = null;
@@ -804,10 +858,16 @@ export const HeroProductImage = memo(function HeroProductImage({
804
858
  prevArtworkSrcRef.current = currentSrc;
805
859
  // Reset onLoad tracking so it fires again for new artwork
806
860
  onLoadCalledRef.current = false;
807
- // Reset realtime tracking so static URL generation isn't blocked
808
- hasReceivedRealtimeRef.current = false;
809
- // Reset realtime artwork tracking so stale URLs are detected correctly
810
- realtimeArtworkSrcRef.current = undefined;
861
+ // Reset realtime tracking so static URL generation isn't blocked, and realtime artwork tracking so stale URLs
862
+ // are detected correctly — on a real change of art only. On mount, a live frame this picture already has (the
863
+ // realtimeUrl handed in, see realtimeArtworkSrcRef; or the provider's replay to the subscription above, which set
864
+ // hasReceivedRealtimeRef) is of THIS art: resetting it laid the static default picture over it (the
865
+ // subscription path of CFKWA6 picture 3).
866
+ if (artSeenRef.current) {
867
+ hasReceivedRealtimeRef.current = false;
868
+ realtimeArtworkSrcRef.current = undefined;
869
+ }
870
+ artSeenRef.current = true;
811
871
  }
812
872
  }, [artworkSrc, selectedArtworkSrc, placementArtKey]);
813
873
 
@@ -1112,15 +1172,16 @@ export const HeroProductImage = memo(function HeroProductImage({
1112
1172
  // error toggles, and throws "change in the order of Hooks called by
1113
1173
  // HeroProductImage". Same rule for any new hook added in this component.
1114
1174
  const CROSSFADE_MS = 400;
1115
- const [prevUrl, setPrevUrl] = useState<string | null>(null);
1116
- const [showNew, setShowNew] = useState(false);
1117
- // `renderedUrl` is what the visible <img> actually paints. We delay updating
1118
- // it from `displayUrl` until the new image is preloaded, so the displayed
1119
- // <img> never flashes the new src before the prevUrl crossfade-from layer
1120
- // is in place. Without this delay, when the browser already has the new
1121
- // image cached, the visible <img> snaps to NEW immediately, then the
1122
- // useEffect runs and overlays prevUrl (showing OLD on top), then prevUrl
1123
- // fades out to reveal NEW again — i.e. the new → old → new flash.
1175
+ // The NEXT picture, double-buffered: its own <img> (keyed by its URL, so no element ever changes src while it is
1176
+ // seen) loads INVISIBLE above the picture on screen; once loaded and decoded it shows (at once for a live frame, a
1177
+ // 400 ms fade for another picture), THEN the main <img> takes its URL underneath, and when that has loaded the
1178
+ // incoming layer goes. Whatever the browser does with a src change, the shopper never sees a frame without a picture:
1179
+ // swapping the main <img>'s src directly painted nothing for a frame on a 2560-wide screen (a 2976-px picture whose
1180
+ // decode was not ready, measured 2026-12-01). Stamped data-hero-incoming (loading | showing).
1181
+ const [incoming, setIncoming] = useState<{ url: string; kind: "instant" | "crossfade"; ready: boolean } | null>(null);
1182
+ const incomingRef = useRef(incoming);
1183
+ incomingRef.current = incoming;
1184
+ // `renderedUrl` is what the main <img> paints: it takes a new URL only once the incoming layer covers it.
1124
1185
  const [renderedUrl, setRenderedUrl] = useState<string | null>(displayUrl);
1125
1186
  const renderedUrlRef = useRef(renderedUrl);
1126
1187
  renderedUrlRef.current = renderedUrl;
@@ -1179,38 +1240,45 @@ export const HeroProductImage = memo(function HeroProductImage({
1179
1240
  return;
1180
1241
  }
1181
1242
 
1182
- // Preload new image, then atomically: set prevUrl = old, set rendered = new.
1183
- // Both happen in the same render so the user always sees either OLD or
1184
- // OLD-on-top-of-NEW, never bare NEW before prev is in place.
1185
- const preload = new Image();
1186
- preload.crossOrigin = 'anonymous';
1187
- preload.src = displayUrl;
1188
- const startCrossfade = () => {
1189
- setPrevUrl(oldUrl);
1190
- setRenderedUrl(displayUrl);
1191
- setShowNew(false);
1192
- // Trigger fade-in on next frame so the CSS transition plays
1193
- requestAnimationFrame(() => {
1194
- requestAnimationFrame(() => setShowNew(true));
1195
- });
1196
- };
1197
- if (preload.complete) startCrossfade();
1198
- else preload.onload = startCrossfade;
1199
- // The new frame could not load (e.g. its blob: URL was already revoked): keep the old image on screen, marked —
1200
- // its data-render-version stays behind, so the picture reads stale, never current over an old image.
1201
- preload.onerror = () => {
1202
- frameErrorRef.current = "E_FRAME_UNAVAILABLE";
1203
- frameFailedRef.current?.(displayUrl); // done with it (frame flow control): the box may send the next one
1204
- applyRenderStampRef.current?.();
1205
- };
1206
-
1207
- return () => { preload.onload = null; preload.onerror = null; };
1243
+ // A frame that was still loading when a newer one came is never shown: done with it (frame flow control), so the
1244
+ // box does not wait on it until its ack timeout. Only the latest is ever swapped in.
1245
+ const skipped = incomingRef.current;
1246
+ // Back to the picture the main <img> already shows (A -> B -> A before B showed): nothing to bring in.
1247
+ if (displayUrl === renderedUrlRef.current) {
1248
+ if (skipped && !skipped.ready) frameFailedRef.current?.(skipped.url);
1249
+ setIncoming(null);
1250
+ return;
1251
+ }
1252
+ if (skipped && !skipped.ready && skipped.url !== displayUrl) frameFailedRef.current?.(skipped.url);
1253
+ setIncoming({ url: displayUrl, kind: pictureSwapOf(renderedUrlRef.current, displayUrl), ready: false });
1208
1254
  }, [displayUrl]);
1209
1255
 
1210
- // Clean up old layer after crossfade completes
1211
- const handleCrossfadeEnd = useCallback(() => {
1212
- setPrevUrl(null);
1213
- setShowNew(false);
1256
+ // The next picture could not load (e.g. its blob: URL was already revoked): the picture on screen stays, marked: its
1257
+ // data-render-version stays behind, so it reads stale, never current over an old image.
1258
+ const onIncomingError = useCallback((url: string) => {
1259
+ if (incomingRef.current?.url !== url) return;
1260
+ frameErrorRef.current = "E_FRAME_UNAVAILABLE";
1261
+ frameFailedRef.current?.(url); // done with it (frame flow control): the box may send the next one
1262
+ applyRenderStampRef.current?.();
1263
+ setIncoming(null);
1264
+ }, []);
1265
+ // The incoming layer has loaded: decode it, then show it. A live frame also goes to the main <img> in the same
1266
+ // render (the now opaque incoming layer covers it until the main <img> has loaded it too).
1267
+ const onIncomingLoad = useCallback((el: HTMLImageElement, url: string) => {
1268
+ // Its load event has fired: without decode() (jsdom, old browsers) that is as ready as it gets.
1269
+ (typeof el.decode === "function" ? decodedPicture(el) : Promise.resolve()).then(
1270
+ () => {
1271
+ const cur = incomingRef.current;
1272
+ if (!cur || cur.url !== url) return;
1273
+ setIncoming({ ...cur, ready: true });
1274
+ if (cur.kind === "instant") setRenderedUrl(url);
1275
+ },
1276
+ () => onIncomingError(url)
1277
+ );
1278
+ }, [onIncomingError]);
1279
+ // A crossfade finished: the main <img> takes the new picture under the (now opaque) incoming layer.
1280
+ const onIncomingShown = useCallback((url: string) => {
1281
+ if (incomingRef.current?.url === url) setRenderedUrl(url);
1214
1282
  }, []);
1215
1283
 
1216
1284
  // Unmount the rainbow loader once its fade-out transition has finished.
@@ -1277,6 +1345,7 @@ export const HeroProductImage = memo(function HeroProductImage({
1277
1345
  data-picture-failed-src={failedSrc}
1278
1346
  data-mockup-unavailable={unavailable ? unavailable.code : undefined}
1279
1347
  data-design-refused={designRefused ?? undefined}
1348
+ data-hero-incoming={incoming ? (incoming.ready ? "showing" : "loading") : undefined}
1280
1349
  >
1281
1350
  {unavailable && (
1282
1351
  <div
@@ -1287,12 +1356,8 @@ export const HeroProductImage = memo(function HeroProductImage({
1287
1356
  Mockup unavailable
1288
1357
  </div>
1289
1358
  )}
1290
- {/* Current image — shows `renderedUrl`, which the crossfade effect only
1291
- advances after the next image has finished preloading. This prevents
1292
- the new → old → new flash that happened when displayUrl was bound
1293
- directly to <img src> (the browser snapped to NEW from the cache
1294
- before prevUrl could be staged on top, then prevUrl appeared and
1295
- covered NEW with OLD, then OLD faded back to NEW). */}
1359
+ {/* Current image — shows `renderedUrl`, which only advances once the incoming layer (below in source, above on
1360
+ screen) shows the same picture over it. */}
1296
1361
  {renderedUrl && !imgFailed && (
1297
1362
  <img
1298
1363
  // Remounts on retry (key bump) so the browser issues a fresh request
@@ -1326,6 +1391,8 @@ export const HeroProductImage = memo(function HeroProductImage({
1326
1391
  }
1327
1392
  onUrlGeneratedRef.current?.(renderedUrl);
1328
1393
  if (renderedUrl) onShownRef.current?.(renderedUrl);
1394
+ // The main <img> has the picture the incoming layer was showing over it: the layer can go.
1395
+ if (renderedUrl && incomingRef.current?.url === renderedUrl) setIncoming(null);
1329
1396
  }}
1330
1397
  onError={() => {
1331
1398
  // First failure for this URL → retry once before giving up
@@ -1407,10 +1474,9 @@ export const HeroProductImage = memo(function HeroProductImage({
1407
1474
  )}
1408
1475
 
1409
1476
  {/* Image load failed with no stale image to fall back on. Show a neutral
1410
- panel instead of the browser's broken-image glyph. `prevUrl` (the
1411
- crossfade-from layer below) is kept when present — a stale mockup
1412
- beats a blank one — so we only show this when there's nothing else. */}
1413
- {imgFailed && !prevUrl && (
1477
+ panel instead of the browser's broken-image glyph — unless the
1478
+ incoming layer is showing a picture over it. */}
1479
+ {imgFailed && !incoming?.ready && (
1414
1480
  <div className="absolute inset-0 flex items-center justify-center bg-muted">
1415
1481
  <p className="text-muted-foreground text-xs">{unavailableText}</p>
1416
1482
  </div>
@@ -1436,19 +1502,26 @@ export const HeroProductImage = memo(function HeroProductImage({
1436
1502
  </div>
1437
1503
  )}
1438
1504
 
1439
- {/* Previous image — fades out during crossfade */}
1440
- {prevUrl && (
1505
+ {/* The next picture (see `incoming`): invisible while it loads, then shown over the current one (at once, or a
1506
+ fade for another picture) until the main <img> has it too. Keyed by its URL: a newer picture is a new layer. */}
1507
+ {incoming && (
1441
1508
  <img
1509
+ key={incoming.url}
1442
1510
  alt=""
1511
+ aria-hidden
1443
1512
  crossOrigin="anonymous"
1444
1513
  className={`absolute inset-0 w-full h-full ${fit === "whole" ? "object-contain" : "object-cover"}`}
1445
- src={prevUrl}
1514
+ src={incoming.url}
1515
+ loading="eager"
1516
+ decoding="async"
1446
1517
  style={{
1447
- opacity: showNew ? 0 : 1,
1448
- transition: `opacity ${CROSSFADE_MS}ms ease-in-out`,
1449
- pointerEvents: 'none',
1518
+ opacity: incoming.ready ? 1 : 0,
1519
+ transition: incoming.kind === "crossfade" ? `opacity ${CROSSFADE_MS}ms ease-in-out` : undefined,
1520
+ pointerEvents: "none",
1450
1521
  }}
1451
- onTransitionEnd={handleCrossfadeEnd}
1522
+ onLoad={(e) => onIncomingLoad(e.currentTarget, incoming.url)}
1523
+ onError={() => onIncomingError(incoming.url)}
1524
+ onTransitionEnd={() => onIncomingShown(incoming.url)}
1452
1525
  />
1453
1526
  )}
1454
1527
 
@@ -1456,7 +1529,7 @@ export const HeroProductImage = memo(function HeroProductImage({
1456
1529
  generates. Rendered LAST so it sits ON TOP of the <img>: the image
1457
1530
  loads underneath, then the loader fades OUT to reveal it (a quick
1458
1531
  ~400ms crossfade) instead of the image popping in. First load only;
1459
- later URL changes use the prevUrl crossfade above. */}
1532
+ later URL changes use the incoming layer above. */}
1460
1533
  {loaderMounted && (
1461
1534
  <LoadingOverlayPrismCandyInline
1462
1535
  visible={!firstImageLoaded}
@@ -0,0 +1,147 @@
1
+ /**
2
+ * A picture that MOUNTS after its live frames arrived (snowcone.app bottle opener CFKWA6, 2026-12-01: the shopper typed
3
+ * a name on picture 1, then swiped to picture 3, HCX799). The phone carousel mounts only the slides near the one shown,
4
+ * so picture 3's frames arrived while it had no element; when its slide mounted it was handed the newest frame
5
+ * (`realtimeUrl`, or the provider's replay). The mount counted as an artwork change: the static picture of the DEFAULT
6
+ * design was laid over the live frame, for good, while data-render-state said "current" at version 2.
7
+ *
8
+ * Rules pinned here:
9
+ * - a picture mounted with its newest live frame shows that frame (never the static default over it), whether the
10
+ * carousel hands it in (`realtimeUrl`, fixed in #6688) or the provider replays it to the subscription;
11
+ * - a NON-live URL handed in at mount (the carousel hands back a static picture the slide made earlier, maybe of
12
+ * another variant) is still replaced by the hero's own picture;
13
+ * - data-render-state is "current" only while the element shows a frame of the current version: a non-live picture
14
+ * loaded over a live frame drops data-render-version back to 0;
15
+ * - an artwork change while mounted still replaces a live frame with the new artwork's picture (unchanged).
16
+ */
17
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
18
+ import React from "react";
19
+ import { render, waitFor, cleanup, act, fireEvent } from "@testing-library/react";
20
+ import { ordinaryMockups, type CatalogProduct } from "@snowcone-app/sdk";
21
+ import { HeroProductImage } from "../HeroProductImage";
22
+ import { Product } from "../../patterns/Product";
23
+ import { MOBILE_HERO_WIDTH } from "../heroMockupUrl";
24
+ import KVJVVA from "./fixtures/catalog-KVJVVA.json";
25
+
26
+ const product = KVJVVA as unknown as CatalogProduct & { id: string; mockups: Array<{ id: string }>; placements: Array<{ label: string }> };
27
+ const MOCKUP = ordinaryMockups(product.mockups)[0].id;
28
+ const DEFAULT_ART = "https://agentdraft.storage.snowcone.app/agent-drafts/drf_default.webp";
29
+ const NEW_ART = "https://agentdraft.storage.snowcone.app/agent-drafts/drf_other.webp";
30
+ const LIVE_V2 = "blob:https://snowcone.app/live-frame-v2";
31
+
32
+ // A realtime session that already holds this picture's newest frame (version 2) and has sent canvas version 2.
33
+ const rt = vi.hoisted(() => ({ ctx: null as Record<string, unknown> | null }));
34
+ vi.mock("../../patterns/RealtimeProvider", () => ({ useRealtimeOptional: () => rt.ctx ?? undefined }));
35
+
36
+ function fakeRealtime(liveUrl: string | null) {
37
+ const result = liveUrl ? { mockupId: MOCKUP, imageUrl: liveUrl, requestVersion: 2 } : null;
38
+ return {
39
+ getMockupUrl: (id: string) => (id === MOCKUP ? liveUrl : null),
40
+ getMockupUrls: (ids: string[]) => Object.fromEntries(ids.map((id) => [id, id === MOCKUP ? liveUrl : null])),
41
+ // The provider replays the cached result to a new subscriber (subscribeMockupResultById).
42
+ subscribeMockupResultById: (id: string, cb: (r: unknown) => void) => {
43
+ if (result && id === MOCKUP) cb(result);
44
+ return () => {};
45
+ },
46
+ subscribeBlobSent: () => () => {},
47
+ subscribePendingBlob: () => () => {},
48
+ getCanvasVersion: () => 2,
49
+ getLatestSentVersions: () => ({}),
50
+ getSessionShape: () => ({ phase: "catch-up", width: 3000 }),
51
+ markBlobShown: vi.fn(),
52
+ frameFailed: vi.fn(),
53
+ releaseBlobConsumer: vi.fn(),
54
+ unavailableMockups: new Map(),
55
+ renderError: null,
56
+ };
57
+ }
58
+
59
+ function Hero({ art, realtimeUrl }: { art: string; realtimeUrl?: string }) {
60
+ return (
61
+ <Product productId={product.id} productData={product} initialPlacements={{ Front: { imageUrl: art, alignment: "center" as never } }} dataMode="auto">
62
+ <HeroProductImage
63
+ productId={product.id}
64
+ artwork={{ type: "regular", src: art }}
65
+ placement={product.placements[0].label}
66
+ mockupId={MOCKUP}
67
+ width={MOBILE_HERO_WIDTH}
68
+ realtimeUrl={realtimeUrl}
69
+ viewportPolicy
70
+ />
71
+ </Product>
72
+ );
73
+ }
74
+
75
+ const root = (c: HTMLElement) => c.querySelector("[data-hero-image]") as HTMLElement;
76
+ /** The <img> the picture paints (the crossfade-from layer has alt=""). */
77
+ const shown = (c: HTMLElement) => c.querySelector("img[alt^='Product mockup']") as HTMLImageElement | null;
78
+
79
+ beforeEach(() => {
80
+ (window as unknown as { snowcone?: unknown }).snowcone = { shop: "2e2c853b83" };
81
+ });
82
+ afterEach(() => {
83
+ cleanup();
84
+ delete (window as unknown as { snowcone?: unknown }).snowcone;
85
+ rt.ctx = null;
86
+ vi.unstubAllGlobals();
87
+ });
88
+
89
+ /** jsdom loads nothing; play the browser: the main <img> loads first (a blob: frame is local), then the incoming layer
90
+ * (alt="", a picture over the network) loads and finishes its fade, then the main <img> loads what it took over. */
91
+ async function paint(c: HTMLElement) {
92
+ for (let i = 0; i < 3; i++) {
93
+ const main = shown(c);
94
+ if (main) await act(async () => { fireEvent.load(main); });
95
+ for (const layer of Array.from(c.querySelectorAll<HTMLImageElement>("img[alt='']"))) {
96
+ await act(async () => { fireEvent.load(layer); });
97
+ await act(async () => { await new Promise((r) => setTimeout(r, 0)); });
98
+ await act(async () => { fireEvent.transitionEnd(layer); });
99
+ }
100
+ await act(async () => { await new Promise((r) => setTimeout(r, 10)); });
101
+ }
102
+ }
103
+
104
+ describe("HeroProductImage mounted after its live frames arrived (carousel slide swiped to)", () => {
105
+ it("handed the newest frame as realtimeUrl (the phone carousel): shows it, never the static default over it", async () => {
106
+ rt.ctx = fakeRealtime(LIVE_V2);
107
+ const { container } = render(<Hero art={DEFAULT_ART} realtimeUrl={LIVE_V2} />);
108
+ await paint(container);
109
+ expect(shown(container)?.getAttribute("src")).toBe(LIVE_V2);
110
+ expect(Array.from(container.querySelectorAll("img")).map((i) => i.getAttribute("src"))).toEqual([LIVE_V2]);
111
+ expect(root(container).dataset.renderVersion).toBe("2");
112
+ expect(root(container).dataset.renderState).toBe("current");
113
+ });
114
+
115
+ it("wrong case: a URL the carousel hands back that is NOT the session's frame (its old static picture) is still replaced", async () => {
116
+ rt.ctx = fakeRealtime(null); // no live frame for this picture
117
+ const handedBack = "https://img.snowcone.app/KVJVVA?shop=2e2c853b83&variant=OLD&mockup=X&width=3000";
118
+ const { container } = render(<Hero art={DEFAULT_ART} realtimeUrl={handedBack} />);
119
+ await paint(container);
120
+ const src = new URL(shown(container)!.getAttribute("src")!);
121
+ expect(src.searchParams.get("variant")).not.toBe("OLD");
122
+ expect(src.searchParams.get("mockup")).toBe(MOCKUP);
123
+ });
124
+
125
+ it("no realtimeUrl, the provider replays the cached frame (subscription path): shows it, never the static default", async () => {
126
+ rt.ctx = fakeRealtime(LIVE_V2);
127
+ const { container } = render(<Hero art={DEFAULT_ART} />);
128
+ await paint(container);
129
+ expect(shown(container)?.getAttribute("src")).toBe(LIVE_V2);
130
+ expect(root(container).dataset.renderState).toBe("current");
131
+ });
132
+
133
+ it("a non-live picture painted over a live frame is never stamped current (render-version back to 0, stale)", async () => {
134
+ rt.ctx = fakeRealtime(LIVE_V2);
135
+ const { container, rerender } = render(<Hero art={DEFAULT_ART} realtimeUrl={LIVE_V2} />);
136
+ await paint(container);
137
+ expect(root(container).dataset.renderState).toBe("current");
138
+ // The artwork changes while mounted: the new artwork's static picture replaces the live frame (that is right)...
139
+ rerender(<Hero art={NEW_ART} realtimeUrl={LIVE_V2} />);
140
+ await paint(container);
141
+ const src = shown(container)?.getAttribute("src") ?? "";
142
+ expect(src.startsWith("https://")).toBe(true);
143
+ // ...and the stamp says what is on screen: not version 2, not current.
144
+ expect(root(container).dataset.renderVersion).toBe("0");
145
+ expect(root(container).dataset.renderState).toBe("stale");
146
+ });
147
+ });