@snowcone-app/ui 0.9.5 → 0.9.7
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 +109 -31
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +109 -31
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/composed/HeroProductImage.tsx +39 -4
- package/src/patterns/RealtimeProvider.tsx +109 -35
- package/src/patterns/__tests__/RealtimeProvider.blobLifecycle.test.tsx +214 -0
- package/src/patterns/__tests__/RealtimeProvider.cropDelivery.test.tsx +24 -0
package/package.json
CHANGED
|
@@ -555,6 +555,18 @@ export const HeroProductImage = memo(function HeroProductImage({
|
|
|
555
555
|
// picture stuck on `stale` is the "editor updates, pictures don't" defect
|
|
556
556
|
// (snowcone.app phone case, 2026-11-11). Absent until the first edit.
|
|
557
557
|
const renderVersionRef = useRef(0);
|
|
558
|
+
// What arrived vs what is on screen: url -> the version it was rendered from; the url the <img> has loaded.
|
|
559
|
+
const arrivedVersionRef = useRef(0);
|
|
560
|
+
const versionByUrlRef = useRef<Map<string, { v: number; versions: Record<string, number> | null }>>(new Map());
|
|
561
|
+
const loadedUrlRef = useRef<string | null>(null);
|
|
562
|
+
const frameErrorRef = useRef<string | null>(null);
|
|
563
|
+
const showVersionOf = useCallback((url: string) => {
|
|
564
|
+
const e = versionByUrlRef.current.get(url);
|
|
565
|
+
if (!e || e.v < renderVersionRef.current) return;
|
|
566
|
+
renderVersionRef.current = e.v;
|
|
567
|
+
renderVersionsRef.current = e.versions;
|
|
568
|
+
frameErrorRef.current = null;
|
|
569
|
+
}, []);
|
|
558
570
|
// Per-placement versions of the shown frame (servers that stamp them).
|
|
559
571
|
const renderVersionsRef = useRef<Record<string, number> | null>(null);
|
|
560
572
|
const getLatestSentVersions = realtimeContext?.getLatestSentVersions;
|
|
@@ -584,10 +596,15 @@ export const HeroProductImage = memo(function HeroProductImage({
|
|
|
584
596
|
: rendered < canvas;
|
|
585
597
|
node.dataset.canvasVersion = String(canvas);
|
|
586
598
|
node.dataset.renderVersion = String(rendered);
|
|
599
|
+
node.dataset.arrivedVersion = String(arrivedVersionRef.current);
|
|
600
|
+
if (frameErrorRef.current) node.dataset.frameError = frameErrorRef.current;
|
|
601
|
+
else delete node.dataset.frameError;
|
|
587
602
|
node.dataset.renderState = refusalCodeRef.current || (behind && sessionErrorCodeRef.current)
|
|
588
603
|
? "refused"
|
|
589
604
|
: behind ? "stale" : "current";
|
|
590
605
|
}, [getCanvasVersion, getLatestSentVersions]);
|
|
606
|
+
const applyRenderStampRef = useRef(applyRenderStamp);
|
|
607
|
+
applyRenderStampRef.current = applyRenderStamp;
|
|
591
608
|
// Re-apply after every render (the root node can change; refusals are state).
|
|
592
609
|
useEffect(() => {
|
|
593
610
|
applyRenderStamp();
|
|
@@ -598,9 +615,15 @@ export const HeroProductImage = memo(function HeroProductImage({
|
|
|
598
615
|
if (!actualMockupId || !subscribeSent || !subscribeResult) return;
|
|
599
616
|
const offSent = subscribeSent(() => applyRenderStamp());
|
|
600
617
|
const offResult = subscribeResult(actualMockupId, (result) => {
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
618
|
+
// A frame ARRIVED; data-render-version moves only when it is ON SCREEN (the <img> loaded it): a frame
|
|
619
|
+
// revoked or failed before it painted must never be stamped current (prod 2026-11-11).
|
|
620
|
+
if (typeof result?.requestVersion === "number") {
|
|
621
|
+
arrivedVersionRef.current = Math.max(arrivedVersionRef.current, result.requestVersion);
|
|
622
|
+
const url = realtimeContext?.getMockupUrl?.(result.mockupId) ?? result.imageUrl;
|
|
623
|
+
if (url) {
|
|
624
|
+
versionByUrlRef.current.set(url, { v: result.requestVersion, versions: result.versions ?? null });
|
|
625
|
+
if (url === loadedUrlRef.current) showVersionOf(url); // already on screen (an identical re-delivery)
|
|
626
|
+
}
|
|
604
627
|
}
|
|
605
628
|
applyRenderStamp();
|
|
606
629
|
});
|
|
@@ -1043,8 +1066,14 @@ export const HeroProductImage = memo(function HeroProductImage({
|
|
|
1043
1066
|
};
|
|
1044
1067
|
if (preload.complete) startCrossfade();
|
|
1045
1068
|
else preload.onload = startCrossfade;
|
|
1069
|
+
// The new frame could not load (e.g. its blob: URL was already revoked): keep the old image on screen, marked —
|
|
1070
|
+
// its data-render-version stays behind, so the picture reads stale, never current over an old image.
|
|
1071
|
+
preload.onerror = () => {
|
|
1072
|
+
frameErrorRef.current = "E_FRAME_UNAVAILABLE";
|
|
1073
|
+
applyRenderStampRef.current?.();
|
|
1074
|
+
};
|
|
1046
1075
|
|
|
1047
|
-
return () => { preload.onload = null; };
|
|
1076
|
+
return () => { preload.onload = null; preload.onerror = null; };
|
|
1048
1077
|
}, [displayUrl]);
|
|
1049
1078
|
|
|
1050
1079
|
// Clean up old layer after crossfade completes
|
|
@@ -1145,6 +1174,12 @@ export const HeroProductImage = memo(function HeroProductImage({
|
|
|
1145
1174
|
onLoad={() => {
|
|
1146
1175
|
setImgFailed(false);
|
|
1147
1176
|
setFirstImageLoaded(true);
|
|
1177
|
+
if (renderedUrl) {
|
|
1178
|
+
loadedUrlRef.current = renderedUrl;
|
|
1179
|
+
showVersionOf(renderedUrl);
|
|
1180
|
+
if (actualMockupId) realtimeContext?.markBlobShown?.(actualMockupId, renderedUrl);
|
|
1181
|
+
applyRenderStampRef.current?.();
|
|
1182
|
+
}
|
|
1148
1183
|
if (!onLoadCalledRef.current && onLoad) {
|
|
1149
1184
|
onLoadCalledRef.current = true;
|
|
1150
1185
|
onLoad();
|
|
@@ -62,8 +62,16 @@ const DEFAULT_ARTBOARD_SIZE = 2000;
|
|
|
62
62
|
// Enforce a conservative cap to prevent memory crashes
|
|
63
63
|
const MAX_CONCURRENT_BLOBS = 5;
|
|
64
64
|
|
|
65
|
+
/**
|
|
66
|
+
* Live composited frames per picture: the one on screen, the newest, one in flight. Measured bound (2026-11-11):
|
|
67
|
+
* phone case, 31 pictures: at 1200 px ~38 KB a frame -> <= 3.5 MB held on a phone; at 3000 px ~115 KB -> <= 10.7 MB.
|
|
68
|
+
*/
|
|
69
|
+
const MAX_FRAMES_PER_PICTURE = 3;
|
|
70
|
+
|
|
65
71
|
/** How long a frame whose blob: URL was revoked waits for its newer frame before counting as a real failure. */
|
|
66
72
|
const FRAME_SUPERSEDE_GRACE_MS = 2000;
|
|
73
|
+
/** The box accepts one `rerender` per this many ms (rc#840; more are refused with E_RERENDER_RATE_LIMITED). */
|
|
74
|
+
const RERENDER_MIN_INTERVAL_MS = 550;
|
|
67
75
|
|
|
68
76
|
/** `current` in order, then any of `extra` not already in it. */
|
|
69
77
|
function mergeMockupIds(current: readonly string[], extra: readonly string[]): string[] {
|
|
@@ -299,6 +307,9 @@ export interface RealtimeContextValue {
|
|
|
299
307
|
* @returns The blob URL (created or passed through)
|
|
300
308
|
*/
|
|
301
309
|
registerBlobUrl: (blobOrUrl: Blob | string, placementName?: string) => string;
|
|
310
|
+
|
|
311
|
+
/** A picture's <img> loaded `url` (from getMockupUrl): its older composited frames are released. */
|
|
312
|
+
markBlobShown: (mockupId: string, url: string) => void;
|
|
302
313
|
}
|
|
303
314
|
|
|
304
315
|
const RealtimeContext = createContext<RealtimeContextValue | undefined>(
|
|
@@ -568,6 +579,9 @@ export function RealtimeProvider({
|
|
|
568
579
|
// Track all registered blob URLs for memory management
|
|
569
580
|
// Uses insertion order to determine oldest URL for eviction
|
|
570
581
|
const registeredBlobUrlsRef = useRef<Set<string>>(new Set());
|
|
582
|
+
// Composited frames per picture (newest first), and the one its <img> shows: revoked only when that picture moves on.
|
|
583
|
+
const blobsByOwnerRef = useRef<Map<string, string[]>>(new Map());
|
|
584
|
+
const shownBlobByOwnerRef = useRef<Map<string, string>>(new Map());
|
|
571
585
|
|
|
572
586
|
// Track which placements have pending exports (for shimmer state)
|
|
573
587
|
const pendingPlacementsRef = useRef<Set<string>>(new Set());
|
|
@@ -617,6 +631,10 @@ export function RealtimeProvider({
|
|
|
617
631
|
// Mockups a `rerender` was sent for, until it is answered or refused.
|
|
618
632
|
const pendingRerenderRef = useRef<string[]>([]);
|
|
619
633
|
const forceRerenderByConfigRef = useRef<((failed: string[]) => void) | null>(null);
|
|
634
|
+
// Pacing of `rerender` requests (the box allows one per 500 ms).
|
|
635
|
+
const lastRerenderAtRef = useRef(0);
|
|
636
|
+
const rerenderQueueRef = useRef<string[]>([]);
|
|
637
|
+
const rerenderTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
620
638
|
// Cropped frames that could not be shown, waiting for one batched
|
|
621
639
|
// full-frame re-render (see rerenderFullFrame).
|
|
622
640
|
const fullFrameRerenderIdsRef = useRef<Set<string>>(new Set());
|
|
@@ -631,39 +649,65 @@ export function RealtimeProvider({
|
|
|
631
649
|
/**
|
|
632
650
|
* Register a blob URL with lifecycle management
|
|
633
651
|
*/
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
if (
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
URL.revokeObjectURL(oldest);
|
|
644
|
-
registeredBlobUrlsRef.current.delete(oldest);
|
|
645
|
-
|
|
646
|
-
// Also remove from URL cache and the results snapshot if present, so
|
|
647
|
-
// late subscribers are never replayed a revoked blob URL.
|
|
648
|
-
mockupUrlCacheRef.current.forEach((value, key) => {
|
|
649
|
-
if (value.url === oldest) {
|
|
650
|
-
mockupUrlCacheRef.current.delete(key);
|
|
651
|
-
}
|
|
652
|
-
});
|
|
653
|
-
mockupResultsRef.current = mockupResultsRef.current.filter(
|
|
654
|
-
(r) => r.imageUrl !== oldest
|
|
655
|
-
);
|
|
656
|
-
}
|
|
657
|
-
}
|
|
652
|
+
/** Revoke one blob URL and forget it everywhere a late subscriber could be replayed it. */
|
|
653
|
+
const revokeBlobUrl = useCallback((url: string) => {
|
|
654
|
+
URL.revokeObjectURL(url);
|
|
655
|
+
registeredBlobUrlsRef.current.delete(url);
|
|
656
|
+
mockupUrlCacheRef.current.forEach((value, key) => {
|
|
657
|
+
if (value.url === url) mockupUrlCacheRef.current.delete(key);
|
|
658
|
+
});
|
|
659
|
+
mockupResultsRef.current = mockupResultsRef.current.filter((r) => r.imageUrl !== url);
|
|
660
|
+
}, []);
|
|
658
661
|
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
662
|
+
/**
|
|
663
|
+
* Register a blob URL with lifecycle management.
|
|
664
|
+
*
|
|
665
|
+
* With an `owner` (a mockup id: the composited frames), a picture's frames are
|
|
666
|
+
* revoked only when that SAME picture has shown a newer one (`markBlobShown`,
|
|
667
|
+
* from its <img> load). A global "keep the newest 5" revoked other pictures'
|
|
668
|
+
* fresh frames before their <img> loaded them (31 composites per edit on the
|
|
669
|
+
* phone case): the picture kept its old image while its stamp said current
|
|
670
|
+
* (prod desktop, 2026-11-11: 15 ERR_FILE_NOT_FOUND per edit). Bound: at most
|
|
671
|
+
* MAX_FRAMES_PER_PICTURE live frames per picture (shown + newest + one in
|
|
672
|
+
* flight); a picture that exceeds it is a typed error and loses its OLDEST,
|
|
673
|
+
* never-shown frame — never the one on screen. Unowned blobs keep the old cap.
|
|
674
|
+
*/
|
|
675
|
+
const registerBlobUrl = useCallback((blobOrUrl: Blob | string, _placementName?: string, owner?: string): string => {
|
|
676
|
+
if (!(blobOrUrl instanceof Blob)) return blobOrUrl;
|
|
677
|
+
const url = URL.createObjectURL(blobOrUrl);
|
|
678
|
+
if (owner) {
|
|
679
|
+
const list = [url, ...(blobsByOwnerRef.current.get(owner) ?? [])]; // newest first
|
|
680
|
+
const shown = shownBlobByOwnerRef.current.get(owner);
|
|
681
|
+
while (list.length > MAX_FRAMES_PER_PICTURE) {
|
|
682
|
+
const victimIdx = [...list.keys()].reverse().find((i) => i > 0 && list[i] !== shown);
|
|
683
|
+
if (victimIdx === undefined) break;
|
|
684
|
+
const [victim] = list.splice(victimIdx, 1);
|
|
685
|
+
console.error(
|
|
686
|
+
`[RealtimeProvider] E_BLOB_PICTURE_BOUND: ${owner} has more than ${MAX_FRAMES_PER_PICTURE} frames waiting to be shown; dropping its oldest unshown frame (the picture on screen is kept).`
|
|
687
|
+
);
|
|
688
|
+
revokeBlobUrl(victim);
|
|
689
|
+
}
|
|
690
|
+
blobsByOwnerRef.current.set(owner, list);
|
|
691
|
+
return url;
|
|
663
692
|
}
|
|
664
|
-
|
|
693
|
+
if (registeredBlobUrlsRef.current.size >= MAX_CONCURRENT_BLOBS) {
|
|
694
|
+
const oldest = registeredBlobUrlsRef.current.values().next().value;
|
|
695
|
+
if (oldest) revokeBlobUrl(oldest);
|
|
696
|
+
}
|
|
697
|
+
registeredBlobUrlsRef.current.add(url);
|
|
665
698
|
return url;
|
|
666
|
-
}, []);
|
|
699
|
+
}, [revokeBlobUrl]);
|
|
700
|
+
|
|
701
|
+
/** A picture's <img> has loaded `url`: its older composited frames can go. */
|
|
702
|
+
const markBlobShown = useCallback((owner: string, url: string) => {
|
|
703
|
+
const list = blobsByOwnerRef.current.get(owner);
|
|
704
|
+
if (!list) return;
|
|
705
|
+
const idx = list.indexOf(url);
|
|
706
|
+
if (idx < 0) return;
|
|
707
|
+
shownBlobByOwnerRef.current.set(owner, url);
|
|
708
|
+
list.slice(idx + 1).forEach(revokeBlobUrl);
|
|
709
|
+
blobsByOwnerRef.current.set(owner, list.slice(0, idx + 1));
|
|
710
|
+
}, [revokeBlobUrl]);
|
|
667
711
|
|
|
668
712
|
const croppedDeliveryEnabled = delivery !== "full-frame";
|
|
669
713
|
|
|
@@ -743,6 +787,35 @@ export function RealtimeProvider({
|
|
|
743
787
|
);
|
|
744
788
|
forceRerenderByConfigRef.current = forceRerenderByConfig;
|
|
745
789
|
|
|
790
|
+
/**
|
|
791
|
+
* Ask the box to re-render `ids`, never faster than it allows (one request
|
|
792
|
+
* per RERENDER_MIN_INTERVAL_MS; it refuses more with E_RERENDER_RATE_LIMITED,
|
|
793
|
+
* prod 2026-11-11). Requests inside the interval wait for the remainder and
|
|
794
|
+
* go out as ONE request with every picture that failed meanwhile.
|
|
795
|
+
*/
|
|
796
|
+
const sendRerenderPaced = useCallback(
|
|
797
|
+
(ids: string[]) => {
|
|
798
|
+
rerenderQueueRef.current = mergeMockupIds(rerenderQueueRef.current, ids);
|
|
799
|
+
if (rerenderTimerRef.current) return;
|
|
800
|
+
const wait = Math.max(0, lastRerenderAtRef.current + RERENDER_MIN_INTERVAL_MS - Date.now());
|
|
801
|
+
const flush = () => {
|
|
802
|
+
rerenderTimerRef.current = null;
|
|
803
|
+
const batch = rerenderQueueRef.current;
|
|
804
|
+
rerenderQueueRef.current = [];
|
|
805
|
+
if (batch.length === 0) return;
|
|
806
|
+
lastRerenderAtRef.current = Date.now();
|
|
807
|
+
pendingRerenderRef.current = mergeMockupIds(pendingRerenderRef.current, batch);
|
|
808
|
+
if (!rerenderRaw(batch)) {
|
|
809
|
+
pendingRerenderRef.current = [];
|
|
810
|
+
forceRerenderByConfigRef.current?.(batch);
|
|
811
|
+
}
|
|
812
|
+
};
|
|
813
|
+
if (wait === 0) flush();
|
|
814
|
+
else rerenderTimerRef.current = setTimeout(flush, wait);
|
|
815
|
+
},
|
|
816
|
+
[rerenderRaw]
|
|
817
|
+
);
|
|
818
|
+
|
|
746
819
|
const rerenderFullFrame = useCallback(
|
|
747
820
|
(mockupId: string) => {
|
|
748
821
|
fullFrameRerenderIdsRef.current.add(mockupId);
|
|
@@ -769,14 +842,13 @@ export function RealtimeProvider({
|
|
|
769
842
|
// for exactly the failed pictures. A refusal (E_RERENDER_*) falls
|
|
770
843
|
// back to the config way (see onError).
|
|
771
844
|
sendFullFrameConfig(ids);
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
pendingRerenderRef.current = [];
|
|
845
|
+
sendRerenderPaced(failed);
|
|
846
|
+
return;
|
|
775
847
|
}
|
|
776
848
|
forceRerenderByConfig(failed);
|
|
777
849
|
}, 0);
|
|
778
850
|
},
|
|
779
|
-
[sendFullFrameConfig, forceRerenderByConfig,
|
|
851
|
+
[sendFullFrameConfig, forceRerenderByConfig, sendRerenderPaced]
|
|
780
852
|
);
|
|
781
853
|
|
|
782
854
|
/** Flip to cropped delivery once every configured mockup has a frozen
|
|
@@ -930,7 +1002,7 @@ export function RealtimeProvider({
|
|
|
930
1002
|
});
|
|
931
1003
|
// Scene changed while compositing (variant/bg flip) — stale, drop.
|
|
932
1004
|
if (gen !== sceneGenRef.current) return;
|
|
933
|
-
deliverResults([{ ...result, imageUrl: registerBlobUrl(blob) }]);
|
|
1005
|
+
deliverResults([{ ...result, imageUrl: registerBlobUrl(blob, undefined, result.mockupId) }]);
|
|
934
1006
|
} catch (err) {
|
|
935
1007
|
// A newer frame for this mockup already arrived: the SDK revokes a
|
|
936
1008
|
// mockup's previous blob: frame the moment the next one lands, so a
|
|
@@ -1755,6 +1827,7 @@ export function RealtimeProvider({
|
|
|
1755
1827
|
getLatestSentVersions: getLatestSentVersionsStable,
|
|
1756
1828
|
isMockupLoading,
|
|
1757
1829
|
registerBlobUrl,
|
|
1830
|
+
markBlobShown,
|
|
1758
1831
|
// WebRTC streaming
|
|
1759
1832
|
subscribeRTCTiming,
|
|
1760
1833
|
}),
|
|
@@ -1788,6 +1861,7 @@ export function RealtimeProvider({
|
|
|
1788
1861
|
getLatestSentVersionsStable,
|
|
1789
1862
|
isMockupLoading,
|
|
1790
1863
|
registerBlobUrl,
|
|
1864
|
+
markBlobShown,
|
|
1791
1865
|
]
|
|
1792
1866
|
);
|
|
1793
1867
|
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cropped-frame delivery state machine (RealtimeProvider internals).
|
|
3
|
+
*
|
|
4
|
+
* The sdk hook and the composite engine are mocked; these tests pin the
|
|
5
|
+
* provider's money-path invariants:
|
|
6
|
+
* - the session flips to overlayCrop:'auto' only after EVERY configured
|
|
7
|
+
* mockup has a frozen full-frame background
|
|
8
|
+
* - cropped frames are composited and consumers only ever see full-frame
|
|
9
|
+
* URLs (blob: URLs from the composite)
|
|
10
|
+
* - any composite failure falls back to full-frame delivery for the session
|
|
11
|
+
* and re-renders the affected mockup so the edit isn't lost
|
|
12
|
+
* - priority requests for never-rendered mockups drop the session back to
|
|
13
|
+
* full-frame before rendering
|
|
14
|
+
*/
|
|
15
|
+
import { describe, expect, it, beforeEach, vi } from "vitest";
|
|
16
|
+
import React from "react";
|
|
17
|
+
import { render, waitFor, act } from "@testing-library/react";
|
|
18
|
+
import {
|
|
19
|
+
RealtimeProvider,
|
|
20
|
+
useRealtime,
|
|
21
|
+
type RealtimeContextValue,
|
|
22
|
+
} from "../RealtimeProvider";
|
|
23
|
+
|
|
24
|
+
const h = vi.hoisted(() => {
|
|
25
|
+
return {
|
|
26
|
+
state: {
|
|
27
|
+
results: [] as Array<Record<string, unknown>>,
|
|
28
|
+
},
|
|
29
|
+
sendConfig: vi.fn(),
|
|
30
|
+
updateMockupIds: vi.fn(),
|
|
31
|
+
compositeCroppedFrame: vi.fn(),
|
|
32
|
+
loadImageElement: vi.fn(),
|
|
33
|
+
// Stable identities across renders — the real hook returns stable
|
|
34
|
+
// callbacks; fresh fns per render would churn the provider's effects.
|
|
35
|
+
sendCanvasBlob: vi.fn(),
|
|
36
|
+
sendCanvasState: vi.fn(),
|
|
37
|
+
sendColorBlob: vi.fn(),
|
|
38
|
+
updatePlacementSettings: vi.fn(),
|
|
39
|
+
connect: vi.fn(),
|
|
40
|
+
disconnect: vi.fn(),
|
|
41
|
+
flushPendingBlobs: vi.fn(),
|
|
42
|
+
hasPendingBlobs: vi.fn(() => false),
|
|
43
|
+
getLastSentVersion: vi.fn(() => 0),
|
|
44
|
+
getLatestSentVersions: vi.fn(() => ({})),
|
|
45
|
+
rerender: vi.fn((_ids: string[]) => true),
|
|
46
|
+
opts: null as null | { onError?: (msg: string, detail: Record<string, unknown>) => void },
|
|
47
|
+
};
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
vi.mock("@snowcone-app/sdk/react", () => ({
|
|
51
|
+
useRealtimeMockup: (opts: unknown) => {
|
|
52
|
+
h.opts = opts as typeof h.opts;
|
|
53
|
+
return {
|
|
54
|
+
isConnected: true,
|
|
55
|
+
isConfigured: true,
|
|
56
|
+
renderError: null,
|
|
57
|
+
mockupResults: h.state.results,
|
|
58
|
+
sendCanvasBlob: h.sendCanvasBlob,
|
|
59
|
+
sendCanvasState: h.sendCanvasState,
|
|
60
|
+
sendColorBlob: h.sendColorBlob,
|
|
61
|
+
sendConfig: h.sendConfig,
|
|
62
|
+
updateMockupIds: h.updateMockupIds,
|
|
63
|
+
updatePlacementSettings: h.updatePlacementSettings,
|
|
64
|
+
connect: h.connect,
|
|
65
|
+
disconnect: h.disconnect,
|
|
66
|
+
flushPendingBlobs: h.flushPendingBlobs,
|
|
67
|
+
hasPendingBlobs: h.hasPendingBlobs,
|
|
68
|
+
getLastSentVersion: h.getLastSentVersion,
|
|
69
|
+
getLatestSentVersions: h.getLatestSentVersions,
|
|
70
|
+
rerender: h.rerender,
|
|
71
|
+
};
|
|
72
|
+
},
|
|
73
|
+
}));
|
|
74
|
+
|
|
75
|
+
vi.mock("@snowcone-app/sdk", () => ({
|
|
76
|
+
resolveVariantId: () => "gv1",
|
|
77
|
+
resolvePreviewVariantId: (_context: unknown, variantId: string) => variantId,
|
|
78
|
+
}));
|
|
79
|
+
|
|
80
|
+
vi.mock("../Product", () => {
|
|
81
|
+
const product = {
|
|
82
|
+
id: "prod1",
|
|
83
|
+
placements: [{ label: "Front", type: "image" }],
|
|
84
|
+
mockups: Array.from({ length: 31 }, (_, i) => ({ id: `m${i}` })),
|
|
85
|
+
};
|
|
86
|
+
return {
|
|
87
|
+
useProductOptional: () => ({ product, selection: {} }),
|
|
88
|
+
};
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
vi.mock("../MockupBackground", () => ({
|
|
92
|
+
useMockupBackgroundOptional: () => undefined,
|
|
93
|
+
}));
|
|
94
|
+
|
|
95
|
+
vi.mock("../croppedFrameComposite", async (importOriginal) => {
|
|
96
|
+
const actual = await importOriginal<typeof import("../croppedFrameComposite")>();
|
|
97
|
+
return {
|
|
98
|
+
...actual,
|
|
99
|
+
compositeCroppedFrame: h.compositeCroppedFrame,
|
|
100
|
+
loadImageElement: h.loadImageElement,
|
|
101
|
+
};
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
let capturedCtx: RealtimeContextValue;
|
|
105
|
+
function Capture() {
|
|
106
|
+
capturedCtx = useRealtime();
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function Harness({ version }: { version: number }) {
|
|
111
|
+
void version; // re-render trigger — the mocked hook returns h.state.results
|
|
112
|
+
return (
|
|
113
|
+
<RealtimeProvider autoEnable>
|
|
114
|
+
<Capture />
|
|
115
|
+
</RealtimeProvider>
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function fullResult(mockupId: string, url: string) {
|
|
120
|
+
return { mockupId, imageUrl: url, renderUrl: url, imageSize: 1000, placement: "Front" };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function croppedResult(mockupId: string, url: string) {
|
|
124
|
+
return {
|
|
125
|
+
...fullResult(mockupId, url),
|
|
126
|
+
cropRect: { x: 0.2, y: 0.1, w: 0.5, h: 0.6 },
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** sendConfig payloads observed since the last mock reset. */
|
|
131
|
+
function sentConfigs(): Array<Record<string, unknown>> {
|
|
132
|
+
return h.sendConfig.mock.calls.map((c) => c[0] as Record<string, unknown>);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
let blobCounter = 0;
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* The box's rule (rendercenter realtime.ts renderFingerprint): a config
|
|
139
|
+
* re-renders only when its render fingerprint changes — overlayCrop is NOT in
|
|
140
|
+
* it and mockupIds are SORTED. Returns the mockup sets the box re-renders for
|
|
141
|
+
* `configs`, given the set in force before them.
|
|
142
|
+
*/
|
|
143
|
+
function boxRerenders(before: string[], configs: Array<Record<string, unknown>>): string[][] {
|
|
144
|
+
const fp = (ids: unknown) => [...(ids as string[])].sort().join(",");
|
|
145
|
+
let prev = fp(before);
|
|
146
|
+
const out: string[][] = [];
|
|
147
|
+
for (const c of configs) {
|
|
148
|
+
if (fp(c.mockupIds) !== prev) out.push(c.mockupIds as string[]);
|
|
149
|
+
prev = fp(c.mockupIds);
|
|
150
|
+
}
|
|
151
|
+
return out;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
beforeEach(() => {
|
|
155
|
+
vi.clearAllMocks();
|
|
156
|
+
h.state.results = [];
|
|
157
|
+
blobCounter = 0;
|
|
158
|
+
h.loadImageElement.mockResolvedValue({ naturalWidth: 1400, naturalHeight: 782 });
|
|
159
|
+
h.compositeCroppedFrame.mockResolvedValue(new Blob(["x"], { type: "image/webp" }));
|
|
160
|
+
// jsdom has no createObjectURL
|
|
161
|
+
globalThis.URL.createObjectURL = vi.fn(() => `blob:composite-${++blobCounter}`);
|
|
162
|
+
globalThis.URL.revokeObjectURL = vi.fn();
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
async function seedAndFlip(rerender: (ui: React.ReactElement) => void) {
|
|
166
|
+
h.state.results = [fullResult("m1", "https://r/m1-full")];
|
|
167
|
+
await act(async () => rerender(<Harness version={2} />));
|
|
168
|
+
expect(sentConfigs().some((c) => c.overlayCrop)).toBe(false);
|
|
169
|
+
|
|
170
|
+
h.state.results = [
|
|
171
|
+
fullResult("m1", "https://r/m1-full"),
|
|
172
|
+
fullResult("m2", "https://r/m2-full"),
|
|
173
|
+
];
|
|
174
|
+
await act(async () => rerender(<Harness version={3} />));
|
|
175
|
+
await waitFor(() => {
|
|
176
|
+
expect(sentConfigs().some((c) => c.overlayCrop === "auto")).toBe(true);
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
const IDS = Array.from({ length: 31 }, (_, i) => `m${i}`);
|
|
182
|
+
|
|
183
|
+
describe("composited frames per picture (prod desktop 2026-11-11: 15 ERR_FILE_NOT_FOUND per edit)", () => {
|
|
184
|
+
it("31 pictures, one edit: no picture's NEW frame is revoked before that picture shows it; showing it releases its older frame", async () => {
|
|
185
|
+
const revoked: string[] = [];
|
|
186
|
+
globalThis.URL.revokeObjectURL = vi.fn((u: string) => { revoked.push(u); });
|
|
187
|
+
const { rerender } = render(<Harness version={1} />);
|
|
188
|
+
await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
|
|
189
|
+
h.state.results = IDS.map((id) => fullResult(id, `https://r/${id}-full`));
|
|
190
|
+
await act(async () => rerender(<Harness version={2} />));
|
|
191
|
+
await waitFor(() => expect(sentConfigs().some((c) => c.overlayCrop === "auto")).toBe(true));
|
|
192
|
+
|
|
193
|
+
// Edit 1: a cropped frame for every picture, composited into a blob each.
|
|
194
|
+
h.state.results = IDS.map((id) => croppedResult(id, `https://r/${id}-crop-1`));
|
|
195
|
+
await act(async () => rerender(<Harness version={3} />));
|
|
196
|
+
await waitFor(() => expect(h.compositeCroppedFrame).toHaveBeenCalledTimes(31));
|
|
197
|
+
await act(async () => { await new Promise((r) => setTimeout(r, 50)); });
|
|
198
|
+
const firstUrls = IDS.map((id) => capturedCtx.getMockupUrl(id));
|
|
199
|
+
expect(firstUrls.every((u) => u?.startsWith("blob:composite-"))).toBe(true);
|
|
200
|
+
// The bug: a global "keep 5" revoked 26 of these fresh frames before any <img> loaded them.
|
|
201
|
+
expect(revoked.filter((u) => firstUrls.includes(u))).toEqual([]);
|
|
202
|
+
|
|
203
|
+
// m0's <img> shows its frame; edit 2 arrives; m0 shows the new one -> its edit-1 frame goes, nobody else's.
|
|
204
|
+
capturedCtx.markBlobShown("m0", firstUrls[0]!);
|
|
205
|
+
h.state.results = IDS.map((id) => croppedResult(id, `https://r/${id}-crop-2`));
|
|
206
|
+
await act(async () => rerender(<Harness version={4} />));
|
|
207
|
+
await waitFor(() => expect(h.compositeCroppedFrame).toHaveBeenCalledTimes(62));
|
|
208
|
+
await act(async () => { await new Promise((r) => setTimeout(r, 50)); });
|
|
209
|
+
const second = capturedCtx.getMockupUrl("m0")!;
|
|
210
|
+
expect(revoked).toEqual([]);
|
|
211
|
+
capturedCtx.markBlobShown("m0", second);
|
|
212
|
+
expect(revoked).toEqual([firstUrls[0]]);
|
|
213
|
+
});
|
|
214
|
+
});
|
|
@@ -453,5 +453,29 @@ describe("RealtimeProvider cropped delivery", () => {
|
|
|
453
453
|
expect(sentConfigs().every((c) => c.overlayCrop === undefined)).toBe(true);
|
|
454
454
|
errSpy.mockRestore();
|
|
455
455
|
});
|
|
456
|
+
|
|
457
|
+
it("never asks the box to rerender faster than it allows: failures 100 ms apart become 2 requests >= 500 ms apart", async () => {
|
|
458
|
+
const { rerender } = render(<Harness version={1} />);
|
|
459
|
+
await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
|
|
460
|
+
const v = { versions: { Front: 1 } };
|
|
461
|
+
h.state.results = [{ ...fullResult("m1", "https://r/m1-full"), ...v }, { ...fullResult("m2", "https://r/m2-full"), ...v }];
|
|
462
|
+
await act(async () => rerender(<Harness version={2} />));
|
|
463
|
+
await waitFor(() => expect(sentConfigs().some((c) => c.overlayCrop === "auto")).toBe(true));
|
|
464
|
+
const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
|
|
465
|
+
h.compositeCroppedFrame.mockRejectedValue(new Error("E_OVERLAY_ENCODE_FAILED"));
|
|
466
|
+
const calls: number[] = [];
|
|
467
|
+
h.rerender.mockImplementation(() => { calls.push(Date.now()); return true; });
|
|
468
|
+
|
|
469
|
+
h.state.results = [croppedResult("m1", "https://r/m1-crop-a")];
|
|
470
|
+
await act(async () => rerender(<Harness version={3} />));
|
|
471
|
+
await act(async () => { await new Promise((r) => setTimeout(r, 100)); });
|
|
472
|
+
h.state.results = [croppedResult("m1", "https://r/m1-crop-a"), croppedResult("m2", "https://r/m2-crop-a")];
|
|
473
|
+
await act(async () => rerender(<Harness version={4} />));
|
|
474
|
+
await act(async () => { await new Promise((r) => setTimeout(r, 900)); });
|
|
475
|
+
|
|
476
|
+
expect(h.rerender.mock.calls.map((c) => c[0])).toEqual([["m1"], ["m2"]]);
|
|
477
|
+
expect(calls[1] - calls[0]).toBeGreaterThanOrEqual(500);
|
|
478
|
+
errSpy.mockRestore();
|
|
479
|
+
});
|
|
456
480
|
});
|
|
457
481
|
|