@snowcone-app/ui 0.9.7 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@snowcone-app/ui",
3
- "version": "0.9.7",
3
+ "version": "0.10.0",
4
4
  "description": "React components for merchandise visualization and customization",
5
5
  "keywords": [
6
6
  "react",
@@ -103,7 +103,7 @@
103
103
  "react-instantsearch": "^7.15.5",
104
104
  "react-zoom-pan-pinch": "^3.6.4",
105
105
  "tailwind-merge": "^3.0.0",
106
- "@snowcone-app/sdk": "0.25.0"
106
+ "@snowcone-app/sdk": "0.26.0"
107
107
  },
108
108
  "devDependencies": {
109
109
  "@chromatic-com/storybook": "^4.1.2",
@@ -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();
@@ -559,6 +568,16 @@ export const HeroProductImage = memo(function HeroProductImage({
559
568
  const arrivedVersionRef = useRef(0);
560
569
  const versionByUrlRef = useRef<Map<string, { v: number; versions: Record<string, number> | null }>>(new Map());
561
570
  const loadedUrlRef = useRef<string | null>(null);
571
+ // This element's identity for frame release (a picture can have several elements showing different frames).
572
+ const blobConsumerRef = useRef(`el-${Math.random().toString(36).slice(2, 10)}`);
573
+ const releaseBlobConsumer = realtimeContext?.releaseBlobConsumer;
574
+ useEffect(() => {
575
+ const id = actualMockupId;
576
+ const consumer = blobConsumerRef.current;
577
+ return () => {
578
+ if (id) releaseBlobConsumer?.(id, consumer);
579
+ };
580
+ }, [actualMockupId, releaseBlobConsumer]);
562
581
  const frameErrorRef = useRef<string | null>(null);
563
582
  const showVersionOf = useCallback((url: string) => {
564
583
  const e = versionByUrlRef.current.get(url);
@@ -575,6 +594,7 @@ export const HeroProductImage = memo(function HeroProductImage({
575
594
  const sessionErrorCodeRef = useRef<string | null>(null);
576
595
  sessionErrorCodeRef.current = realtimeContext?.renderError?.code ?? null;
577
596
  const getCanvasVersion = realtimeContext?.getCanvasVersion;
597
+ const getSessionShape = realtimeContext?.getSessionShape;
578
598
  const applyRenderStamp = useCallback(() => {
579
599
  const node = containerRef.current;
580
600
  if (!node) return;
@@ -602,7 +622,17 @@ export const HeroProductImage = memo(function HeroProductImage({
602
622
  node.dataset.renderState = refusalCodeRef.current || (behind && sessionErrorCodeRef.current)
603
623
  ? "refused"
604
624
  : behind ? "stale" : "current";
605
- }, [getCanvasVersion, getLatestSentVersions]);
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]);
606
636
  const applyRenderStampRef = useRef(applyRenderStamp);
607
637
  applyRenderStampRef.current = applyRenderStamp;
608
638
  // Re-apply after every render (the root node can change; refusals are state).
@@ -638,6 +668,42 @@ export const HeroProductImage = memo(function HeroProductImage({
638
668
  applyRenderStamp,
639
669
  ]);
640
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
+
641
707
  // Register with priority context
642
708
  useEffect(() => {
643
709
  if (!priorityContext || !actualMockupId || !placement) return;
@@ -1177,7 +1243,7 @@ export const HeroProductImage = memo(function HeroProductImage({
1177
1243
  if (renderedUrl) {
1178
1244
  loadedUrlRef.current = renderedUrl;
1179
1245
  showVersionOf(renderedUrl);
1180
- if (actualMockupId) realtimeContext?.markBlobShown?.(actualMockupId, renderedUrl);
1246
+ if (actualMockupId) realtimeContext?.markBlobShown?.(actualMockupId, renderedUrl, blobConsumerRef.current);
1181
1247
  applyRenderStampRef.current?.();
1182
1248
  }
1183
1249
  if (!onLoadCalledRef.current && onLoad) {
@@ -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,8 @@ 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;
75
78
 
76
79
  /** `current` in order, then any of `extra` not already in it. */
77
80
  function mergeMockupIds(current: readonly string[], extra: readonly string[]): string[] {
@@ -262,6 +265,20 @@ export interface RealtimeContextValue {
262
265
  */
263
266
  getLatestSentVersions: () => Record<string, number>;
264
267
 
268
+ /**
269
+ * Viewport policy (sessionShape.ts): a gallery picture reports whether it is
270
+ * in the edit set (in view or a neighbour), on screen, and its displayed
271
+ * width in device pixels; `null` when it unmounts. Only a gallery that opts
272
+ * in reports (the phone carousel); without reports nothing changes.
273
+ */
274
+ reportPictureView: (elementKey: string, view: PictureView | null) => void;
275
+
276
+ /** The shape the session renders now: its phase and width (for data attributes and checks). */
277
+ getSessionShape: () => { phase: SessionShape["phase"]; width: number } | null;
278
+
279
+ /** The design editor opened or closed (Done). Drives the viewport policy's phase; see `editorOpen`. */
280
+ setEditorOpen: (open: boolean) => void;
281
+
265
282
  // Flush pending blobs immediately (call on mouse up, action complete, etc.)
266
283
  flushPendingBlobs: () => void;
267
284
  hasPendingBlobs: () => boolean;
@@ -309,7 +326,10 @@ export interface RealtimeContextValue {
309
326
  registerBlobUrl: (blobOrUrl: Blob | string, placementName?: string) => string;
310
327
 
311
328
  /** A picture's <img> loaded `url` (from getMockupUrl): its older composited frames are released. */
312
- markBlobShown: (mockupId: string, url: string) => void;
329
+ markBlobShown: (mockupId: string, url: string, consumer?: string) => void;
330
+
331
+ /** An element that called markBlobShown unmounted: it no longer holds its frame. */
332
+ releaseBlobConsumer: (mockupId: string, consumer: string) => void;
313
333
  }
314
334
 
315
335
  const RealtimeContext = createContext<RealtimeContextValue | undefined>(
@@ -351,6 +371,15 @@ export interface RealtimeProviderProps {
351
371
  * the rest of the session automatically.
352
372
  */
353
373
  delivery?: "cropped" | "full-frame";
374
+ /**
375
+ * Whether the design editor is open. With a gallery that opted into the
376
+ * viewport policy (`reportPictureView`, the phone carousel), an open editor
377
+ * renders the pictures in view at the width the screen shows them while an
378
+ * edit is live, and every picture at that width when it stops; closing it
379
+ * (Done) renders the picture on screen at `mockupWidth` (see sessionShape.ts).
380
+ * Without such a gallery it changes nothing. Default true.
381
+ */
382
+ editorOpen?: boolean;
354
383
  }
355
384
 
356
385
  /**
@@ -369,6 +398,7 @@ export function RealtimeProvider({
369
398
  grantUrl,
370
399
  initialGrant,
371
400
  delivery = "cropped",
401
+ editorOpen = true,
372
402
  }: RealtimeProviderProps) {
373
403
  const productContext = useProductOptional();
374
404
  // Page background for renders (see MockupBackground) — sent on the config so
@@ -513,7 +543,11 @@ export function RealtimeProvider({
513
543
  getLastSentVersion,
514
544
  getLatestSentVersions,
515
545
  rerender: rerenderRaw,
546
+ isFrameSuperseded,
516
547
  } = realtimeMockup;
548
+ // Read through a ref: the composite pump's callbacks stay stable across renders.
549
+ const isFrameSupersededRef = useRef(isFrameSuperseded);
550
+ isFrameSupersededRef.current = isFrameSuperseded;
517
551
 
518
552
  // PERFORMANCE: Store mockup results in ref only - NO STATE UPDATES
519
553
  // This eliminates re-render cascades entirely. Components that need mockup results
@@ -581,7 +615,8 @@ export function RealtimeProvider({
581
615
  const registeredBlobUrlsRef = useRef<Set<string>>(new Set());
582
616
  // Composited frames per picture (newest first), and the one its <img> shows: revoked only when that picture moves on.
583
617
  const blobsByOwnerRef = useRef<Map<string, string[]>>(new Map());
584
- const shownBlobByOwnerRef = useRef<Map<string, string>>(new Map());
618
+ // Per picture: what EACH of its elements shows (a gallery can render one picture twice: the phone carousel does).
619
+ const shownBlobByOwnerRef = useRef<Map<string, Map<string, string>>>(new Map());
585
620
 
586
621
  // Track which placements have pending exports (for shimmer state)
587
622
  const pendingPlacementsRef = useRef<Set<string>>(new Set());
@@ -625,6 +660,22 @@ export function RealtimeProvider({
625
660
  // config's set, or the last updateMockupIds set. A full-frame fallback
626
661
  // re-sends this set (plus the failed mockups) — it must never shrink it.
627
662
  const requestedMockupIdsRef = useRef<string[]>([]);
663
+ // VIEWPORT POLICY (sessionShape.ts): the pictures that opted in, whether an
664
+ // edit is live, and the shape last sent. ONE config per change of shape.
665
+ const pictureViewsRef = useRef<Map<string, PictureView>>(new Map());
666
+ const editLiveRef = useRef(false);
667
+ const editQuietTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
668
+ const shapeApplyTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
669
+ const lastShapeRef = useRef<SessionShape | null>(null);
670
+ const applySessionShapeRef = useRef<(() => void) | null>(null);
671
+ // Initial value from the prop; pages whose editor state lives below the
672
+ // provider drive it with setEditorOpen().
673
+ const [editorOpenState, setEditorOpenState] = useState(editorOpen);
674
+ useEffect(() => setEditorOpenState(editorOpen), [editorOpen]);
675
+ const editorOpenRef = useRef(editorOpenState);
676
+ editorOpenRef.current = editorOpenState;
677
+ const heroWidthRef = useRef(mockupWidth);
678
+ heroWidthRef.current = mockupWidth;
628
679
  // True once a frame carries per-placement `versions`: the box then also
629
680
  // understands `rerender` (rendercenter rc#839 + rc#840, one roll).
630
681
  const serverStampsVersionsRef = useRef(false);
@@ -677,9 +728,9 @@ export function RealtimeProvider({
677
728
  const url = URL.createObjectURL(blobOrUrl);
678
729
  if (owner) {
679
730
  const list = [url, ...(blobsByOwnerRef.current.get(owner) ?? [])]; // newest first
680
- const shown = shownBlobByOwnerRef.current.get(owner);
731
+ const shown = new Set(shownBlobByOwnerRef.current.get(owner)?.values() ?? []);
681
732
  while (list.length > MAX_FRAMES_PER_PICTURE) {
682
- const victimIdx = [...list.keys()].reverse().find((i) => i > 0 && list[i] !== shown);
733
+ const victimIdx = [...list.keys()].reverse().find((i) => i > 0 && !shown.has(list[i]));
683
734
  if (victimIdx === undefined) break;
684
735
  const [victim] = list.splice(victimIdx, 1);
685
736
  console.error(
@@ -698,17 +749,40 @@ export function RealtimeProvider({
698
749
  return url;
699
750
  }, [revokeBlobUrl]);
700
751
 
701
- /** A picture's <img> has loaded `url`: its older composited frames can go. */
702
- const markBlobShown = useCallback((owner: string, url: string) => {
752
+ /** Release a picture's frames that are older than what EVERY one of its elements shows. */
753
+ const releaseOlderFrames = useCallback((owner: string) => {
703
754
  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));
755
+ const shown = shownBlobByOwnerRef.current.get(owner);
756
+ if (!list || !shown || shown.size === 0) return;
757
+ // The oldest frame any element still shows: everything older is unreachable.
758
+ const oldestShownIdx = Math.max(...[...shown.values()].map((u) => list.indexOf(u)));
759
+ if (oldestShownIdx < 0) return;
760
+ list.slice(oldestShownIdx + 1).forEach(revokeBlobUrl);
761
+ blobsByOwnerRef.current.set(owner, list.slice(0, oldestShownIdx + 1));
710
762
  }, [revokeBlobUrl]);
711
763
 
764
+ /**
765
+ * An element of a picture (`consumer`: one per <img>) has loaded `url`. A picture can be rendered by more than one
766
+ * element (the phone carousel renders each twice): releasing on the FIRST element's load revoked the frame its twin
767
+ * was still loading, so the twin kept its old image for good (prod phone, 2026-11-11, after #4390). Frames go only
768
+ * when they are older than what every element shows.
769
+ */
770
+ const markBlobShown = useCallback((owner: string, url: string, consumer = "default") => {
771
+ const list = blobsByOwnerRef.current.get(owner);
772
+ if (!list || list.indexOf(url) < 0) return;
773
+ const shown = shownBlobByOwnerRef.current.get(owner) ?? new Map<string, string>();
774
+ shown.set(consumer, url);
775
+ shownBlobByOwnerRef.current.set(owner, shown);
776
+ releaseOlderFrames(owner);
777
+ }, [releaseOlderFrames]);
778
+
779
+ /** An element of a picture is gone (unmount): it no longer holds a frame. */
780
+ const releaseBlobConsumer = useCallback((owner: string, consumer: string) => {
781
+ const shown = shownBlobByOwnerRef.current.get(owner);
782
+ if (!shown?.delete(consumer)) return;
783
+ releaseOlderFrames(owner);
784
+ }, [releaseOlderFrames]);
785
+
712
786
  const croppedDeliveryEnabled = delivery !== "full-frame";
713
787
 
714
788
  /** Re-send the last config with/without overlayCrop (delivery flip only). */
@@ -879,6 +953,79 @@ export function RealtimeProvider({
879
953
  croppedActiveRef.current = false;
880
954
  }, []);
881
955
 
956
+ const currentShape = useCallback(
957
+ () =>
958
+ sessionShape({
959
+ allMockupIds: configuredMockupIdsRef.current,
960
+ views: pictureViewsRef.current,
961
+ heroWidth: heroWidthRef.current,
962
+ editorOpen: editorOpenRef.current,
963
+ editLive: editLiveRef.current,
964
+ }),
965
+ []
966
+ );
967
+
968
+ /**
969
+ * Send ONE config when the session's shape (which pictures, what width)
970
+ * changed. The server renders the last config's set at its width, so this
971
+ * is the only place the set or the width changes mid-session. A width
972
+ * change re-seeds the cropped-delivery backgrounds (they are the old size).
973
+ */
974
+ const applySessionShape = useCallback(() => {
975
+ const base = lastConfigBaseRef.current;
976
+ if (!base || !configSentRef.current) return;
977
+ const shape = currentShape();
978
+ if (sameShape(lastShapeRef.current, shape)) {
979
+ lastShapeRef.current = shape; // phase may differ with the same request
980
+ return;
981
+ }
982
+ if (lastShapeRef.current && lastShapeRef.current.width !== shape.width) invalidateBackgrounds();
983
+ lastShapeRef.current = shape;
984
+ base.mockupIds = shape.mockupIds;
985
+ base.width = shape.width;
986
+ requestedMockupIdsRef.current = [...shape.mockupIds];
987
+ sendConfigRaw({
988
+ ...base,
989
+ placementSettings: { ...placementSettingsOverridesRef.current },
990
+ ...(croppedActiveRef.current ? { overlayCrop: "auto" as const } : {}),
991
+ } as Parameters<typeof sendConfigRaw>[0]);
992
+ }, [currentShape, invalidateBackgrounds, sendConfigRaw]);
993
+ applySessionShapeRef.current = applySessionShape;
994
+
995
+ /** An edit went out: render the set in view until it stops; cancels a catch-up in flight. */
996
+ const markEditLive = useCallback(() => {
997
+ if (editQuietTimerRef.current) {
998
+ clearTimeout(editQuietTimerRef.current);
999
+ editQuietTimerRef.current = null;
1000
+ }
1001
+ if (editLiveRef.current) return;
1002
+ editLiveRef.current = true;
1003
+ applySessionShapeRef.current?.();
1004
+ }, []);
1005
+
1006
+ /** The pipeline settled: after EDIT_QUIET_MS with no new edit, catch every picture up. */
1007
+ const markEditSettled = useCallback(() => {
1008
+ if (!editLiveRef.current) return;
1009
+ if (editQuietTimerRef.current) clearTimeout(editQuietTimerRef.current);
1010
+ editQuietTimerRef.current = setTimeout(() => {
1011
+ editQuietTimerRef.current = null;
1012
+ editLiveRef.current = false;
1013
+ applySessionShapeRef.current?.();
1014
+ }, EDIT_QUIET_MS);
1015
+ }, []);
1016
+
1017
+ useEffect(() => {
1018
+ applySessionShapeRef.current?.();
1019
+ }, [editorOpenState]);
1020
+
1021
+ useEffect(
1022
+ () => () => {
1023
+ if (editQuietTimerRef.current) clearTimeout(editQuietTimerRef.current);
1024
+ if (shapeApplyTimerRef.current) clearTimeout(shapeApplyTimerRef.current);
1025
+ },
1026
+ []
1027
+ );
1028
+
882
1029
  /**
883
1030
  * Deliver displayable (always full-frame) results: update the snapshot and
884
1031
  * URL cache, clear pending state, notify subscribers, check settle.
@@ -963,13 +1110,15 @@ export function RealtimeProvider({
963
1110
  if (!pipelineResetCooldownRef.current) {
964
1111
  hasBlobInFlightRef.current = false;
965
1112
  for (let i = 0; i < settledVersions; i++) pipelineSettledSubscribersRef.current.forEach((cb) => cb());
1113
+ markEditSettled();
966
1114
  }
967
1115
  } else if (due.size === 0 && hasBlobInFlightRef.current && !hasPendingBlobs() && !pipelineResetCooldownRef.current) {
968
1116
  hasBlobInFlightRef.current = false;
969
1117
  pipelineSettledSubscribersRef.current.forEach((cb) => cb());
1118
+ markEditSettled();
970
1119
  }
971
1120
  },
972
- [hasPendingBlobs]
1121
+ [hasPendingBlobs, markEditSettled]
973
1122
  );
974
1123
 
975
1124
  /** Composite one cropped frame over its frozen background and deliver it. */
@@ -1018,6 +1167,13 @@ export function RealtimeProvider({
1018
1167
  ) {
1019
1168
  return;
1020
1169
  }
1170
+ // The SDK revoked this frame because the mockup's NEXT frame has
1171
+ // arrived. React only learns of it with that batch's
1172
+ // all_mockups_rendered, which on a 31-picture product can come well
1173
+ // after the 2 s grace below (prod phone case, 2026-11-11, rendercenter
1174
+ // 20d5eaf: v3 batch 2.3 s, the grace fired first, cropped delivery went
1175
+ // off and a visible picture stayed at v2). The SDK knows at once.
1176
+ if (isFrameSupersededRef.current?.(result.imageUrl)) return;
1021
1177
  // The FRAME (not the background) failed to load from a revoked blob:
1022
1178
  // URL. The SDK revokes a mockup's frame only when that mockup's next
1023
1179
  // frame arrives, so the newer frame exists even if React state hasn't
@@ -1162,10 +1318,11 @@ export function RealtimeProvider({
1162
1318
  isPendingMockupsRef.current = true;
1163
1319
  // Notify pending blob subscribers (for shimmer effects)
1164
1320
  pendingBlobSubscribersRef.current.forEach((cb) => cb(placement));
1321
+ markEditLive();
1165
1322
  }
1166
1323
  return result;
1167
1324
  },
1168
- [sendCanvasBlobRaw]
1325
+ [sendCanvasBlobRaw, markEditLive]
1169
1326
  );
1170
1327
 
1171
1328
  // Wrap sendCanvasState for JSON mode (server-side canvas rendering)
@@ -1191,15 +1348,18 @@ export function RealtimeProvider({
1191
1348
  // count when it is smaller (a subset shown via updateMockupIds).
1192
1349
  const version = getLastSentVersion();
1193
1350
  if (version > 0) {
1194
- const configured = configuredMockupIdsRef.current.length;
1351
+ // Frames due = the set the session renders now (the viewport policy
1352
+ // narrows it while an edit is live), not every configured picture.
1353
+ const configured = requestedMockupIdsRef.current.length || configuredMockupIdsRef.current.length;
1195
1354
  const expected = Math.max(1, Math.min(configured || Infinity, mockupCount || Infinity));
1196
1355
  dueByVersionRef.current.set(version, { due: Number.isFinite(expected) ? expected : 1, at: Date.now() });
1197
1356
  }
1198
1357
  pendingBlobSubscribersRef.current.forEach((cb) => cb(placement));
1358
+ markEditLive();
1199
1359
  }
1200
1360
  return result;
1201
1361
  },
1202
- [sendCanvasStateRaw, getLastSentVersion]
1362
+ [sendCanvasStateRaw, getLastSentVersion, markEditLive]
1203
1363
  );
1204
1364
 
1205
1365
  // Wrap sendColorBlob to track when colors are sent
@@ -1294,6 +1454,10 @@ export function RealtimeProvider({
1294
1454
  });
1295
1455
  }
1296
1456
  configuredMockupIdsRef.current = mockupIds;
1457
+ // The viewport policy shapes even the first config (sessionShape.ts):
1458
+ // with no gallery opted in it is every picture at mockupWidth (today).
1459
+ const shape = currentShape();
1460
+ lastShapeRef.current = shape;
1297
1461
 
1298
1462
  // Authed sessions: the grant token (verified on connect) authorizes the
1299
1463
  // session and the server self-signs the render, so no seal is sent and the
@@ -1302,21 +1466,21 @@ export function RealtimeProvider({
1302
1466
  const configPayload = useSessionGrant
1303
1467
  ? {
1304
1468
  productId,
1305
- mockupIds,
1469
+ mockupIds: shape.mockupIds,
1306
1470
  variantId,
1307
1471
  shop: shop as string,
1308
- width: mockupWidth,
1472
+ width: shape.width,
1309
1473
  ...(mockupBg ? { bg: mockupBg } : {}),
1310
1474
  ...(spreadCropsRef.current ? { spreadCrops: spreadCropsRef.current } : {}),
1311
1475
  placementSettings: { ...placementSettingsOverridesRef.current },
1312
1476
  }
1313
1477
  : {
1314
1478
  productId,
1315
- mockupIds,
1479
+ mockupIds: shape.mockupIds,
1316
1480
  variantId,
1317
1481
  shop: "hTidnpNnNa",
1318
1482
  seal: "bypass-sig-for-k6-load-test",
1319
- width: mockupWidth,
1483
+ width: shape.width,
1320
1484
  ...(mockupBg ? { bg: mockupBg } : {}),
1321
1485
  ...(spreadCropsRef.current ? { spreadCrops: spreadCropsRef.current } : {}),
1322
1486
  placementSettings: { ...placementSettingsOverridesRef.current },
@@ -1335,7 +1499,7 @@ export function RealtimeProvider({
1335
1499
  // send — preserving cropped delivery across re-sends that kept the scene
1336
1500
  // (e.g. spread-crop changes).
1337
1501
  lastConfigBaseRef.current = configPayload as unknown as Record<string, unknown>;
1338
- requestedMockupIdsRef.current = mockupIds;
1502
+ requestedMockupIdsRef.current = [...shape.mockupIds];
1339
1503
  sendConfigRaw(
1340
1504
  (croppedActiveRef.current
1341
1505
  ? { ...configPayload, overlayCrop: "auto" as const }
@@ -1366,6 +1530,7 @@ export function RealtimeProvider({
1366
1530
  sendConfigRaw,
1367
1531
  sendColorBlobTracked,
1368
1532
  invalidateBackgrounds,
1533
+ currentShape,
1369
1534
  mockupWidth,
1370
1535
  mockupBg,
1371
1536
  spreadCropsVersion,
@@ -1622,8 +1787,9 @@ export function RealtimeProvider({
1622
1787
  console.log(`[RTP] notifyPendingExport("${placement}"): marked ${pendingIds.length} mockup(s) pending — [${pendingIds.slice(0, 5).join(', ')}${pendingIds.length > 5 ? '...' : ''}]`);
1623
1788
 
1624
1789
  pendingBlobSubscribersRef.current.forEach((cb) => cb(placement));
1790
+ markEditLive();
1625
1791
  },
1626
- [productContext?.product?.mockups]
1792
+ [productContext?.product?.mockups, markEditLive]
1627
1793
  );
1628
1794
 
1629
1795
  // Roll back a previous notifyPendingExport when the actual export turned
@@ -1771,6 +1937,22 @@ export function RealtimeProvider({
1771
1937
  getLatestSentVersionsRef.current = getLatestSentVersions;
1772
1938
  const getLatestSentVersionsStable = useCallback(() => getLatestSentVersionsRef.current?.() ?? {}, []);
1773
1939
 
1940
+ const reportPictureView = useCallback((elementKey: string, view: PictureView | null) => {
1941
+ const views = pictureViewsRef.current;
1942
+ if (view) views.set(elementKey, view);
1943
+ else views.delete(elementKey);
1944
+ // Batch a swipe's / a scroll's reports into one shape check (one config).
1945
+ if (shapeApplyTimerRef.current) return;
1946
+ shapeApplyTimerRef.current = setTimeout(() => {
1947
+ shapeApplyTimerRef.current = null;
1948
+ applySessionShapeRef.current?.();
1949
+ }, 100);
1950
+ }, []);
1951
+ const getSessionShape = useCallback(() => {
1952
+ const s = lastShapeRef.current;
1953
+ return s ? { phase: s.phase, width: s.width } : null;
1954
+ }, []);
1955
+
1774
1956
  const stableSubscribePipelineSettled = useCallback(
1775
1957
  (callback: () => void) => {
1776
1958
  return subscribePipelineSettledRef.current(callback);
@@ -1825,9 +2007,13 @@ export function RealtimeProvider({
1825
2007
  getMockupUrls,
1826
2008
  getCanvasVersion,
1827
2009
  getLatestSentVersions: getLatestSentVersionsStable,
2010
+ reportPictureView,
2011
+ getSessionShape,
2012
+ setEditorOpen: setEditorOpenState,
1828
2013
  isMockupLoading,
1829
2014
  registerBlobUrl,
1830
2015
  markBlobShown,
2016
+ releaseBlobConsumer,
1831
2017
  // WebRTC streaming
1832
2018
  subscribeRTCTiming,
1833
2019
  }),
@@ -1859,9 +2045,12 @@ export function RealtimeProvider({
1859
2045
  getMockupUrls,
1860
2046
  getCanvasVersion,
1861
2047
  getLatestSentVersionsStable,
2048
+ reportPictureView,
2049
+ getSessionShape,
1862
2050
  isMockupLoading,
1863
2051
  registerBlobUrl,
1864
2052
  markBlobShown,
2053
+ releaseBlobConsumer,
1865
2054
  ]
1866
2055
  );
1867
2056
 
@@ -211,4 +211,61 @@ describe("composited frames per picture (prod desktop 2026-11-11: 15 ERR_FILE_NO
211
211
  capturedCtx.markBlobShown("m0", second);
212
212
  expect(revoked).toEqual([firstUrls[0]]);
213
213
  });
214
+
215
+ it("a picture rendered by N elements (the phone page renders each twice): a frame goes only when EVERY element has moved past it", async () => {
216
+ const revoked: string[] = [];
217
+ globalThis.URL.revokeObjectURL = vi.fn((u: string) => { revoked.push(u); });
218
+ const { rerender } = render(<Harness version={1} />);
219
+ await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
220
+ h.state.results = IDS.map((id) => fullResult(id, `https://r/${id}-full`));
221
+ await act(async () => rerender(<Harness version={2} />));
222
+ await waitFor(() => expect(sentConfigs().some((c) => c.overlayCrop === "auto")).toBe(true));
223
+ h.state.results = IDS.map((id) => croppedResult(id, `https://r/${id}-crop-1`));
224
+ await act(async () => rerender(<Harness version={3} />));
225
+ await waitFor(() => expect(h.compositeCroppedFrame).toHaveBeenCalledTimes(31));
226
+ await act(async () => { await new Promise((r) => setTimeout(r, 50)); });
227
+ const f1 = capturedCtx.getMockupUrl("m0")!;
228
+ // N elements of m0 (the phone page mounts the carousel twice; a third surface for the general case) show frame 1.
229
+ for (const el of ["hero", "twin", "third"]) capturedCtx.markBlobShown("m0", f1, el);
230
+ h.state.results = IDS.map((id) => croppedResult(id, `https://r/${id}-crop-2`));
231
+ await act(async () => rerender(<Harness version={4} />));
232
+ await waitFor(() => expect(h.compositeCroppedFrame).toHaveBeenCalledTimes(62));
233
+ await act(async () => { await new Promise((r) => setTimeout(r, 50)); });
234
+ const f2 = capturedCtx.getMockupUrl("m0")!;
235
+ // The hero shows frame 2 first; the twin still shows (and may be reloading) frame 1: it must stay alive.
236
+ capturedCtx.markBlobShown("m0", f2, "hero");
237
+ expect(revoked).toEqual([]);
238
+ // A second element catches up: the third still shows frame 1, so it stays.
239
+ capturedCtx.markBlobShown("m0", f2, "twin");
240
+ expect(revoked).toEqual([]);
241
+ // The last element catches up: now frame 1 is unreachable and goes.
242
+ capturedCtx.markBlobShown("m0", f2, "third");
243
+ expect(revoked).toEqual([f1]);
244
+ });
245
+
246
+ it("an element that unmounts stops holding its frame", async () => {
247
+ const revoked: string[] = [];
248
+ globalThis.URL.revokeObjectURL = vi.fn((u: string) => { revoked.push(u); });
249
+ const { rerender } = render(<Harness version={1} />);
250
+ await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
251
+ h.state.results = IDS.map((id) => fullResult(id, `https://r/${id}-full`));
252
+ await act(async () => rerender(<Harness version={2} />));
253
+ await waitFor(() => expect(sentConfigs().some((c) => c.overlayCrop === "auto")).toBe(true));
254
+ h.state.results = IDS.map((id) => croppedResult(id, `https://r/${id}-crop-1`));
255
+ await act(async () => rerender(<Harness version={3} />));
256
+ await waitFor(() => expect(h.compositeCroppedFrame).toHaveBeenCalledTimes(31));
257
+ await act(async () => { await new Promise((r) => setTimeout(r, 50)); });
258
+ const f1 = capturedCtx.getMockupUrl("m0")!;
259
+ capturedCtx.markBlobShown("m0", f1, "hero");
260
+ capturedCtx.markBlobShown("m0", f1, "twin");
261
+ h.state.results = IDS.map((id) => croppedResult(id, `https://r/${id}-crop-2`));
262
+ await act(async () => rerender(<Harness version={4} />));
263
+ await waitFor(() => expect(h.compositeCroppedFrame).toHaveBeenCalledTimes(62));
264
+ await act(async () => { await new Promise((r) => setTimeout(r, 50)); });
265
+ capturedCtx.markBlobShown("m0", capturedCtx.getMockupUrl("m0")!, "hero");
266
+ expect(revoked).toEqual([]);
267
+ capturedCtx.releaseBlobConsumer("m0", "twin");
268
+ expect(revoked).toEqual([f1]);
269
+ });
214
270
  });
271
+