@snowcone-app/ui 0.9.8 → 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.8",
3
+ "version": "0.10.0",
4
4
  "description": "React components for merchandise visualization and customization",
5
5
  "keywords": [
6
6
  "react",
@@ -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
- }, [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]);
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,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;
@@ -354,6 +371,15 @@ export interface RealtimeProviderProps {
354
371
  * the rest of the session automatically.
355
372
  */
356
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;
357
383
  }
358
384
 
359
385
  /**
@@ -372,6 +398,7 @@ export function RealtimeProvider({
372
398
  grantUrl,
373
399
  initialGrant,
374
400
  delivery = "cropped",
401
+ editorOpen = true,
375
402
  }: RealtimeProviderProps) {
376
403
  const productContext = useProductOptional();
377
404
  // Page background for renders (see MockupBackground) — sent on the config so
@@ -633,6 +660,22 @@ export function RealtimeProvider({
633
660
  // config's set, or the last updateMockupIds set. A full-frame fallback
634
661
  // re-sends this set (plus the failed mockups) — it must never shrink it.
635
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;
636
679
  // True once a frame carries per-placement `versions`: the box then also
637
680
  // understands `rerender` (rendercenter rc#839 + rc#840, one roll).
638
681
  const serverStampsVersionsRef = useRef(false);
@@ -910,6 +953,79 @@ export function RealtimeProvider({
910
953
  croppedActiveRef.current = false;
911
954
  }, []);
912
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
+
913
1029
  /**
914
1030
  * Deliver displayable (always full-frame) results: update the snapshot and
915
1031
  * URL cache, clear pending state, notify subscribers, check settle.
@@ -994,13 +1110,15 @@ export function RealtimeProvider({
994
1110
  if (!pipelineResetCooldownRef.current) {
995
1111
  hasBlobInFlightRef.current = false;
996
1112
  for (let i = 0; i < settledVersions; i++) pipelineSettledSubscribersRef.current.forEach((cb) => cb());
1113
+ markEditSettled();
997
1114
  }
998
1115
  } else if (due.size === 0 && hasBlobInFlightRef.current && !hasPendingBlobs() && !pipelineResetCooldownRef.current) {
999
1116
  hasBlobInFlightRef.current = false;
1000
1117
  pipelineSettledSubscribersRef.current.forEach((cb) => cb());
1118
+ markEditSettled();
1001
1119
  }
1002
1120
  },
1003
- [hasPendingBlobs]
1121
+ [hasPendingBlobs, markEditSettled]
1004
1122
  );
1005
1123
 
1006
1124
  /** Composite one cropped frame over its frozen background and deliver it. */
@@ -1200,10 +1318,11 @@ export function RealtimeProvider({
1200
1318
  isPendingMockupsRef.current = true;
1201
1319
  // Notify pending blob subscribers (for shimmer effects)
1202
1320
  pendingBlobSubscribersRef.current.forEach((cb) => cb(placement));
1321
+ markEditLive();
1203
1322
  }
1204
1323
  return result;
1205
1324
  },
1206
- [sendCanvasBlobRaw]
1325
+ [sendCanvasBlobRaw, markEditLive]
1207
1326
  );
1208
1327
 
1209
1328
  // Wrap sendCanvasState for JSON mode (server-side canvas rendering)
@@ -1229,15 +1348,18 @@ export function RealtimeProvider({
1229
1348
  // count when it is smaller (a subset shown via updateMockupIds).
1230
1349
  const version = getLastSentVersion();
1231
1350
  if (version > 0) {
1232
- 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;
1233
1354
  const expected = Math.max(1, Math.min(configured || Infinity, mockupCount || Infinity));
1234
1355
  dueByVersionRef.current.set(version, { due: Number.isFinite(expected) ? expected : 1, at: Date.now() });
1235
1356
  }
1236
1357
  pendingBlobSubscribersRef.current.forEach((cb) => cb(placement));
1358
+ markEditLive();
1237
1359
  }
1238
1360
  return result;
1239
1361
  },
1240
- [sendCanvasStateRaw, getLastSentVersion]
1362
+ [sendCanvasStateRaw, getLastSentVersion, markEditLive]
1241
1363
  );
1242
1364
 
1243
1365
  // Wrap sendColorBlob to track when colors are sent
@@ -1332,6 +1454,10 @@ export function RealtimeProvider({
1332
1454
  });
1333
1455
  }
1334
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;
1335
1461
 
1336
1462
  // Authed sessions: the grant token (verified on connect) authorizes the
1337
1463
  // session and the server self-signs the render, so no seal is sent and the
@@ -1340,21 +1466,21 @@ export function RealtimeProvider({
1340
1466
  const configPayload = useSessionGrant
1341
1467
  ? {
1342
1468
  productId,
1343
- mockupIds,
1469
+ mockupIds: shape.mockupIds,
1344
1470
  variantId,
1345
1471
  shop: shop as string,
1346
- width: mockupWidth,
1472
+ width: shape.width,
1347
1473
  ...(mockupBg ? { bg: mockupBg } : {}),
1348
1474
  ...(spreadCropsRef.current ? { spreadCrops: spreadCropsRef.current } : {}),
1349
1475
  placementSettings: { ...placementSettingsOverridesRef.current },
1350
1476
  }
1351
1477
  : {
1352
1478
  productId,
1353
- mockupIds,
1479
+ mockupIds: shape.mockupIds,
1354
1480
  variantId,
1355
1481
  shop: "hTidnpNnNa",
1356
1482
  seal: "bypass-sig-for-k6-load-test",
1357
- width: mockupWidth,
1483
+ width: shape.width,
1358
1484
  ...(mockupBg ? { bg: mockupBg } : {}),
1359
1485
  ...(spreadCropsRef.current ? { spreadCrops: spreadCropsRef.current } : {}),
1360
1486
  placementSettings: { ...placementSettingsOverridesRef.current },
@@ -1373,7 +1499,7 @@ export function RealtimeProvider({
1373
1499
  // send — preserving cropped delivery across re-sends that kept the scene
1374
1500
  // (e.g. spread-crop changes).
1375
1501
  lastConfigBaseRef.current = configPayload as unknown as Record<string, unknown>;
1376
- requestedMockupIdsRef.current = mockupIds;
1502
+ requestedMockupIdsRef.current = [...shape.mockupIds];
1377
1503
  sendConfigRaw(
1378
1504
  (croppedActiveRef.current
1379
1505
  ? { ...configPayload, overlayCrop: "auto" as const }
@@ -1404,6 +1530,7 @@ export function RealtimeProvider({
1404
1530
  sendConfigRaw,
1405
1531
  sendColorBlobTracked,
1406
1532
  invalidateBackgrounds,
1533
+ currentShape,
1407
1534
  mockupWidth,
1408
1535
  mockupBg,
1409
1536
  spreadCropsVersion,
@@ -1660,8 +1787,9 @@ export function RealtimeProvider({
1660
1787
  console.log(`[RTP] notifyPendingExport("${placement}"): marked ${pendingIds.length} mockup(s) pending — [${pendingIds.slice(0, 5).join(', ')}${pendingIds.length > 5 ? '...' : ''}]`);
1661
1788
 
1662
1789
  pendingBlobSubscribersRef.current.forEach((cb) => cb(placement));
1790
+ markEditLive();
1663
1791
  },
1664
- [productContext?.product?.mockups]
1792
+ [productContext?.product?.mockups, markEditLive]
1665
1793
  );
1666
1794
 
1667
1795
  // Roll back a previous notifyPendingExport when the actual export turned
@@ -1809,6 +1937,22 @@ export function RealtimeProvider({
1809
1937
  getLatestSentVersionsRef.current = getLatestSentVersions;
1810
1938
  const getLatestSentVersionsStable = useCallback(() => getLatestSentVersionsRef.current?.() ?? {}, []);
1811
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
+
1812
1956
  const stableSubscribePipelineSettled = useCallback(
1813
1957
  (callback: () => void) => {
1814
1958
  return subscribePipelineSettledRef.current(callback);
@@ -1863,6 +2007,9 @@ export function RealtimeProvider({
1863
2007
  getMockupUrls,
1864
2008
  getCanvasVersion,
1865
2009
  getLatestSentVersions: getLatestSentVersionsStable,
2010
+ reportPictureView,
2011
+ getSessionShape,
2012
+ setEditorOpen: setEditorOpenState,
1866
2013
  isMockupLoading,
1867
2014
  registerBlobUrl,
1868
2015
  markBlobShown,
@@ -1898,6 +2045,8 @@ export function RealtimeProvider({
1898
2045
  getMockupUrls,
1899
2046
  getCanvasVersion,
1900
2047
  getLatestSentVersionsStable,
2048
+ reportPictureView,
2049
+ getSessionShape,
1901
2050
  isMockupLoading,
1902
2051
  registerBlobUrl,
1903
2052
  markBlobShown,
@@ -0,0 +1,126 @@
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("Done: the slide on screen at hero width, in ONE config", 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
+ h.sendConfig.mockClear();
123
+ await act(async () => rerender(<Harness v={2} editorOpen={false} />));
124
+ expect(shapes()).toEqual(["M0@3000"]);
125
+ });
126
+ });
@@ -0,0 +1,62 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { ladderWidth, sameShape, sessionShape, type PictureView } from "../sessionShape";
3
+
4
+ const ALL = Array.from({ length: 31 }, (_, i) => `M${i}`); // the phone case has 31 pictures
5
+ const view = (inSet: boolean, onScreen: boolean, devicePx = 1026): PictureView => ({ inSet, onScreen, devicePx });
6
+ // iPhone 14 in the editor: slide M0 on screen (342 css px x 3 = 1026 device px), M1 its neighbour.
7
+ const phone = new Map<string, PictureView>(ALL.map((id, i) => [id, view(i <= 1, i === 0, i <= 1 ? 1026 : 0)]));
8
+
9
+ describe("sessionShape", () => {
10
+ it("no viewport policy (desktop): every picture at the page width, exactly as today", () => {
11
+ expect(sessionShape({ allMockupIds: ALL, views: new Map(), heroWidth: 1280, editorOpen: true, editLive: true }))
12
+ .toEqual({ mockupIds: ALL, width: 1280, phase: "no-policy" });
13
+ });
14
+
15
+ it("a live edit renders only the set in view, at the width the screen shows (1026 -> 1200)", () => {
16
+ expect(sessionShape({ allMockupIds: ALL, views: phone, heroWidth: 3000, editorOpen: true, editLive: true }))
17
+ .toEqual({ mockupIds: ["M0", "M1"], width: 1200, phase: "editing" });
18
+ });
19
+
20
+ it("when the edit stops: every picture, still at the editing width (the catch-up)", () => {
21
+ expect(sessionShape({ allMockupIds: ALL, views: phone, heroWidth: 3000, editorOpen: true, editLive: false }))
22
+ .toEqual({ mockupIds: ALL, width: 1200, phase: "catch-up" });
23
+ });
24
+
25
+ it("Done: the slide on screen at hero width", () => {
26
+ expect(sessionShape({ allMockupIds: ALL, views: phone, heroWidth: 3000, editorOpen: false, editLive: false }))
27
+ .toEqual({ mockupIds: ["M0"], width: 3000, phase: "done" });
28
+ });
29
+
30
+ it("width comes from the element, not a breakpoint: a tablet slide 700 css px at 2x asks 1600", () => {
31
+ const tablet = new Map<string, PictureView>([["M0", view(true, true, 1400)], ["M1", view(true, false, 1400)]]);
32
+ expect(sessionShape({ allMockupIds: ALL, views: tablet, heroWidth: 3000, editorOpen: true, editLive: true }).width).toBe(1600);
33
+ });
34
+
35
+ it("keeps gallery order and never returns an empty set", () => {
36
+ const none = new Map<string, PictureView>([["M5", view(false, false, 0)]]);
37
+ expect(sessionShape({ allMockupIds: ALL, views: none, heroWidth: 3000, editorOpen: true, editLive: true }).mockupIds).toEqual(ALL);
38
+ expect(sessionShape({ allMockupIds: ALL, views: none, heroWidth: 3000, editorOpen: false, editLive: false }).mockupIds).toEqual(ALL);
39
+ });
40
+ });
41
+
42
+ describe("ladderWidth / sameShape", () => {
43
+ it("rounds UP to a ladder step", () => {
44
+ expect(ladderWidth(1026)).toBe(1200);
45
+ expect(ladderWidth(1200)).toBe(1200);
46
+ expect(ladderWidth(5000)).toBe(4000);
47
+ });
48
+ it("compares like the server: sorted ids and width", () => {
49
+ expect(sameShape({ mockupIds: ["b", "a"], width: 1200 }, { mockupIds: ["a", "b"], width: 1200 })).toBe(true);
50
+ expect(sameShape({ mockupIds: ["a"], width: 1200 }, { mockupIds: ["a"], width: 3000 })).toBe(false);
51
+ expect(sameShape(null, { mockupIds: ["a"], width: 1 })).toBe(false);
52
+ });
53
+
54
+ it("a mockup rendered twice (two elements) counts as on screen if either is", () => {
55
+ const twice = new Map<string, PictureView>([
56
+ ["M0#a", { mockupId: "M0", inSet: true, onScreen: true, devicePx: 1026 }],
57
+ ["M0#b", { mockupId: "M0", inSet: false, onScreen: false, devicePx: 0 }],
58
+ ]);
59
+ expect(sessionShape({ allMockupIds: ALL, views: twice, heroWidth: 3000, editorOpen: false, editLive: false }).mockupIds).toEqual(["M0"]);
60
+ });
61
+ });
62
+