@snowcone-app/ui 0.13.0 → 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.
- package/CHANGELOG.md +12 -0
- package/dist/index.cjs +135 -39
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +14 -1
- package/dist/index.d.ts +14 -1
- package/dist/index.js +133 -39
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/composed/HeroProductImage.tsx +137 -64
- package/src/composed/__tests__/HeroProductImage.mountsOnLiveFrame.test.tsx +147 -0
- package/src/composed/__tests__/HeroProductImage.swap.test.tsx +105 -0
- package/src/patterns/RealtimeProvider.tsx +32 -1
- package/src/patterns/__tests__/RealtimeProvider.blobLifecycle.test.tsx +73 -0
- package/src/personalization/PersonalizationProvider.tsx +43 -1
- package/src/personalization/__tests__/PersonalizationProvider.last-keystroke.test.tsx +81 -0
package/package.json
CHANGED
|
@@ -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
|
|
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
|
|
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
|
-
|
|
809
|
-
//
|
|
810
|
-
|
|
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
|
-
|
|
1116
|
-
|
|
1117
|
-
//
|
|
1118
|
-
//
|
|
1119
|
-
// <img>
|
|
1120
|
-
//
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
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
|
-
//
|
|
1183
|
-
//
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
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
|
-
//
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
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
|
|
1291
|
-
|
|
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
|
|
1411
|
-
|
|
1412
|
-
|
|
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
|
-
{/*
|
|
1440
|
-
|
|
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={
|
|
1514
|
+
src={incoming.url}
|
|
1515
|
+
loading="eager"
|
|
1516
|
+
decoding="async"
|
|
1446
1517
|
style={{
|
|
1447
|
-
opacity:
|
|
1448
|
-
transition: `opacity ${CROSSFADE_MS}ms ease-in-out
|
|
1449
|
-
pointerEvents:
|
|
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
|
-
|
|
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
|
|
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
|
+
});
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Typing into a personalization box must not make the pictures flash (snowcone.app engraved tumbler / opener,
|
|
3
|
+
* 2026-12-01):
|
|
4
|
+
* - the picture on screen stays until the next one has loaded AND decoded; a live frame (blob:) then swaps in at once,
|
|
5
|
+
* with no 400 ms crossfade per keystroke; another picture (a new design) still crossfades;
|
|
6
|
+
* - a picture MOUNTED with a live frame (the phone carousel mounting slide 3 as the shopper swipes) keeps that frame:
|
|
7
|
+
* its static store-default picture never replaces it (picture 3 kept "YOUR NAME" while its stamp said current).
|
|
8
|
+
*/
|
|
9
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
10
|
+
import React from "react";
|
|
11
|
+
import { act, cleanup, fireEvent, render, waitFor } from "@testing-library/react";
|
|
12
|
+
import { HeroProductImage, pictureSwapOf } from "../HeroProductImage";
|
|
13
|
+
|
|
14
|
+
const ART = { type: "regular", src: "https://example.test/art.png" } as const;
|
|
15
|
+
const PRODUCT = { id: "CFKWA6", placements: [{ label: "Front", key: "front" }] };
|
|
16
|
+
|
|
17
|
+
/** An Image that loads and decodes at once (jsdom fetches nothing). */
|
|
18
|
+
class DecodedImage {
|
|
19
|
+
crossOrigin = "";
|
|
20
|
+
decoding = "auto";
|
|
21
|
+
src = "";
|
|
22
|
+
complete = true;
|
|
23
|
+
naturalWidth = 1;
|
|
24
|
+
onload: (() => void) | null = null;
|
|
25
|
+
onerror: (() => void) | null = null;
|
|
26
|
+
decode() {
|
|
27
|
+
return Promise.resolve();
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const srcs = (c: HTMLElement) => Array.from(c.querySelectorAll("img")).map((i) => i.getAttribute("src"));
|
|
32
|
+
|
|
33
|
+
describe("pictureSwapOf", () => {
|
|
34
|
+
it("a live frame swaps at once; another picture crossfades", () => {
|
|
35
|
+
expect(pictureSwapOf("blob:https://x/1", "blob:https://x/2")).toBe("instant");
|
|
36
|
+
expect(pictureSwapOf("https://img.test/a", "blob:https://x/2")).toBe("instant");
|
|
37
|
+
expect(pictureSwapOf("blob:https://x/1", "https://img.test/b")).toBe("instant");
|
|
38
|
+
expect(pictureSwapOf("https://img.test/a", "https://img.test/b")).toBe("crossfade");
|
|
39
|
+
expect(pictureSwapOf(null, "https://img.test/b")).toBe("instant");
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
describe("HeroProductImage: swapping pictures without a blank or a smear", () => {
|
|
44
|
+
beforeEach(() => {
|
|
45
|
+
(window as unknown as { snowcone?: unknown }).snowcone = { shop: "shop1" };
|
|
46
|
+
vi.stubGlobal("Image", DecodedImage);
|
|
47
|
+
});
|
|
48
|
+
afterEach(() => {
|
|
49
|
+
cleanup();
|
|
50
|
+
vi.unstubAllGlobals();
|
|
51
|
+
delete (window as unknown as { snowcone?: unknown }).snowcone;
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
const hero = (realtimeUrl: string, mode?: "realtime") => (
|
|
55
|
+
<HeroProductImage productId="CFKWA6" mockupId="HCX799" gvid="gv1" artwork={ART} product={PRODUCT} width={800} realtimeUrl={realtimeUrl} mode={mode} />
|
|
56
|
+
);
|
|
57
|
+
|
|
58
|
+
const root = (c: HTMLElement) => c.querySelector<HTMLElement>("[data-hero-image]")!;
|
|
59
|
+
const layer = (c: HTMLElement) => c.querySelectorAll("img")[1] as HTMLImageElement;
|
|
60
|
+
|
|
61
|
+
it("live frames: the next frame loads hidden over the shown one, then shows at once; the main picture follows under it", async () => {
|
|
62
|
+
const { container, rerender } = render(hero("blob:https://shop.test/frame-1"));
|
|
63
|
+
await waitFor(() => expect(srcs(container)).toEqual(["blob:https://shop.test/frame-1"]));
|
|
64
|
+
rerender(hero("blob:https://shop.test/frame-2"));
|
|
65
|
+
// loading: the shown picture is untouched, the next one invisible above it
|
|
66
|
+
await waitFor(() => expect(srcs(container)).toEqual(["blob:https://shop.test/frame-1", "blob:https://shop.test/frame-2"]));
|
|
67
|
+
expect(root(container).dataset.heroIncoming).toBe("loading");
|
|
68
|
+
expect(layer(container).style.opacity).toBe("0");
|
|
69
|
+
fireEvent.load(layer(container));
|
|
70
|
+
// shown at once (no fade), and the main <img> takes the frame underneath it
|
|
71
|
+
await waitFor(() => expect(root(container).dataset.heroIncoming).toBe("showing"));
|
|
72
|
+
expect(layer(container).style.opacity).toBe("1");
|
|
73
|
+
expect(layer(container).style.transition).toBe("");
|
|
74
|
+
expect(srcs(container)).toEqual(["blob:https://shop.test/frame-2", "blob:https://shop.test/frame-2"]);
|
|
75
|
+
fireEvent.load(container.querySelector("img")!);
|
|
76
|
+
await waitFor(() => expect(srcs(container)).toEqual(["blob:https://shop.test/frame-2"]));
|
|
77
|
+
expect(root(container).dataset.heroIncoming).toBeUndefined();
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
it("another picture: fades in over the old one, which stays until the fade is done", async () => {
|
|
81
|
+
// Only the pictures it is handed (mode "realtime": no static picture of its own). In "auto", a non-live URL handed
|
|
82
|
+
// in at mount is replaced by the hero's own static picture (HeroProductImage.mountsOnLiveFrame.test.tsx).
|
|
83
|
+
const { container, rerender } = render(hero("https://img.test/a.png", "realtime"));
|
|
84
|
+
await waitFor(() => expect(srcs(container)).toEqual(["https://img.test/a.png"]));
|
|
85
|
+
rerender(hero("https://img.test/b.png", "realtime"));
|
|
86
|
+
await waitFor(() => expect(srcs(container)).toEqual(["https://img.test/a.png", "https://img.test/b.png"]));
|
|
87
|
+
fireEvent.load(layer(container));
|
|
88
|
+
await waitFor(() => expect(layer(container).style.opacity).toBe("1"));
|
|
89
|
+
expect(layer(container).style.transition).toContain("opacity");
|
|
90
|
+
expect(srcs(container)[0]).toBe("https://img.test/a.png");
|
|
91
|
+
fireEvent.transitionEnd(layer(container));
|
|
92
|
+
await waitFor(() => expect(srcs(container)).toEqual(["https://img.test/b.png", "https://img.test/b.png"]));
|
|
93
|
+
fireEvent.load(container.querySelector("img")!);
|
|
94
|
+
await waitFor(() => expect(srcs(container)).toEqual(["https://img.test/b.png"]));
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it("a picture mounted with a live frame keeps it: its static picture never replaces it", async () => {
|
|
98
|
+
const { container } = render(hero("blob:https://shop.test/typed-name"));
|
|
99
|
+
// the static path signs/builds asynchronously; give every effect and promise a turn
|
|
100
|
+
await act(async () => {
|
|
101
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
102
|
+
});
|
|
103
|
+
expect(srcs(container)).toEqual(["blob:https://shop.test/typed-name"]);
|
|
104
|
+
});
|
|
105
|
+
});
|
|
@@ -779,6 +779,9 @@ export function RealtimeProvider({
|
|
|
779
779
|
// full-frame re-render (see rerenderFullFrame).
|
|
780
780
|
const fullFrameRerenderIdsRef = useRef<Set<string>>(new Set());
|
|
781
781
|
const fullFrameRerenderTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
782
|
+
const rerenderFullFrameRef = useRef<((mockupId: string) => void) | null>(null);
|
|
783
|
+
// Pictures whose newest frame was lost and re-asked (frameFailed), until they show a picture again.
|
|
784
|
+
const lostFrameAskedRef = useRef<Set<string>>(new Set());
|
|
782
785
|
useEffect(
|
|
783
786
|
() => () => {
|
|
784
787
|
if (fullFrameRerenderTimerRef.current) clearTimeout(fullFrameRerenderTimerRef.current);
|
|
@@ -859,6 +862,7 @@ export function RealtimeProvider({
|
|
|
859
862
|
*/
|
|
860
863
|
const markBlobShown = useCallback((owner: string, url: string, consumer = "default") => {
|
|
861
864
|
ackUrl(url); // drawn: the box may send this picture's next frame
|
|
865
|
+
lostFrameAskedRef.current.delete(owner); // it shows a picture again: a later lost frame may ask again
|
|
862
866
|
const list = blobsByOwnerRef.current.get(owner);
|
|
863
867
|
if (!list || list.indexOf(url) < 0) return;
|
|
864
868
|
const shown = shownBlobByOwnerRef.current.get(owner) ?? new Map<string, string>();
|
|
@@ -867,9 +871,35 @@ export function RealtimeProvider({
|
|
|
867
871
|
releaseOlderFrames(owner);
|
|
868
872
|
}, [releaseOlderFrames, ackUrl]);
|
|
869
873
|
|
|
870
|
-
/**
|
|
874
|
+
/**
|
|
875
|
+
* A picture could not load a delivered frame (its img errored): the client is done with it (frame flow control).
|
|
876
|
+
*
|
|
877
|
+
* When that frame is the picture's NEWEST (still what getMockupUrl hands out) and nothing newer is on its way, the
|
|
878
|
+
* edit would be lost on that picture: it was off screen when its frames came (the phone carousel mounts only the
|
|
879
|
+
* slides near the one shown) and its newest frame died before an element drew it. Forget the dead frame, so no
|
|
880
|
+
* later element is handed it, and re-render exactly that picture (rerenderFullFrame). Once per picture until it
|
|
881
|
+
* shows something again (markBlobShown), so a frame that can never load cannot loop.
|
|
882
|
+
*/
|
|
871
883
|
const frameFailed = useCallback((url: string) => {
|
|
872
884
|
ackUrl(url);
|
|
885
|
+
if (!url.startsWith("blob:")) return; // a network picture: HeroProductImage's retry and fallback own it
|
|
886
|
+
let mockupId: string | undefined;
|
|
887
|
+
mockupUrlCacheRef.current.forEach((entry, id) => {
|
|
888
|
+
if (entry.url === url) mockupId = id;
|
|
889
|
+
});
|
|
890
|
+
if (!mockupId) return; // not its newest frame: a newer one was delivered
|
|
891
|
+
if (pendingMockupIdsRef.current.has(mockupId)) return; // an edit's frame is on its way
|
|
892
|
+
if (compositeQueueRef.current.has(mockupId) || compositeBusyRef.current.has(mockupId)) return; // its successor composites
|
|
893
|
+
if (lostFrameAskedRef.current.has(mockupId)) return;
|
|
894
|
+
lostFrameAskedRef.current.add(mockupId);
|
|
895
|
+
console.error(
|
|
896
|
+
`[RealtimeProvider] E_FRAME_LOST: ${mockupId}'s newest frame could not be loaded (gone before any element drew it); re-rendering that picture.`
|
|
897
|
+
);
|
|
898
|
+
// Forget it where a later element would be handed it (getMockupUrl(s), the replay to a new subscriber). Not
|
|
899
|
+
// revoked here: a twin element may still show it; it is released like any frame once the re-render is shown.
|
|
900
|
+
mockupUrlCacheRef.current.delete(mockupId);
|
|
901
|
+
mockupResultsRef.current = mockupResultsRef.current.filter((r) => r.imageUrl !== url);
|
|
902
|
+
rerenderFullFrameRef.current?.(mockupId);
|
|
873
903
|
}, [ackUrl]);
|
|
874
904
|
|
|
875
905
|
/** An element of a picture is gone (unmount): it no longer holds a frame. */
|
|
@@ -1022,6 +1052,7 @@ export function RealtimeProvider({
|
|
|
1022
1052
|
},
|
|
1023
1053
|
[sendFullFrameConfig, forceRerenderByConfig, sendRerenderPaced]
|
|
1024
1054
|
);
|
|
1055
|
+
rerenderFullFrameRef.current = rerenderFullFrame;
|
|
1025
1056
|
|
|
1026
1057
|
/** Flip to cropped delivery once every configured mockup has a frozen
|
|
1027
1058
|
* background (a cropped frame can't seed one). */
|