@snowcone-app/ui 0.9.8 → 0.10.1
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 +202 -15
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +49 -1
- package/dist/index.d.ts +49 -1
- package/dist/index.js +202 -15
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/composed/HeroProductImage.tsx +57 -1
- package/src/composed/carousels/MobileProductCarousel.tsx +3 -0
- package/src/patterns/RealtimeProvider.tsx +179 -11
- package/src/patterns/__tests__/RealtimeProvider.sessionShape.test.tsx +162 -0
- package/src/patterns/__tests__/sessionShape.test.ts +62 -0
- package/src/patterns/sessionShape.ts +82 -0
package/package.json
CHANGED
|
@@ -165,6 +165,14 @@ export interface HeroProductImageProps {
|
|
|
165
165
|
errorText?: string;
|
|
166
166
|
/** Label shown when the image fails to load with no stale image to keep. */
|
|
167
167
|
unavailableText?: string;
|
|
168
|
+
/**
|
|
169
|
+
* Opt this picture into the realtime viewport policy (sessionShape.ts): it
|
|
170
|
+
* reports whether it is in view (or a neighbour) and its displayed width,
|
|
171
|
+
* so an edit renders only the pictures a shopper can see, at the width the
|
|
172
|
+
* screen shows them. The phone carousel sets it; galleries that don't keep
|
|
173
|
+
* today's behaviour.
|
|
174
|
+
*/
|
|
175
|
+
viewportPolicy?: boolean;
|
|
168
176
|
}
|
|
169
177
|
|
|
170
178
|
/**
|
|
@@ -213,6 +221,7 @@ export const HeroProductImage = memo(function HeroProductImage({
|
|
|
213
221
|
emptyText = "No artwork",
|
|
214
222
|
errorText = "Error loading",
|
|
215
223
|
unavailableText = "Preview unavailable",
|
|
224
|
+
viewportPolicy = false,
|
|
216
225
|
}: HeroProductImageProps) {
|
|
217
226
|
// Context
|
|
218
227
|
const context = useProductOptional();
|
|
@@ -585,6 +594,7 @@ export const HeroProductImage = memo(function HeroProductImage({
|
|
|
585
594
|
const sessionErrorCodeRef = useRef<string | null>(null);
|
|
586
595
|
sessionErrorCodeRef.current = realtimeContext?.renderError?.code ?? null;
|
|
587
596
|
const getCanvasVersion = realtimeContext?.getCanvasVersion;
|
|
597
|
+
const getSessionShape = realtimeContext?.getSessionShape;
|
|
588
598
|
const applyRenderStamp = useCallback(() => {
|
|
589
599
|
const node = containerRef.current;
|
|
590
600
|
if (!node) return;
|
|
@@ -612,7 +622,17 @@ export const HeroProductImage = memo(function HeroProductImage({
|
|
|
612
622
|
node.dataset.renderState = refusalCodeRef.current || (behind && sessionErrorCodeRef.current)
|
|
613
623
|
? "refused"
|
|
614
624
|
: behind ? "stale" : "current";
|
|
615
|
-
|
|
625
|
+
// Resolution: the width the shown image really has vs the width the
|
|
626
|
+
// session wants now (an editing-width frame after Done is marked, not
|
|
627
|
+
// passed off as the hero).
|
|
628
|
+
const img = node.querySelector("img");
|
|
629
|
+
if (img?.naturalWidth) node.dataset.renderWidth = String(img.naturalWidth);
|
|
630
|
+
const shape = getSessionShape?.();
|
|
631
|
+
if (shape) {
|
|
632
|
+
node.dataset.wantedWidth = String(shape.width);
|
|
633
|
+
node.dataset.sessionPhase = shape.phase;
|
|
634
|
+
}
|
|
635
|
+
}, [getCanvasVersion, getLatestSentVersions, getSessionShape]);
|
|
616
636
|
const applyRenderStampRef = useRef(applyRenderStamp);
|
|
617
637
|
applyRenderStampRef.current = applyRenderStamp;
|
|
618
638
|
// Re-apply after every render (the root node can change; refusals are state).
|
|
@@ -648,6 +668,42 @@ export const HeroProductImage = memo(function HeroProductImage({
|
|
|
648
668
|
applyRenderStamp,
|
|
649
669
|
]);
|
|
650
670
|
|
|
671
|
+
// VIEWPORT POLICY: report in-set (in view or a neighbour one screen away
|
|
672
|
+
// sideways), on-screen, and the displayed width in device pixels.
|
|
673
|
+
const reportPictureView = realtimeContext?.reportPictureView;
|
|
674
|
+
useEffect(() => {
|
|
675
|
+
if (!viewportPolicy || !reportPictureView || !actualMockupId) return;
|
|
676
|
+
const node = containerRef.current;
|
|
677
|
+
if (!node || typeof IntersectionObserver === "undefined") return;
|
|
678
|
+
let inSet = false;
|
|
679
|
+
const key = `${actualMockupId}#${Math.random().toString(36).slice(2, 9)}`;
|
|
680
|
+
const report = () => {
|
|
681
|
+
const r = node.getBoundingClientRect();
|
|
682
|
+
const onScreen = r.width > 0 && r.right > 0 && r.left < window.innerWidth && r.bottom > 0 && r.top < window.innerHeight;
|
|
683
|
+
reportPictureView(key, {
|
|
684
|
+
mockupId: actualMockupId,
|
|
685
|
+
inSet: inSet || onScreen,
|
|
686
|
+
onScreen,
|
|
687
|
+
devicePx: Math.round(r.width * (window.devicePixelRatio || 1)),
|
|
688
|
+
});
|
|
689
|
+
};
|
|
690
|
+
const io = new IntersectionObserver(
|
|
691
|
+
(entries) => {
|
|
692
|
+
inSet = entries.some((e) => e.isIntersecting);
|
|
693
|
+
report();
|
|
694
|
+
},
|
|
695
|
+
{ rootMargin: "0px 100% 0px 100%" }
|
|
696
|
+
);
|
|
697
|
+
io.observe(node);
|
|
698
|
+
const onResize = () => report();
|
|
699
|
+
window.addEventListener("resize", onResize);
|
|
700
|
+
return () => {
|
|
701
|
+
io.disconnect();
|
|
702
|
+
window.removeEventListener("resize", onResize);
|
|
703
|
+
reportPictureView(key, null);
|
|
704
|
+
};
|
|
705
|
+
}, [viewportPolicy, reportPictureView, actualMockupId]);
|
|
706
|
+
|
|
651
707
|
// Register with priority context
|
|
652
708
|
useEffect(() => {
|
|
653
709
|
if (!priorityContext || !actualMockupId || !placement) return;
|
|
@@ -917,6 +917,9 @@ export const MobileProductCarousel = memo(function MobileProductCarousel({
|
|
|
917
917
|
errorText={errorText}
|
|
918
918
|
unavailableText={unavailableText}
|
|
919
919
|
className="w-full h-full object-cover cursor-pointer pointer-events-none"
|
|
920
|
+
// Edits render only the slides a shopper can see, at the
|
|
921
|
+
// width the screen shows them (sessionShape.ts).
|
|
922
|
+
viewportPolicy
|
|
920
923
|
/>
|
|
921
924
|
) : image.isRealMockup && !currentArtwork ? (
|
|
922
925
|
<LoadingOverlayPrismCandyInline visible variant="light" />
|
|
@@ -46,6 +46,7 @@ import { readEnv } from "../lib/env";
|
|
|
46
46
|
import { useProductOptional } from "./Product";
|
|
47
47
|
import type { ReactProductContext } from "./Product";
|
|
48
48
|
import { useMockupBackgroundOptional } from "./MockupBackground";
|
|
49
|
+
import { sameShape, sessionShape, type PictureView, type SessionShape } from "./sessionShape";
|
|
49
50
|
import {
|
|
50
51
|
allBackgroundsSeeded,
|
|
51
52
|
compositeCroppedFrame,
|
|
@@ -72,6 +73,10 @@ const MAX_FRAMES_PER_PICTURE = 3;
|
|
|
72
73
|
const FRAME_SUPERSEDE_GRACE_MS = 2000;
|
|
73
74
|
/** The box accepts one `rerender` per this many ms (rc#840; more are refused with E_RERENDER_RATE_LIMITED). */
|
|
74
75
|
const RERENDER_MIN_INTERVAL_MS = 550;
|
|
76
|
+
/** Quiet time after the pipeline settles before an edit counts as stopped (the catch-up renders every picture). */
|
|
77
|
+
const EDIT_QUIET_MS = 600;
|
|
78
|
+
/** An announced export that has not gone out after this long is lost: it stops holding the edit open. */
|
|
79
|
+
const EXPORT_PENDING_MAX_MS = 5000;
|
|
75
80
|
|
|
76
81
|
/** `current` in order, then any of `extra` not already in it. */
|
|
77
82
|
function mergeMockupIds(current: readonly string[], extra: readonly string[]): string[] {
|
|
@@ -262,6 +267,20 @@ export interface RealtimeContextValue {
|
|
|
262
267
|
*/
|
|
263
268
|
getLatestSentVersions: () => Record<string, number>;
|
|
264
269
|
|
|
270
|
+
/**
|
|
271
|
+
* Viewport policy (sessionShape.ts): a gallery picture reports whether it is
|
|
272
|
+
* in the edit set (in view or a neighbour), on screen, and its displayed
|
|
273
|
+
* width in device pixels; `null` when it unmounts. Only a gallery that opts
|
|
274
|
+
* in reports (the phone carousel); without reports nothing changes.
|
|
275
|
+
*/
|
|
276
|
+
reportPictureView: (elementKey: string, view: PictureView | null) => void;
|
|
277
|
+
|
|
278
|
+
/** The shape the session renders now: its phase and width (for data attributes and checks). */
|
|
279
|
+
getSessionShape: () => { phase: SessionShape["phase"]; width: number } | null;
|
|
280
|
+
|
|
281
|
+
/** The design editor opened or closed (Done). Drives the viewport policy's phase; see `editorOpen`. */
|
|
282
|
+
setEditorOpen: (open: boolean) => void;
|
|
283
|
+
|
|
265
284
|
// Flush pending blobs immediately (call on mouse up, action complete, etc.)
|
|
266
285
|
flushPendingBlobs: () => void;
|
|
267
286
|
hasPendingBlobs: () => boolean;
|
|
@@ -354,6 +373,15 @@ export interface RealtimeProviderProps {
|
|
|
354
373
|
* the rest of the session automatically.
|
|
355
374
|
*/
|
|
356
375
|
delivery?: "cropped" | "full-frame";
|
|
376
|
+
/**
|
|
377
|
+
* Whether the design editor is open. With a gallery that opted into the
|
|
378
|
+
* viewport policy (`reportPictureView`, the phone carousel), an open editor
|
|
379
|
+
* renders the pictures in view at the width the screen shows them while an
|
|
380
|
+
* edit is live, and every picture at that width when it stops; closing it
|
|
381
|
+
* (Done) renders the picture on screen at `mockupWidth` (see sessionShape.ts).
|
|
382
|
+
* Without such a gallery it changes nothing. Default true.
|
|
383
|
+
*/
|
|
384
|
+
editorOpen?: boolean;
|
|
357
385
|
}
|
|
358
386
|
|
|
359
387
|
/**
|
|
@@ -372,6 +400,7 @@ export function RealtimeProvider({
|
|
|
372
400
|
grantUrl,
|
|
373
401
|
initialGrant,
|
|
374
402
|
delivery = "cropped",
|
|
403
|
+
editorOpen = true,
|
|
375
404
|
}: RealtimeProviderProps) {
|
|
376
405
|
const productContext = useProductOptional();
|
|
377
406
|
// Page background for renders (see MockupBackground) — sent on the config so
|
|
@@ -633,6 +662,27 @@ export function RealtimeProvider({
|
|
|
633
662
|
// config's set, or the last updateMockupIds set. A full-frame fallback
|
|
634
663
|
// re-sends this set (plus the failed mockups) — it must never shrink it.
|
|
635
664
|
const requestedMockupIdsRef = useRef<string[]>([]);
|
|
665
|
+
// VIEWPORT POLICY (sessionShape.ts): the pictures that opted in, whether an
|
|
666
|
+
// edit is live, and the shape last sent. ONE config per change of shape.
|
|
667
|
+
const pictureViewsRef = useRef<Map<string, PictureView>>(new Map());
|
|
668
|
+
const editLiveRef = useRef(false);
|
|
669
|
+
const editQuietTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
670
|
+
// An export announced (notifyPendingExport) but not sent yet: when it started, or 0. While it is pending, the edit is
|
|
671
|
+
// still going, whatever older version settles meanwhile (slow phone link, 2026-11-11: the editor-open frames were
|
|
672
|
+
// still landing when the drag began; their settle + 600 ms quiet fired a 31-picture catch-up mid-gesture, and the
|
|
673
|
+
// edit's own frames queued behind it for 21 s). Older than EXPORT_PENDING_MAX_MS = lost: it no longer holds the edit.
|
|
674
|
+
const exportPendingSinceRef = useRef(0);
|
|
675
|
+
const shapeApplyTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
676
|
+
const lastShapeRef = useRef<SessionShape | null>(null);
|
|
677
|
+
const applySessionShapeRef = useRef<(() => void) | null>(null);
|
|
678
|
+
// Initial value from the prop; pages whose editor state lives below the
|
|
679
|
+
// provider drive it with setEditorOpen().
|
|
680
|
+
const [editorOpenState, setEditorOpenState] = useState(editorOpen);
|
|
681
|
+
useEffect(() => setEditorOpenState(editorOpen), [editorOpen]);
|
|
682
|
+
const editorOpenRef = useRef(editorOpenState);
|
|
683
|
+
editorOpenRef.current = editorOpenState;
|
|
684
|
+
const heroWidthRef = useRef(mockupWidth);
|
|
685
|
+
heroWidthRef.current = mockupWidth;
|
|
636
686
|
// True once a frame carries per-placement `versions`: the box then also
|
|
637
687
|
// understands `rerender` (rendercenter rc#839 + rc#840, one roll).
|
|
638
688
|
const serverStampsVersionsRef = useRef(false);
|
|
@@ -910,6 +960,79 @@ export function RealtimeProvider({
|
|
|
910
960
|
croppedActiveRef.current = false;
|
|
911
961
|
}, []);
|
|
912
962
|
|
|
963
|
+
const currentShape = useCallback(
|
|
964
|
+
() =>
|
|
965
|
+
sessionShape({
|
|
966
|
+
allMockupIds: configuredMockupIdsRef.current,
|
|
967
|
+
views: pictureViewsRef.current,
|
|
968
|
+
heroWidth: heroWidthRef.current,
|
|
969
|
+
editorOpen: editorOpenRef.current,
|
|
970
|
+
editLive: editLiveRef.current,
|
|
971
|
+
}),
|
|
972
|
+
[]
|
|
973
|
+
);
|
|
974
|
+
|
|
975
|
+
/**
|
|
976
|
+
* Send ONE config when the session's shape (which pictures, what width)
|
|
977
|
+
* changed. The server renders the last config's set at its width, so this
|
|
978
|
+
* is the only place the set or the width changes mid-session. A width
|
|
979
|
+
* change re-seeds the cropped-delivery backgrounds (they are the old size).
|
|
980
|
+
*/
|
|
981
|
+
const applySessionShape = useCallback(() => {
|
|
982
|
+
const base = lastConfigBaseRef.current;
|
|
983
|
+
if (!base || !configSentRef.current) return;
|
|
984
|
+
const shape = currentShape();
|
|
985
|
+
if (sameShape(lastShapeRef.current, shape)) {
|
|
986
|
+
lastShapeRef.current = shape; // phase may differ with the same request
|
|
987
|
+
return;
|
|
988
|
+
}
|
|
989
|
+
if (lastShapeRef.current && lastShapeRef.current.width !== shape.width) invalidateBackgrounds();
|
|
990
|
+
lastShapeRef.current = shape;
|
|
991
|
+
base.mockupIds = shape.mockupIds;
|
|
992
|
+
base.width = shape.width;
|
|
993
|
+
requestedMockupIdsRef.current = [...shape.mockupIds];
|
|
994
|
+
sendConfigRaw({
|
|
995
|
+
...base,
|
|
996
|
+
placementSettings: { ...placementSettingsOverridesRef.current },
|
|
997
|
+
...(croppedActiveRef.current ? { overlayCrop: "auto" as const } : {}),
|
|
998
|
+
} as Parameters<typeof sendConfigRaw>[0]);
|
|
999
|
+
}, [currentShape, invalidateBackgrounds, sendConfigRaw]);
|
|
1000
|
+
applySessionShapeRef.current = applySessionShape;
|
|
1001
|
+
|
|
1002
|
+
/** An edit went out: render the set in view until it stops; cancels a catch-up in flight. */
|
|
1003
|
+
const markEditLive = useCallback(() => {
|
|
1004
|
+
if (editQuietTimerRef.current) {
|
|
1005
|
+
clearTimeout(editQuietTimerRef.current);
|
|
1006
|
+
editQuietTimerRef.current = null;
|
|
1007
|
+
}
|
|
1008
|
+
if (editLiveRef.current) return;
|
|
1009
|
+
editLiveRef.current = true;
|
|
1010
|
+
applySessionShapeRef.current?.();
|
|
1011
|
+
}, []);
|
|
1012
|
+
|
|
1013
|
+
/** The pipeline settled: after EDIT_QUIET_MS with no new edit, catch every picture up. */
|
|
1014
|
+
const markEditSettled = useCallback(() => {
|
|
1015
|
+
if (!editLiveRef.current) return;
|
|
1016
|
+
if (editQuietTimerRef.current) clearTimeout(editQuietTimerRef.current);
|
|
1017
|
+
editQuietTimerRef.current = setTimeout(() => {
|
|
1018
|
+
editQuietTimerRef.current = null;
|
|
1019
|
+
editLiveRef.current = false;
|
|
1020
|
+
applySessionShapeRef.current?.();
|
|
1021
|
+
}, EDIT_QUIET_MS);
|
|
1022
|
+
}, []);
|
|
1023
|
+
|
|
1024
|
+
useEffect(() => {
|
|
1025
|
+
applySessionShapeRef.current?.();
|
|
1026
|
+
}, [editorOpenState]);
|
|
1027
|
+
|
|
1028
|
+
useEffect(
|
|
1029
|
+
() => () => {
|
|
1030
|
+
if (editQuietTimerRef.current) clearTimeout(editQuietTimerRef.current);
|
|
1031
|
+
if (shapeApplyTimerRef.current) clearTimeout(shapeApplyTimerRef.current);
|
|
1032
|
+
},
|
|
1033
|
+
[]
|
|
1034
|
+
);
|
|
1035
|
+
|
|
913
1036
|
/**
|
|
914
1037
|
* Deliver displayable (always full-frame) results: update the snapshot and
|
|
915
1038
|
* URL cache, clear pending state, notify subscribers, check settle.
|
|
@@ -974,6 +1097,7 @@ export function RealtimeProvider({
|
|
|
974
1097
|
// frames never all arrive (a failed mockup) is forgotten after 10 s so
|
|
975
1098
|
// it cannot wedge the policy. Blob sends keep the throttle-queue rule.
|
|
976
1099
|
let settledVersions = 0;
|
|
1100
|
+
let newestSettled = 0;
|
|
977
1101
|
const due = dueByVersionRef.current;
|
|
978
1102
|
results.forEach((result) => {
|
|
979
1103
|
const v = result.requestVersion;
|
|
@@ -983,6 +1107,7 @@ export function RealtimeProvider({
|
|
|
983
1107
|
if (entry.due <= 1) {
|
|
984
1108
|
due.delete(v);
|
|
985
1109
|
settledVersions += 1;
|
|
1110
|
+
newestSettled = Math.max(newestSettled, v);
|
|
986
1111
|
} else {
|
|
987
1112
|
entry.due -= 1;
|
|
988
1113
|
}
|
|
@@ -994,13 +1119,19 @@ export function RealtimeProvider({
|
|
|
994
1119
|
if (!pipelineResetCooldownRef.current) {
|
|
995
1120
|
hasBlobInFlightRef.current = false;
|
|
996
1121
|
for (let i = 0; i < settledVersions; i++) pipelineSettledSubscribersRef.current.forEach((cb) => cb());
|
|
1122
|
+
// The EDIT settles only when its newest version has landed and no further export is on its way: an older
|
|
1123
|
+
// version (the editor-open frames on a slow link) settling mid-gesture is not the edit stopping.
|
|
1124
|
+
const exportPending =
|
|
1125
|
+
exportPendingSinceRef.current > 0 && Date.now() - exportPendingSinceRef.current < EXPORT_PENDING_MAX_MS;
|
|
1126
|
+
if (!exportPending && newestSettled >= getLastSentVersion()) markEditSettled();
|
|
997
1127
|
}
|
|
998
1128
|
} else if (due.size === 0 && hasBlobInFlightRef.current && !hasPendingBlobs() && !pipelineResetCooldownRef.current) {
|
|
999
1129
|
hasBlobInFlightRef.current = false;
|
|
1000
1130
|
pipelineSettledSubscribersRef.current.forEach((cb) => cb());
|
|
1131
|
+
if (!(exportPendingSinceRef.current > 0 && Date.now() - exportPendingSinceRef.current < EXPORT_PENDING_MAX_MS)) markEditSettled();
|
|
1001
1132
|
}
|
|
1002
1133
|
},
|
|
1003
|
-
[hasPendingBlobs]
|
|
1134
|
+
[hasPendingBlobs, markEditSettled, getLastSentVersion]
|
|
1004
1135
|
);
|
|
1005
1136
|
|
|
1006
1137
|
/** Composite one cropped frame over its frozen background and deliver it. */
|
|
@@ -1188,6 +1319,7 @@ export function RealtimeProvider({
|
|
|
1188
1319
|
baseThrottleMs?: number
|
|
1189
1320
|
) => {
|
|
1190
1321
|
blobQueuedGenRef.current = pipelineGenRef.current;
|
|
1322
|
+
exportPendingSinceRef.current = 0;
|
|
1191
1323
|
const result = sendCanvasBlobRaw(
|
|
1192
1324
|
placement,
|
|
1193
1325
|
blob,
|
|
@@ -1200,10 +1332,11 @@ export function RealtimeProvider({
|
|
|
1200
1332
|
isPendingMockupsRef.current = true;
|
|
1201
1333
|
// Notify pending blob subscribers (for shimmer effects)
|
|
1202
1334
|
pendingBlobSubscribersRef.current.forEach((cb) => cb(placement));
|
|
1335
|
+
markEditLive();
|
|
1203
1336
|
}
|
|
1204
1337
|
return result;
|
|
1205
1338
|
},
|
|
1206
|
-
[sendCanvasBlobRaw]
|
|
1339
|
+
[sendCanvasBlobRaw, markEditLive]
|
|
1207
1340
|
);
|
|
1208
1341
|
|
|
1209
1342
|
// Wrap sendCanvasState for JSON mode (server-side canvas rendering)
|
|
@@ -1215,6 +1348,7 @@ export function RealtimeProvider({
|
|
|
1215
1348
|
baseThrottleMs?: number
|
|
1216
1349
|
) => {
|
|
1217
1350
|
blobQueuedGenRef.current = pipelineGenRef.current;
|
|
1351
|
+
exportPendingSinceRef.current = 0;
|
|
1218
1352
|
const result = sendCanvasStateRaw(
|
|
1219
1353
|
placement,
|
|
1220
1354
|
state,
|
|
@@ -1229,15 +1363,18 @@ export function RealtimeProvider({
|
|
|
1229
1363
|
// count when it is smaller (a subset shown via updateMockupIds).
|
|
1230
1364
|
const version = getLastSentVersion();
|
|
1231
1365
|
if (version > 0) {
|
|
1232
|
-
|
|
1366
|
+
// Frames due = the set the session renders now (the viewport policy
|
|
1367
|
+
// narrows it while an edit is live), not every configured picture.
|
|
1368
|
+
const configured = requestedMockupIdsRef.current.length || configuredMockupIdsRef.current.length;
|
|
1233
1369
|
const expected = Math.max(1, Math.min(configured || Infinity, mockupCount || Infinity));
|
|
1234
1370
|
dueByVersionRef.current.set(version, { due: Number.isFinite(expected) ? expected : 1, at: Date.now() });
|
|
1235
1371
|
}
|
|
1236
1372
|
pendingBlobSubscribersRef.current.forEach((cb) => cb(placement));
|
|
1373
|
+
markEditLive();
|
|
1237
1374
|
}
|
|
1238
1375
|
return result;
|
|
1239
1376
|
},
|
|
1240
|
-
[sendCanvasStateRaw, getLastSentVersion]
|
|
1377
|
+
[sendCanvasStateRaw, getLastSentVersion, markEditLive]
|
|
1241
1378
|
);
|
|
1242
1379
|
|
|
1243
1380
|
// Wrap sendColorBlob to track when colors are sent
|
|
@@ -1332,6 +1469,10 @@ export function RealtimeProvider({
|
|
|
1332
1469
|
});
|
|
1333
1470
|
}
|
|
1334
1471
|
configuredMockupIdsRef.current = mockupIds;
|
|
1472
|
+
// The viewport policy shapes even the first config (sessionShape.ts):
|
|
1473
|
+
// with no gallery opted in it is every picture at mockupWidth (today).
|
|
1474
|
+
const shape = currentShape();
|
|
1475
|
+
lastShapeRef.current = shape;
|
|
1335
1476
|
|
|
1336
1477
|
// Authed sessions: the grant token (verified on connect) authorizes the
|
|
1337
1478
|
// session and the server self-signs the render, so no seal is sent and the
|
|
@@ -1340,21 +1481,21 @@ export function RealtimeProvider({
|
|
|
1340
1481
|
const configPayload = useSessionGrant
|
|
1341
1482
|
? {
|
|
1342
1483
|
productId,
|
|
1343
|
-
mockupIds,
|
|
1484
|
+
mockupIds: shape.mockupIds,
|
|
1344
1485
|
variantId,
|
|
1345
1486
|
shop: shop as string,
|
|
1346
|
-
width:
|
|
1487
|
+
width: shape.width,
|
|
1347
1488
|
...(mockupBg ? { bg: mockupBg } : {}),
|
|
1348
1489
|
...(spreadCropsRef.current ? { spreadCrops: spreadCropsRef.current } : {}),
|
|
1349
1490
|
placementSettings: { ...placementSettingsOverridesRef.current },
|
|
1350
1491
|
}
|
|
1351
1492
|
: {
|
|
1352
1493
|
productId,
|
|
1353
|
-
mockupIds,
|
|
1494
|
+
mockupIds: shape.mockupIds,
|
|
1354
1495
|
variantId,
|
|
1355
1496
|
shop: "hTidnpNnNa",
|
|
1356
1497
|
seal: "bypass-sig-for-k6-load-test",
|
|
1357
|
-
width:
|
|
1498
|
+
width: shape.width,
|
|
1358
1499
|
...(mockupBg ? { bg: mockupBg } : {}),
|
|
1359
1500
|
...(spreadCropsRef.current ? { spreadCrops: spreadCropsRef.current } : {}),
|
|
1360
1501
|
placementSettings: { ...placementSettingsOverridesRef.current },
|
|
@@ -1373,7 +1514,7 @@ export function RealtimeProvider({
|
|
|
1373
1514
|
// send — preserving cropped delivery across re-sends that kept the scene
|
|
1374
1515
|
// (e.g. spread-crop changes).
|
|
1375
1516
|
lastConfigBaseRef.current = configPayload as unknown as Record<string, unknown>;
|
|
1376
|
-
requestedMockupIdsRef.current = mockupIds;
|
|
1517
|
+
requestedMockupIdsRef.current = [...shape.mockupIds];
|
|
1377
1518
|
sendConfigRaw(
|
|
1378
1519
|
(croppedActiveRef.current
|
|
1379
1520
|
? { ...configPayload, overlayCrop: "auto" as const }
|
|
@@ -1404,6 +1545,7 @@ export function RealtimeProvider({
|
|
|
1404
1545
|
sendConfigRaw,
|
|
1405
1546
|
sendColorBlobTracked,
|
|
1406
1547
|
invalidateBackgrounds,
|
|
1548
|
+
currentShape,
|
|
1407
1549
|
mockupWidth,
|
|
1408
1550
|
mockupBg,
|
|
1409
1551
|
spreadCropsVersion,
|
|
@@ -1638,6 +1780,7 @@ export function RealtimeProvider({
|
|
|
1638
1780
|
// This fires immediately when a change is detected, before the export completes
|
|
1639
1781
|
const notifyPendingExport = useCallback(
|
|
1640
1782
|
(placement: string) => {
|
|
1783
|
+
exportPendingSinceRef.current = Date.now();
|
|
1641
1784
|
// Skip if this placement is already pending — avoids spamming subscribers
|
|
1642
1785
|
// on every canvas change during drag
|
|
1643
1786
|
if (pendingPlacementsRef.current.has(placement)) {
|
|
@@ -1660,8 +1803,9 @@ export function RealtimeProvider({
|
|
|
1660
1803
|
console.log(`[RTP] notifyPendingExport("${placement}"): marked ${pendingIds.length} mockup(s) pending — [${pendingIds.slice(0, 5).join(', ')}${pendingIds.length > 5 ? '...' : ''}]`);
|
|
1661
1804
|
|
|
1662
1805
|
pendingBlobSubscribersRef.current.forEach((cb) => cb(placement));
|
|
1806
|
+
markEditLive();
|
|
1663
1807
|
},
|
|
1664
|
-
[productContext?.product?.mockups]
|
|
1808
|
+
[productContext?.product?.mockups, markEditLive]
|
|
1665
1809
|
);
|
|
1666
1810
|
|
|
1667
1811
|
// Roll back a previous notifyPendingExport when the actual export turned
|
|
@@ -1669,6 +1813,9 @@ export function RealtimeProvider({
|
|
|
1669
1813
|
// notifies cancellation subscribers so loading UI can be dismissed.
|
|
1670
1814
|
const notifyPendingExportCancelled = useCallback(
|
|
1671
1815
|
(placement: string) => {
|
|
1816
|
+
// The export turned out a no-op: it no longer holds the edit open; let it settle.
|
|
1817
|
+
exportPendingSinceRef.current = 0;
|
|
1818
|
+
markEditSettled();
|
|
1672
1819
|
// If we never marked this placement as pending, nothing to do.
|
|
1673
1820
|
if (!pendingPlacementsRef.current.has(placement)) {
|
|
1674
1821
|
return;
|
|
@@ -1693,7 +1840,7 @@ export function RealtimeProvider({
|
|
|
1693
1840
|
|
|
1694
1841
|
pendingExportCancelledSubscribersRef.current.forEach((cb) => cb(placement));
|
|
1695
1842
|
},
|
|
1696
|
-
[productContext?.product?.mockups]
|
|
1843
|
+
[productContext?.product?.mockups, markEditSettled]
|
|
1697
1844
|
);
|
|
1698
1845
|
|
|
1699
1846
|
// ============================================================================
|
|
@@ -1809,6 +1956,22 @@ export function RealtimeProvider({
|
|
|
1809
1956
|
getLatestSentVersionsRef.current = getLatestSentVersions;
|
|
1810
1957
|
const getLatestSentVersionsStable = useCallback(() => getLatestSentVersionsRef.current?.() ?? {}, []);
|
|
1811
1958
|
|
|
1959
|
+
const reportPictureView = useCallback((elementKey: string, view: PictureView | null) => {
|
|
1960
|
+
const views = pictureViewsRef.current;
|
|
1961
|
+
if (view) views.set(elementKey, view);
|
|
1962
|
+
else views.delete(elementKey);
|
|
1963
|
+
// Batch a swipe's / a scroll's reports into one shape check (one config).
|
|
1964
|
+
if (shapeApplyTimerRef.current) return;
|
|
1965
|
+
shapeApplyTimerRef.current = setTimeout(() => {
|
|
1966
|
+
shapeApplyTimerRef.current = null;
|
|
1967
|
+
applySessionShapeRef.current?.();
|
|
1968
|
+
}, 100);
|
|
1969
|
+
}, []);
|
|
1970
|
+
const getSessionShape = useCallback(() => {
|
|
1971
|
+
const s = lastShapeRef.current;
|
|
1972
|
+
return s ? { phase: s.phase, width: s.width } : null;
|
|
1973
|
+
}, []);
|
|
1974
|
+
|
|
1812
1975
|
const stableSubscribePipelineSettled = useCallback(
|
|
1813
1976
|
(callback: () => void) => {
|
|
1814
1977
|
return subscribePipelineSettledRef.current(callback);
|
|
@@ -1863,6 +2026,9 @@ export function RealtimeProvider({
|
|
|
1863
2026
|
getMockupUrls,
|
|
1864
2027
|
getCanvasVersion,
|
|
1865
2028
|
getLatestSentVersions: getLatestSentVersionsStable,
|
|
2029
|
+
reportPictureView,
|
|
2030
|
+
getSessionShape,
|
|
2031
|
+
setEditorOpen: setEditorOpenState,
|
|
1866
2032
|
isMockupLoading,
|
|
1867
2033
|
registerBlobUrl,
|
|
1868
2034
|
markBlobShown,
|
|
@@ -1898,6 +2064,8 @@ export function RealtimeProvider({
|
|
|
1898
2064
|
getMockupUrls,
|
|
1899
2065
|
getCanvasVersion,
|
|
1900
2066
|
getLatestSentVersionsStable,
|
|
2067
|
+
reportPictureView,
|
|
2068
|
+
getSessionShape,
|
|
1901
2069
|
isMockupLoading,
|
|
1902
2070
|
registerBlobUrl,
|
|
1903
2071
|
markBlobShown,
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The phone viewport policy end to end in the provider (lane-editor design, approved 2026-11-11). Conditions:
|
|
3
|
+
* 1. ONE config per change, holding the whole set wanted (the server keeps the last config).
|
|
4
|
+
* 3. The catch-up when the edit stops (every picture, editing width, one config) and its cancel by a new edit.
|
|
5
|
+
* 4. A swipe during an edit adds the new slide in one config.
|
|
6
|
+
* Done renders the slide on screen at hero width; desktop (no reports) sends exactly what it sends today.
|
|
7
|
+
*/
|
|
8
|
+
import { describe, expect, it, beforeEach, vi } from "vitest";
|
|
9
|
+
import React from "react";
|
|
10
|
+
import { render, waitFor, act, cleanup } from "@testing-library/react";
|
|
11
|
+
import { RealtimeProvider, useRealtime, type RealtimeContextValue } from "../RealtimeProvider";
|
|
12
|
+
|
|
13
|
+
const h = vi.hoisted(() => ({
|
|
14
|
+
state: { results: [] as Array<Record<string, unknown>> },
|
|
15
|
+
sendConfig: vi.fn(),
|
|
16
|
+
version: 0,
|
|
17
|
+
sendCanvasState: vi.fn(() => true),
|
|
18
|
+
stable: {
|
|
19
|
+
sendCanvasBlob: vi.fn(), sendColorBlob: vi.fn(), updateMockupIds: vi.fn(), updatePlacementSettings: vi.fn(),
|
|
20
|
+
connect: vi.fn(), disconnect: vi.fn(), flushPendingBlobs: vi.fn(), hasPendingBlobs: vi.fn(() => false),
|
|
21
|
+
getLatestSentVersions: vi.fn(() => ({})), rerender: vi.fn(() => true),
|
|
22
|
+
},
|
|
23
|
+
}));
|
|
24
|
+
|
|
25
|
+
vi.mock("@snowcone-app/sdk/react", () => ({
|
|
26
|
+
useRealtimeMockup: () => ({
|
|
27
|
+
isConnected: true, isConfigured: true, renderError: null, mockupResults: h.state.results,
|
|
28
|
+
sendConfig: h.sendConfig, sendCanvasState: h.sendCanvasState, getLastSentVersion: () => h.version, ...h.stable,
|
|
29
|
+
}),
|
|
30
|
+
}));
|
|
31
|
+
vi.mock("@snowcone-app/sdk", () => ({ resolveVariantId: () => "gv1", resolvePreviewVariantId: (_c: unknown, v: string) => v }));
|
|
32
|
+
const IDS = ["M0", "M1", "M2", "M3", "M4", "M5"];
|
|
33
|
+
vi.mock("../Product", () => {
|
|
34
|
+
const product = { id: "p1", placements: [{ label: "Front", type: "image" }], mockups: ["M0", "M1", "M2", "M3", "M4", "M5"].map((id) => ({ id })) };
|
|
35
|
+
return { useProductOptional: () => ({ product, selection: {} }) };
|
|
36
|
+
});
|
|
37
|
+
vi.mock("../MockupBackground", () => ({ useMockupBackgroundOptional: () => undefined }));
|
|
38
|
+
|
|
39
|
+
let ctx: RealtimeContextValue;
|
|
40
|
+
function Capture() { ctx = useRealtime(); return null; }
|
|
41
|
+
function Harness({ v, editorOpen }: { v: number; editorOpen?: boolean }) {
|
|
42
|
+
void v;
|
|
43
|
+
return <RealtimeProvider autoEnable delivery="full-frame" mockupWidth={3000} editorOpen={editorOpen}><Capture /></RealtimeProvider>;
|
|
44
|
+
}
|
|
45
|
+
const configs = () => h.sendConfig.mock.calls.map((c) => c[0] as { mockupIds: string[]; width: number });
|
|
46
|
+
const shapes = () => configs().map((c) => `${c.mockupIds.join(",")}@${c.width}`);
|
|
47
|
+
const wait = (ms: number) => act(async () => { await new Promise((r) => setTimeout(r, ms)); });
|
|
48
|
+
// iPhone 14 in the editor: M0 on screen (342 css px x 3), M1 its neighbour.
|
|
49
|
+
function phoneGallery(onScreen = "M0", neighbours = ["M1"]) {
|
|
50
|
+
IDS.forEach((id) => ctx.reportPictureView(`${id}#el`, {
|
|
51
|
+
mockupId: id, onScreen: id === onScreen, inSet: id === onScreen || neighbours.includes(id), devicePx: id === onScreen || neighbours.includes(id) ? 1026 : 0,
|
|
52
|
+
}));
|
|
53
|
+
}
|
|
54
|
+
function edit() { h.version += 1; ctx.sendCanvasState("Front", { v: h.version }); }
|
|
55
|
+
const frame = (id: string, v: number) => ({ mockupId: id, imageUrl: `https://r/${id}-v${v}`, renderUrl: `https://r/${id}-v${v}`, imageSize: 1, placement: "Front", requestVersion: v });
|
|
56
|
+
|
|
57
|
+
beforeEach(() => {
|
|
58
|
+
cleanup();
|
|
59
|
+
vi.clearAllMocks();
|
|
60
|
+
h.state.results = [];
|
|
61
|
+
h.version = 0;
|
|
62
|
+
h.sendCanvasState.mockImplementation(() => true);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
describe("viewport policy (phone gallery)", () => {
|
|
66
|
+
it("desktop / no gallery reports: one config, every picture at the page width, nothing more on edits (today)", async () => {
|
|
67
|
+
render(<Harness v={1} />);
|
|
68
|
+
await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
|
|
69
|
+
await act(async () => { edit(); edit(); });
|
|
70
|
+
await wait(150);
|
|
71
|
+
expect(shapes()).toEqual([`${IDS.join(",")}@3000`]);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it("an edit renders the set in view at the screen's width, in ONE config; more edit steps send none", async () => {
|
|
75
|
+
render(<Harness v={1} />);
|
|
76
|
+
await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
|
|
77
|
+
await act(async () => phoneGallery());
|
|
78
|
+
await wait(150);
|
|
79
|
+
h.sendConfig.mockClear();
|
|
80
|
+
await act(async () => { edit(); edit(); edit(); });
|
|
81
|
+
expect(shapes()).toEqual(["M0,M1@1200"]);
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it("a swipe during the edit adds the new slide in ONE config", async () => {
|
|
85
|
+
render(<Harness v={1} />);
|
|
86
|
+
await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
|
|
87
|
+
await act(async () => phoneGallery());
|
|
88
|
+
await wait(150);
|
|
89
|
+
await act(async () => edit());
|
|
90
|
+
h.sendConfig.mockClear();
|
|
91
|
+
await act(async () => phoneGallery("M1", ["M0", "M2"]));
|
|
92
|
+
await wait(150);
|
|
93
|
+
expect(shapes()).toEqual(["M0,M1,M2@1200"]);
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
it("when the edit settles: one catch-up config, every picture at the editing width; a new edit cancels it", async () => {
|
|
97
|
+
const { rerender } = render(<Harness v={1} />);
|
|
98
|
+
await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
|
|
99
|
+
await act(async () => phoneGallery());
|
|
100
|
+
await wait(150);
|
|
101
|
+
await act(async () => edit());
|
|
102
|
+
h.sendConfig.mockClear();
|
|
103
|
+
// v1's frames for the set land: the pipeline settles.
|
|
104
|
+
h.state.results = [frame("M0", 1), frame("M1", 1)];
|
|
105
|
+
await act(async () => rerender(<Harness v={2} />));
|
|
106
|
+
await wait(300);
|
|
107
|
+
// A new edit inside the quiet window cancels the catch-up.
|
|
108
|
+
await act(async () => edit());
|
|
109
|
+
await wait(700);
|
|
110
|
+
expect(shapes()).toEqual([]);
|
|
111
|
+
h.state.results = [frame("M0", 2), frame("M1", 2)];
|
|
112
|
+
await act(async () => rerender(<Harness v={3} />));
|
|
113
|
+
await wait(700);
|
|
114
|
+
expect(shapes()).toEqual([`${IDS.join(",")}@1200`]);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it("no catch-up mid-gesture: an OLDER version settling while the edit's export is pending is not the edit stopping (slow phone link, 2026-11-11)", async () => {
|
|
118
|
+
const { rerender } = render(<Harness v={1} />);
|
|
119
|
+
await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
|
|
120
|
+
await act(async () => phoneGallery());
|
|
121
|
+
await wait(150);
|
|
122
|
+
await act(async () => edit()); // v1 (the editor-open state) goes out; its frames are slow to land
|
|
123
|
+
h.sendConfig.mockClear();
|
|
124
|
+
// The drag begins: its export is announced, but the page takes 2.7 s to produce it (starved phone).
|
|
125
|
+
await act(async () => ctx.notifyPendingExport("Front"));
|
|
126
|
+
// Meanwhile v1's frames land (all of its set) and v1 settles.
|
|
127
|
+
h.state.results = IDS.map((id) => frame(id, 1));
|
|
128
|
+
await act(async () => rerender(<Harness v={2} />));
|
|
129
|
+
await wait(800);
|
|
130
|
+
expect(shapes()).toEqual([]); // no 6-picture catch-up while the gesture's export is on its way
|
|
131
|
+
await act(async () => edit()); // v2: the drag's state finally goes out
|
|
132
|
+
h.state.results = [frame("M0", 2), frame("M1", 2)];
|
|
133
|
+
await act(async () => rerender(<Harness v={3} />));
|
|
134
|
+
await wait(800);
|
|
135
|
+
expect(shapes()).toEqual([`${IDS.join(",")}@1200`]); // the edit's own frames landed: now catch up
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it("an export that turns out a no-op releases the edit: the catch-up still happens", async () => {
|
|
139
|
+
const { rerender } = render(<Harness v={1} />);
|
|
140
|
+
await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
|
|
141
|
+
await act(async () => phoneGallery());
|
|
142
|
+
await wait(150);
|
|
143
|
+
await act(async () => edit());
|
|
144
|
+
h.sendConfig.mockClear();
|
|
145
|
+
await act(async () => ctx.notifyPendingExport("Front"));
|
|
146
|
+
h.state.results = IDS.map((id) => frame(id, 1));
|
|
147
|
+
await act(async () => rerender(<Harness v={2} />));
|
|
148
|
+
await act(async () => ctx.notifyPendingExportCancelled("Front"));
|
|
149
|
+
await wait(800);
|
|
150
|
+
expect(shapes()).toEqual([`${IDS.join(",")}@1200`]);
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
it("Done: the slide on screen at hero width, in ONE config", async () => {
|
|
154
|
+
const { rerender } = render(<Harness v={1} />);
|
|
155
|
+
await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
|
|
156
|
+
await act(async () => phoneGallery());
|
|
157
|
+
await wait(150);
|
|
158
|
+
h.sendConfig.mockClear();
|
|
159
|
+
await act(async () => rerender(<Harness v={2} editorOpen={false} />));
|
|
160
|
+
expect(shapes()).toEqual(["M0@3000"]);
|
|
161
|
+
});
|
|
162
|
+
});
|