@spatial-elements/sveltekit 1.0.0-beta.5 → 1.0.0-beta.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,291 +1,236 @@
1
1
  <script lang="ts">
2
2
  import { getContext, onMount, tick, untrack } from 'svelte';
3
3
  import Section from './Section.svelte';
4
+ import { retainListDeviceOrientation } from '@spatial-elements/core/catalog/listDeviceOrientation';
5
+ import { carouselTextHit } from './carouselTextHit.js';
4
6
  import CarouselSpatialElement from './CarouselSpatialElement.svelte';
5
- import { CATALOG_POSE_CHANGED } from '@spatial-elements/core/catalog/catalogPose';
6
- import type { CarouselPresentation } from '@spatial-elements/core/catalog/catalogPose';
7
+ import { CATALOG_POSE_CHANGED, carouselEmphasis, CarouselDragEmphasis, type CarouselEmphasis, type CarouselLayout, type CarouselPresentation } from '@spatial-elements/core/catalog/catalogPose';
7
8
  import type { SpatialListItem, SpatialElementSectionDefinition } from '@spatial-elements/core/spatial-element/types';
8
9
  import { CATALOG_SECTIONS, type CatalogSections } from '@spatial-elements/core/catalog/CatalogSections';
9
- import {
10
- carouselKey,
11
- resolveCarouselSelection,
12
- stepCarouselSelection
13
- } from '@spatial-elements/core/catalog/carouselSelection';
14
- import {
15
- CarouselDrag,
16
- CarouselScrollDrag,
17
- clampCarouselPhase,
18
- sampleCarouselSpring,
19
- sampleCarouselScrollMomentum
20
- } from '@spatial-elements/core/catalog/carouselMotion';
21
- import { markStageScrollInput } from '@spatial-elements/core/stage/scrollFrame';
10
+ import { carouselKey, resolveCarouselSelection, stepCarouselSelection } from '@spatial-elements/core/catalog/carouselSelection';
11
+ import { CarouselDrag, CarouselWheelInput, clampCarouselPhase, sampleCarouselInertia } from '@spatial-elements/core/catalog/carouselMotion';
12
+ import { STAGE_CONTEXT_KEY, type StageContext } from '@spatial-elements/core/stage/panelContext';
22
13
 
23
- let {
24
- section,
25
- presentation,
26
- list,
27
- initialItemKey,
28
- onselectionchange
29
- }: {
30
- /** Unique page-local anchor, heading and optional CSS appearance overrides. */
14
+ let { section, presentation, list, initialItemKey, onselectionchange }: {
31
15
  section: SpatialElementSectionDefinition;
32
- /** Project element documents with getSpatialListItems; assets register automatically. */
33
- list: SpatialListItem[];
34
- /** Arc radius (default 0.48 of width) and depth (default 700 CSS-world pixels). */
35
16
  presentation?: CarouselPresentation;
36
- /** Initially selected itemKey (or element ID); defaults to the first item. */
17
+ list: SpatialListItem[];
37
18
  initialItemKey?: string;
38
- /** Reports selection changes; URL and application state remain host-owned. */
39
19
  onselectionchange?: (selection: { itemKey: string; spatialElementId: string }) => void;
40
20
  } = $props();
41
21
  const sections = getContext<CatalogSections | undefined>(CATALOG_SECTIONS);
42
-
22
+ const stage = getContext<StageContext | undefined>(STAGE_CONTEXT_KEY);
23
+ const interactive = $derived(stage?.isEnhanced?.() ?? false);
24
+ const keys = $derived(list.map(carouselKey));
43
25
  let requested = $state<string>();
44
- let interactive = $state(false);
26
+ const selected = $derived(resolveCarouselSelection(keys, requested ?? initialItemKey));
27
+ const initialIndex = $derived(Math.max(0, keys.indexOf(resolveCarouselSelection(keys, initialItemKey) ?? '')));
28
+ const orderedItems = $derived(interactive ? [...list.entries()] : [...list.entries()].slice(initialIndex).concat([...list.entries()].slice(0, initialIndex)));
45
29
  let phase = $state(0);
46
30
  let windowPhase = $state(0);
31
+ let emphasis = $state<CarouselEmphasis[] | undefined>();
32
+ const focus = $derived(emphasis ? Math.max(0, ...emphasis.map(value => value.advance)) : 1);
33
+ const arrowOpacity = $derived(Math.max(0, ...list.map((_, i) => emphasis?.[i]?.panel ?? carouselEmphasis(i - phase).panel)));
34
+ const indicated = $derived(keys[Math.round(clampCarouselPhase(phase, keys.length))]);
35
+ let announced = $state<string>();
36
+ let ring: HTMLDivElement;
47
37
  $effect(() => {
48
- if (Math.abs(phase - windowPhase) > 0.75) windowPhase = Math.round(phase);
38
+ if (interactive && ring) return retainListDeviceOrientation(ring, () => {});
49
39
  });
50
- let ring: HTMLDivElement;
40
+ let layout = $state<CarouselLayout>({ width: 1320, height: 600, left: 60, viewportWidth: 1440 });
51
41
  let frame = 0;
52
- let scrollFrame = 0;
53
- let visible = true;
42
+ let nativeFrame = 0;
43
+ let mounted = false;
44
+ let generation = 0;
54
45
  let suppressClick = false;
55
46
  let clickTimer: ReturnType<typeof setTimeout>;
56
- let announced = $state<string>();
57
- let selectionDirty = false;
58
- let previousKeys: string | undefined;
59
- function rememberSelection() {
60
- if (!selectionDirty) return;
61
- selectionDirty = false;
62
- sections?.remember();
63
- }
64
- let drag: { id: number; kind: 'pointer' | 'touch'; motion: CarouselDrag; scroll?: CarouselScrollDrag } | undefined;
65
- function writeScroll(position: number) {
66
- markStageScrollInput('touch');
67
- window.scrollTo({ top: position, behavior: 'instant' });
68
- }
69
- function stopScrollMomentum() {
70
- cancelAnimationFrame(scrollFrame);
71
- scrollFrame = 0;
72
- window.removeEventListener('touchstart', stopScrollMomentum, true);
73
- window.removeEventListener('pointerdown', stopScrollMomentum, true);
74
- window.removeEventListener('wheel', stopScrollMomentum, true);
75
- window.removeEventListener('keydown', stopScrollMomentum, true);
76
- window.removeEventListener('popstate', stopScrollMomentum);
77
- }
78
- function scrollMomentum(scroll: CarouselScrollDrag, velocity: number) {
79
- stopScrollMomentum();
80
- if (Math.abs(velocity) < 0.02 || matchMedia('(prefers-reduced-motion: reduce)').matches) return;
81
- const start = scroll.position;
82
- const started = performance.now();
83
- for (const name of ['touchstart', 'pointerdown', 'wheel', 'keydown'])
84
- window.addEventListener(name, stopScrollMomentum, { capture: true, passive: true });
85
- window.addEventListener('popstate', stopScrollMomentum);
86
- const advance = (now: number) => {
87
- if (ring?.closest('[data-catalog-transition]')) {
88
- stopScrollMomentum();
89
- return;
90
- }
91
- const sample = sampleCarouselScrollMomentum(start, velocity, now - started, scroll.maximum);
92
- writeScroll(sample.position);
93
- if (sample.finished) stopScrollMomentum();
94
- else scrollFrame = requestAnimationFrame(advance);
95
- };
96
- scrollFrame = requestAnimationFrame(advance);
97
- }
47
+ let wheelTimer: ReturnType<typeof setTimeout>;
48
+ let drag: { id: number; kind: 'pointer' | 'wheel'; motion: CarouselDrag; emphasis: CarouselDragEmphasis; x: number; y: number; time: number; touch: boolean } | undefined;
49
+ let wheelInput: CarouselWheelInput | undefined;
50
+ const currentEmphasis = () => keys.map((_, i) => emphasis?.[i] ?? carouselEmphasis(i - phase));
51
+ const blocked = () => !!ring?.closest('[data-catalog-transition]');
98
52
  function invalidate() {
99
- window.dispatchEvent(new Event(CATALOG_POSE_CHANGED));
53
+ if (Math.abs(phase - windowPhase) > 0.75) windowPhase = Math.round(phase);
54
+ void tick().then(() => { if (mounted) window.dispatchEvent(new Event(CATALOG_POSE_CHANGED)); });
55
+ }
56
+ function measureLayout() {
57
+ if (!ring) return;
58
+ const { width, height, left } = ring.getBoundingClientRect();
59
+ layout = { width, height, left, viewportWidth: document.documentElement.clientWidth };
60
+ invalidate();
61
+ }
62
+ function commit(key: string | undefined) {
63
+ const changed = key !== selected;
64
+ requested = key;
65
+ if (changed) {
66
+ sections?.remember();
67
+ const item = list.find(item => carouselKey(item) === key);
68
+ if (item && key) onselectionchange?.({ itemKey: key, spatialElementId: item.id });
69
+ }
100
70
  }
101
71
  function releaseDrag() {
72
+ ring?.closest('section')?.removeAttribute('data-carousel-dragging');
73
+ clearTimeout(wheelTimer);
102
74
  const current = drag;
103
75
  drag = undefined;
76
+ wheelInput = undefined;
77
+ window.removeEventListener('pointermove', pointermove);
104
78
  window.removeEventListener('pointerup', pointerup);
105
- window.removeEventListener('touchstart', multitouch);
106
- window.removeEventListener('touchmove', touchmove);
107
- window.removeEventListener('touchend', touchend);
108
- window.removeEventListener('touchcancel', touchcancel);
109
- if (current?.kind === 'pointer' && ring?.hasPointerCapture(current.id))
110
- ring.releasePointerCapture(current.id);
111
- }
112
- function settle() {
113
- cancelAnimationFrame(frame);
114
- frame = 0;
115
- releaseDrag();
116
- phase = Math.max(0, keys.indexOf(selected ?? ''));
117
- announced = selected;
118
- void tick().then(invalidate);
119
- rememberSelection();
79
+ window.removeEventListener('pointercancel', pointercancel);
80
+ if (current?.kind === 'pointer' && ring?.hasPointerCapture(current.id)) ring.releasePointerCapture(current.id);
120
81
  }
121
- function animate(target: number, velocity?: number) {
82
+ // One clock drives the turntable and foreground reveal. No scrollLeft writes,
83
+ // snap handoff or velocity overshoot can move the destination sideways first.
84
+ function animate(target: number, reveal = false, velocity = 0) {
122
85
  cancelAnimationFrame(frame);
123
- frame = 0;
124
- const start = phase;
86
+ const start = phase, initial = reveal ? currentEmphasis() : undefined;
87
+ if (!reveal) emphasis = undefined;
125
88
  const started = performance.now();
126
- if (
127
- (velocity === undefined && Math.abs(target - start) > 1.5) ||
128
- !visible ||
129
- document.hidden ||
130
- matchMedia('(prefers-reduced-motion: reduce)').matches
131
- ) {
132
- phase = target;
133
- announced = selected;
134
- invalidate();
135
- rememberSelection();
136
- return;
137
- }
89
+ const duration = reveal ? 240 : Math.min(600, 280 + Math.abs(target - start) * 40);
90
+ const reduced = document.hidden || matchMedia('(prefers-reduced-motion: reduce)').matches;
138
91
  const advance = (now: number) => {
139
- if (ring?.closest('[data-catalog-transition]')) {
140
- frame = 0;
141
- return;
142
- }
143
- const elapsed = now - started;
144
- const spring = velocity === undefined ? undefined : sampleCarouselSpring(start, velocity, target, elapsed);
145
- const t = Math.min(1, elapsed / 320);
146
- const finished = spring
147
- ? (Math.abs(spring.phase - target) < 0.001 && Math.abs(spring.velocity) < 0.00005) || elapsed >= 1000
148
- : t >= 1;
149
- phase = finished ? target : spring
150
- ? clampCarouselPhase(spring.phase, keys.length)
151
- : start + (target - start) * (1 - (1 - t) ** 2);
152
- void tick().then(invalidate);
92
+ frame = 0;
93
+ if (blocked()) return;
94
+ // A queued frame timestamp can precede the release event within that frame.
95
+ const t = reduced ? 1 : Math.max(0, Math.min(1, (now - started) / duration));
96
+ const inertia = !reduced && velocity * (target - start) > 0
97
+ ? sampleCarouselInertia(start, velocity, target, now - started) : undefined;
98
+ const amount = inertia?.progress ?? 1 - (1 - t) ** 2;
99
+ // A nearby endpoint can absorb the horizontal speed in one frame. Keep
100
+ // foreground travel continuous, starting now, even in that limiting case.
101
+ const revealAmount = inertia ? Math.min(amount, 1 - (1 - t) ** 2) : amount;
102
+ const finished = inertia ? inertia.finished && t === 1 : t === 1;
103
+ phase = inertia?.phase ?? start + (target - start) * amount;
104
+ if (initial) emphasis = initial.map((value, i) => ({
105
+ advance: value.advance * (1 - revealAmount) + (i === target ? revealAmount : 0),
106
+ panel: value.panel * (1 - revealAmount) + (i === target ? revealAmount : 0)
107
+ }));
108
+ if (finished) { emphasis = undefined; announced = selected; }
109
+ invalidate();
153
110
  if (!finished) frame = requestAnimationFrame(advance);
154
- else {
155
- frame = 0;
156
- announced = selected;
157
- rememberSelection();
158
- }
159
111
  };
160
- frame = requestAnimationFrame(advance);
112
+ if (reduced) advance(started); else frame = requestAnimationFrame(advance);
113
+ }
114
+ function beginDrag(id: number, kind: 'pointer' | 'wheel', x: number, y = 0, touch = false) {
115
+ // A tap or zero wheel sample must not interrupt a running selection.
116
+ const time = performance.now();
117
+ drag = { id, kind, x, y, touch, time, motion: new CarouselDrag(x, phase, time), emphasis: new CarouselDragEmphasis(phase, currentEmphasis()) };
118
+ clearTimeout(clickTimer);
119
+ suppressClick = false;
120
+ }
121
+ function moveDrag(x: number) {
122
+ if (!drag) return;
123
+ if (!drag.motion.active) {
124
+ drag.motion = new CarouselDrag(drag.x, phase, drag.time);
125
+ drag.emphasis = new CarouselDragEmphasis(phase, currentEmphasis());
126
+ }
127
+ drag.motion.move(x, performance.now(), keys.length);
128
+ if (!drag.motion.active) return;
129
+ if (drag.kind === 'pointer' && !drag.touch) ring.closest('section')?.setAttribute('data-carousel-dragging', '');
130
+ cancelAnimationFrame(frame);
131
+ suppressClick = true;
132
+ phase = drag.motion.phase;
133
+ emphasis = drag.emphasis.move(phase);
134
+ invalidate();
135
+ }
136
+ function endDrag(x?: number, inertia = false) {
137
+ if (!drag) return;
138
+ const { motion, touch, kind } = drag;
139
+ // An idle timeout detects wheel release after the fact; use the final
140
+ // sample's time so this bookkeeping delay does not discard its velocity.
141
+ const wheelRelease = kind === 'wheel' && inertia && (wheelInput?.samples ?? 0) > 1;
142
+ const release = motion.release(wheelRelease ? wheelInput!.lastTime! : performance.now(), keys.length, x);
143
+ const active = motion.active;
144
+ if (active) {
145
+ phase = motion.phase;
146
+ emphasis = drag.emphasis.move(phase);
147
+ }
148
+ const velocity = inertia && (kind === 'pointer' || wheelRelease) && Math.abs(release.velocity) >= 0.0005 &&
149
+ !matchMedia('(prefers-reduced-motion: reduce)').matches ? release.velocity : 0;
150
+ releaseDrag();
151
+ if (active) {
152
+ const target = velocity ? release.target : Math.round(clampCarouselPhase(phase, keys.length));
153
+ commit(keys[target]);
154
+ animate(target, true, velocity);
155
+ }
156
+ clearTimeout(clickTimer);
157
+ clickTimer = setTimeout(() => { suppressClick = false; }, touch ? 400 : 0);
158
+ }
159
+ function canStartDrag(target: EventTarget | null, touch = false) {
160
+ if (!(target instanceof Element) || target.closest('.controls, .carousel-arrows, input, textarea, select, [contenteditable]')) return false;
161
+ return touch || !target.closest('a, button') || !!target.closest('.spatial-element-target');
161
162
  }
162
163
  function pointerdown(event: PointerEvent) {
163
- if (
164
- event.pointerType === 'touch' ||
165
- drag ||
166
- list.length < 2 ||
167
- event.button !== 0 ||
168
- !(event.target as Element).closest('.spatial-element-visual')
169
- )
170
- return;
171
- beginDrag(event.pointerId, 'pointer', event.clientX);
164
+ if (!interactive || blocked() || list.length < 2) return;
165
+ if (!event.isPrimary) { if (drag?.kind === 'pointer') endDrag(); return; }
166
+ if (drag?.kind === 'wheel') endDrag();
167
+ const touch = event.pointerType !== 'mouse';
168
+ if (!touch && carouselTextHit(event.target, event.clientX, event.clientY)) return;
169
+ if (drag || event.button !== 0 || !canStartDrag(event.target, touch)) return;
170
+ if (!touch) event.preventDefault();
171
+ beginDrag(event.pointerId, 'pointer', event.clientX, event.clientY, touch);
172
+ window.addEventListener('pointermove', pointermove);
172
173
  window.addEventListener('pointerup', pointerup);
174
+ window.addEventListener('pointercancel', pointercancel);
173
175
  }
174
176
  function pointermove(event: PointerEvent) {
175
- if (drag?.kind !== 'pointer' || drag.id !== event.pointerId) return;
177
+ if (drag?.kind !== 'pointer' || drag.id !== event.pointerId || blocked()) return;
178
+ if (drag.touch && !drag.motion.active && Math.abs(event.clientX - drag.x) <= Math.abs(event.clientY - drag.y) * 1.2) return;
176
179
  moveDrag(event.clientX);
177
- if (drag.motion.active && !ring.hasPointerCapture(event.pointerId)) ring.setPointerCapture(event.pointerId);
180
+ if (drag?.motion.active && !ring.hasPointerCapture(event.pointerId)) ring.setPointerCapture(event.pointerId);
178
181
  }
179
182
  function pointerup(event: PointerEvent) {
180
183
  if (drag?.kind !== 'pointer' || drag.id !== event.pointerId) return;
181
- endDrag(false, event.clientX);
184
+ // Do not turn a native vertical gesture or a tap into a horizontal release.
185
+ endDrag(drag.motion.active ? event.clientX : undefined, true);
182
186
  }
183
- function beginDrag(id: number, kind: 'pointer' | 'touch', x: number, y?: number) {
184
- cancelAnimationFrame(frame);
185
- stopScrollMomentum();
186
- frame = 0;
187
- clearTimeout(clickTimer);
188
- suppressClick = false;
189
- const now = performance.now();
190
- drag = {
191
- id, kind, motion: new CarouselDrag(x, phase, now),
192
- scroll: y === undefined ? undefined : new CarouselScrollDrag(y, window.scrollY,
193
- Math.max(0, document.documentElement.scrollHeight - window.innerHeight), now)
194
- };
187
+ function pointercancel(event: PointerEvent) {
188
+ if (drag?.kind === 'pointer' && drag.id === event.pointerId) endDrag();
195
189
  }
196
- function moveDrag(x: number, y?: number) {
197
- if (!drag) return;
198
- const now = performance.now();
199
- drag.motion.move(x, now, keys.length);
200
- if (y !== undefined) drag.scroll?.move(y, now);
201
- if (!drag.motion.active && !drag.scroll?.active) return;
202
- suppressClick = true;
203
- // Touch input can arrive faster than rendering. Commit only once per animation frame.
204
- if (!frame) frame = requestAnimationFrame(() => {
205
- frame = 0;
206
- if (!drag) return;
207
- phase = drag.motion.phase;
208
- if (drag.scroll?.active) writeScroll(drag.scroll.position);
209
- void tick().then(invalidate);
210
- });
190
+ function wheel(event: WheelEvent) {
191
+ if (!interactive || blocked() || list.length < 2 || event.ctrlKey || (drag && drag.kind !== 'wheel')) return;
192
+ const scale = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? ring.clientWidth : 1;
193
+ const dx = (event.shiftKey && !event.deltaX ? event.deltaY : event.deltaX) * scale;
194
+ const dy = event.shiftKey && !event.deltaX ? 0 : event.deltaY * scale;
195
+ if (!drag && (!dx || Math.abs(dx) <= Math.abs(dy) * 1.2)) return;
196
+ if (event.cancelable) event.preventDefault();
197
+ // Newer browsers identify the platform's inertial tail. Finish once and
198
+ // ignore that tail; never add a second fling or reopen the withdrawn panel.
199
+ if ((event as WheelEvent & { momentum?: boolean }).momentum === true) {
200
+ if (drag?.kind === 'wheel') endDrag(undefined, true);
201
+ return;
202
+ }
203
+ if (!dx && !drag) return;
204
+ if (!drag) { beginDrag(0, 'wheel', 0); wheelInput = new CarouselWheelInput(); }
205
+ if (!wheelInput) return;
206
+ wheelInput.move(dx, performance.now());
207
+ moveDrag(wheelInput.x);
208
+ clearTimeout(wheelTimer);
209
+ wheelTimer = setTimeout(() => { if (drag?.kind === 'wheel') endDrag(undefined, true); }, wheelInput.idleMs);
211
210
  }
212
- function endDrag(cancelled = false, x?: number, y?: number) {
213
- if (!drag) return;
214
- const { motion, kind, scroll } = drag;
215
- const now = performance.now();
216
- const release = motion.release(now, keys.length, x);
217
- const scrollVelocity = scroll?.release(now, y) ?? 0;
218
- if (motion.active || scroll?.active) suppressClick = true;
219
- cancelAnimationFrame(frame);
220
- frame = 0;
221
- phase = motion.phase;
222
- if (scroll?.active) writeScroll(scroll.position);
211
+ function select(key: string | undefined) {
223
212
  releaseDrag();
224
- const momentum = !cancelled && !matchMedia('(prefers-reduced-motion: reduce)').matches;
225
- if (motion.active) select(keys[momentum ? release.target : Math.round(phase)], momentum ? release.velocity : 0);
226
- else animate(Math.max(0, keys.indexOf(selected ?? '')));
227
- if (!cancelled && scroll?.active) scrollMomentum(scroll, scrollVelocity);
228
- clearTimeout(clickTimer);
229
- // Cover compatibility clicks after touch release; a new gesture always clears this.
230
- clickTimer = setTimeout(() => (suppressClick = false), kind === 'touch' ? 400 : 0);
213
+ commit(key);
214
+ if (interactive) animate(Math.max(0, keys.indexOf(key ?? '')));
215
+ else scrollNative(key, true);
231
216
  }
232
- function pointercancel(event?: PointerEvent) {
233
- // Native pinch zoom may cancel PointerEvents; TouchEvents own gesture cleanup.
234
- if (event?.pointerType === 'touch') return;
235
- stopScrollMomentum();
236
- releaseDrag();
237
- clearTimeout(clickTimer);
238
- clickTimer = setTimeout(() => (suppressClick = false), 400);
239
- animate(Math.max(0, keys.indexOf(selected ?? '')));
240
- }
241
- function touchstart(event: TouchEvent) {
242
- if (drag || event.touches.length !== 1 ||
243
- !(event.target as Element).closest('.spatial-element-visual')) return;
244
- const touch = event.touches[0];
245
- beginDrag(touch.identifier, 'touch', touch.clientX, touch.clientY);
246
- window.addEventListener('touchstart', multitouch, { passive: true });
247
- window.addEventListener('touchmove', touchmove, { passive: true });
248
- window.addEventListener('touchend', touchend, { passive: true });
249
- window.addEventListener('touchcancel', touchcancel, { passive: true });
250
- }
251
- function multitouch(event: TouchEvent) {
252
- if (drag?.kind === 'touch' && event.touches.length > 1) endDrag(true);
253
- }
254
- function touchmove(event: TouchEvent) {
255
- if (drag?.kind !== 'touch') return;
256
- if (event.touches.length !== 1) return endDrag(true);
257
- const touch = event.touches[0];
258
- if (touch.identifier === drag.id) moveDrag(touch.clientX, touch.clientY);
259
- }
260
- function touchend(event: TouchEvent) {
261
- if (drag?.kind !== 'touch') return;
262
- const touch = Array.from(event.changedTouches).find((touch) => touch.identifier === drag?.id);
263
- if (touch) endDrag(false, touch.clientX, touch.clientY);
264
- }
265
- function touchcancel() {
266
- if (drag?.kind === 'touch') endDrag(true);
217
+ function scrollNative(key: string | undefined, smooth = false) {
218
+ if (!ring || !keys.length || interactive) return;
219
+ const index = Math.max(0, keys.indexOf(key ?? ''));
220
+ const seat = (index - initialIndex + keys.length) % keys.length;
221
+ ring.scrollTo({ left: seat * ring.clientWidth, behavior: smooth && !matchMedia('(prefers-reduced-motion: reduce)').matches ? 'smooth' : 'instant' });
267
222
  }
268
- const keys = $derived(list.map(carouselKey));
269
- const selected = $derived(resolveCarouselSelection(keys, requested ?? initialItemKey));
270
- $effect(() => {
271
- // Data reordering/removal changes indices, never the stable selection identity.
272
- const signature = JSON.stringify(keys);
273
- if (interactive)
274
- untrack(() => {
275
- if (previousKeys !== undefined && previousKeys !== signature) selectionDirty = true;
276
- previousKeys = signature;
277
- settle();
278
- });
279
- });
280
- function select(key: string | undefined, velocity?: number) {
281
- selectionDirty = true;
282
- requested = key;
283
- // Persist in the current entry before a possible popstate changes the history index.
284
- rememberSelection();
285
- const target = Math.max(0, keys.indexOf(key ?? ''));
286
- animate(target, velocity);
287
- const spatialElement = list.find((item) => carouselKey(item) === selected);
288
- if (spatialElement && selected) onselectionchange?.({ itemKey: selected, spatialElementId: spatialElement.id });
223
+ function nativeScroll() {
224
+ if (interactive || nativeFrame || !keys.length) return;
225
+ nativeFrame = requestAnimationFrame(() => {
226
+ nativeFrame = 0;
227
+ if (interactive) return;
228
+ const seat = Math.round(ring.scrollLeft / Math.max(1, ring.clientWidth));
229
+ const index = (seat + initialIndex) % keys.length;
230
+ phase = windowPhase = index;
231
+ announced = keys[index];
232
+ commit(keys[index]);
233
+ });
289
234
  }
290
235
  function keydown(event: KeyboardEvent) {
291
236
  const step = event.key === 'ArrowRight' ? 1 : event.key === 'ArrowLeft' ? -1 : 0;
@@ -295,134 +240,144 @@
295
240
  else return;
296
241
  event.preventDefault();
297
242
  }
243
+ function resetMotion() {
244
+ cancelAnimationFrame(frame);
245
+ cancelAnimationFrame(nativeFrame);
246
+ frame = nativeFrame = 0;
247
+ releaseDrag();
248
+ phase = windowPhase = Math.max(0, keys.indexOf(selected ?? ''));
249
+ emphasis = undefined;
250
+ announced = selected;
251
+ invalidate();
252
+ }
253
+ $effect(() => {
254
+ const enhanced = interactive, signature = JSON.stringify(keys);
255
+ untrack(() => {
256
+ if (!mounted) return;
257
+ const token = ++generation;
258
+ resetMotion();
259
+ void tick().then(() => {
260
+ if (!mounted || token !== generation) return;
261
+ if (enhanced) ring.scrollLeft = 0;
262
+ else {
263
+ for (const panel of ring.querySelectorAll<HTMLElement>('.summary')) panel.style.removeProperty('transform');
264
+ for (const target of ring.querySelectorAll<HTMLElement>('.spatial-element-target'))
265
+ for (const property of ['left', 'top', 'width', 'height', 'max-width']) target.style.removeProperty(property);
266
+ scrollNative(selected);
267
+ }
268
+ measureLayout();
269
+ });
270
+ });
271
+ });
298
272
  onMount(() => {
299
- // Section's child snippet can clear bind:this before this mount cleanup runs.
273
+ mounted = true;
300
274
  const carouselRing = ring;
301
- interactive = true;
302
- // The model owns both single-finger axes; passive events still allow native pinch zoom.
303
- carouselRing.addEventListener('touchstart', touchstart, { passive: true });
275
+ const nativeSeat = Math.round(ring.scrollLeft / Math.max(1, ring.clientWidth));
276
+ const nativeInitialKey = keys[(nativeSeat + initialIndex) % Math.max(1, keys.length)];
277
+ let restored = false;
304
278
  const release = sections?.register(section.id, {
305
279
  read: () => selected,
306
- restore: (key) => {
307
- stopScrollMomentum();
308
- selectionDirty = false;
309
- requested = resolveCarouselSelection(keys, key ?? initialItemKey);
310
- cancelAnimationFrame(frame);
311
- frame = 0;
312
- releaseDrag();
313
- phase = Math.max(0, keys.indexOf(requested ?? ''));
314
- announced = requested;
315
- }
316
- });
317
- const observer = new IntersectionObserver(([entry]) => {
318
- visible = entry.isIntersecting;
319
- // The same touch must keep scrolling after carrying the carousel out of view.
320
- if (!visible && drag?.kind !== 'touch') {
321
- settle();
280
+ restore: key => {
281
+ requested = resolveCarouselSelection(keys, key ?? (!restored && !interactive ? nativeInitialKey : initialItemKey));
282
+ restored = true;
283
+ resetMotion();
284
+ void tick().then(() => { if (mounted) scrollNative(requested); });
322
285
  }
323
286
  });
287
+ measureLayout();
288
+ const observer = new ResizeObserver(measureLayout);
324
289
  observer.observe(carouselRing);
325
- let sizingFrame = 0;
326
- const measure = () => {
327
- sizingFrame = 0;
328
- const heights = [...carouselRing.querySelectorAll<HTMLElement>('.summary')].map(
329
- (panel) => panel.offsetHeight
330
- );
331
- const contentHeight = Math.max(0, ...heights);
332
- const height =
333
- carouselRing.clientWidth < 700 ? 408 + contentHeight : Math.max(560, contentHeight + 64);
334
- const value = height + 'px';
335
- if (carouselRing.style.getPropertyValue('--carousel-height') !== value)
336
- carouselRing.style.setProperty('--carousel-height', value);
337
- };
338
- const scheduleSize = () => {
339
- if (!sizingFrame) sizingFrame = requestAnimationFrame(measure);
340
- };
341
- const sizing = new ResizeObserver(scheduleSize);
342
- const contentChanges = new MutationObserver(() => {
343
- sizing.disconnect();
344
- sizing.observe(carouselRing);
345
- for (const panel of carouselRing.querySelectorAll('.summary')) sizing.observe(panel);
346
- scheduleSize();
347
- });
348
- contentChanges.observe(carouselRing, { childList: true, subtree: true });
349
- sizing.observe(carouselRing);
350
- for (const panel of carouselRing.querySelectorAll('.summary')) sizing.observe(panel);
351
- const stop = () => pointercancel();
352
- let viewportWidth = window.innerWidth;
353
- const resize = () => {
354
- // Mobile browser chrome resizes the height during scrolling; keep that gesture alive.
355
- if (window.innerWidth !== viewportWidth) stop();
356
- viewportWidth = window.innerWidth;
357
- };
358
- window.addEventListener('resize', resize);
290
+ const dragSection = ring.closest('section')!;
291
+ dragSection.addEventListener('wheel', wheel, { passive: false });
292
+ const stop = () => { if (drag) endDrag(); };
293
+ const hidden = () => { if (document.hidden) resetMotion(); };
294
+ const escape = (event: KeyboardEvent) => { if (event.key === 'Escape') stop(); };
359
295
  window.addEventListener('blur', stop);
360
- const hidden = () => {
361
- if (document.hidden) {
362
- stopScrollMomentum();
363
- settle();
364
- }
365
- };
366
- document.addEventListener('visibilitychange', hidden);
367
- const escape = (event: KeyboardEvent) => {
368
- if (event.key === 'Escape') stop();
369
- };
370
296
  window.addEventListener('keydown', escape);
297
+ window.addEventListener('resize', measureLayout);
298
+ document.addEventListener('visibilitychange', hidden);
371
299
  return () => {
300
+ mounted = false;
301
+ generation++;
372
302
  cancelAnimationFrame(frame);
373
- stopScrollMomentum();
303
+ cancelAnimationFrame(nativeFrame);
374
304
  clearTimeout(clickTimer);
375
305
  releaseDrag();
376
- carouselRing.removeEventListener('touchstart', touchstart);
377
306
  observer.disconnect();
378
- sizing.disconnect();
379
- contentChanges.disconnect();
380
- cancelAnimationFrame(sizingFrame);
381
307
  release?.();
382
- window.removeEventListener('resize', resize);
308
+ dragSection.removeEventListener('wheel', wheel);
383
309
  window.removeEventListener('blur', stop);
384
310
  window.removeEventListener('keydown', escape);
311
+ window.removeEventListener('resize', measureLayout);
385
312
  document.removeEventListener('visibilitychange', hidden);
386
313
  };
387
314
  });
388
315
  </script>
389
316
 
390
- <Section {section} presentation="list">
317
+ <Section {section} presentation="list" class="carousel-drag-section"
318
+ ondragstart={(event) => { if (interactive && canStartDrag(event.target)) event.preventDefault(); }}
319
+ onpointerdown={pointerdown}
320
+ onclickcapture={(event) => { if (suppressClick) { event.preventDefault(); event.stopPropagation(); } }}
321
+ onlostpointercapture={(event) => {
322
+ // Touch starts with implicit capture on its hit target. Moving capture to
323
+ // the ring must not be mistaken for the end of that same gesture.
324
+ if (event.target === ring && drag?.kind === 'pointer' && drag.id === event.pointerId) endDrag();
325
+ }}>
326
+ {#if interactive}
327
+ <div class="drag-surface" aria-hidden="true" style:left={`${-layout.left}px`} style:width={`${layout.viewportWidth}px`}></div>
328
+ {/if}
391
329
  <div
392
330
  class="carousel"
393
331
  class:interactive
394
332
  class:populated={list.length > 0}
395
333
  data-carousel-section={section.id}
334
+ data-device-orientation=""
396
335
  >
336
+ <!-- svelte-ignore a11y_no_noninteractive_tabindex (The native scroll rail must be keyboard-scrollable without JavaScript.) -->
397
337
  <div
398
338
  class="ring"
339
+ id={`carousel-ring-${section.id}`}
340
+ tabindex={interactive ? undefined : 0}
399
341
  bind:this={ring}
400
- onpointerdown={pointerdown}
401
- onpointermove={pointermove}
402
- onpointerup={pointerup}
403
- onpointercancel={pointercancel}
404
- onlostpointercapture={() => {
405
- if (drag?.kind === 'pointer') pointercancel();
406
- }}
342
+ onscroll={nativeScroll}
407
343
  role="group"
408
344
  aria-label={section.title}
409
345
  >
410
- {#each list as spatialElement, index (carouselKey(spatialElement))}
346
+ {#each orderedItems as [index, spatialElement] (carouselKey(spatialElement))}
411
347
  <CarouselSpatialElement
412
348
  {spatialElement}
413
349
  sectionId={section.id}
414
350
  {presentation}
351
+ {layout}
415
352
  {index}
416
353
  count={list.length}
417
354
  {phase}
355
+ emphasis={emphasis?.[index]}
356
+ {focus}
418
357
  {windowPhase}
419
358
  selected={selected === carouselKey(spatialElement)}
420
359
  {interactive}
421
360
  onselect={() => {
422
361
  if (!suppressClick) select(carouselKey(spatialElement));
423
362
  }}
363
+ canActivate={() => !suppressClick}
424
364
  />
425
365
  {/each}
366
+ {#if interactive && list.length > 1}
367
+ <div class="carousel-arrows" role="group" aria-label="Carousel navigation"
368
+ style:opacity={arrowOpacity} inert={arrowOpacity < 0.05}>
369
+ <button type="button" class="previous" hidden={selected === keys[0]}
370
+ aria-label="Previous product" aria-controls={`carousel-ring-${section.id}`}
371
+ onclick={() => select(stepCarouselSelection(keys, selected, -1))}>
372
+ <svg viewBox="0 0 24 24" aria-hidden="true"><path d="m14 6-6 6 6 6" /></svg>
373
+ </button>
374
+ <button type="button" class="next" hidden={selected === keys.at(-1)}
375
+ aria-label="Next product" aria-controls={`carousel-ring-${section.id}`}
376
+ onclick={() => select(stepCarouselSelection(keys, selected, 1))}>
377
+ <svg viewBox="0 0 24 24" aria-hidden="true"><path d="m10 6 6 6-6 6" /></svg>
378
+ </button>
379
+ </div>
380
+ {/if}
426
381
  </div>
427
382
  {#if interactive && list.length > 1}
428
383
  <div class="controls" role="group" aria-label={`${section.title}: element selection`}>
@@ -430,7 +385,7 @@
430
385
  <button
431
386
  onkeydown={keydown}
432
387
  aria-label={spatialElement.eyebrow}
433
- aria-pressed={selected === carouselKey(spatialElement)}
388
+ aria-pressed={indicated === carouselKey(spatialElement)}
434
389
  onclick={() => select(carouselKey(spatialElement))}><span aria-hidden="true"></span></button
435
390
  >
436
391
  {/each}
@@ -443,25 +398,89 @@
443
398
  </Section>
444
399
 
445
400
  <style>
401
+ :global(.carousel-drag-section) { position: relative; }
402
+ :global(.carousel-drag-section:has(.interactive)) { touch-action: pan-y pinch-zoom; }
403
+ :global(.carousel-drag-section > .section-kicker) { pointer-events: none; }
404
+ .drag-surface {
405
+ position: absolute;
406
+ top: 0;
407
+ bottom: 0;
408
+ pointer-events: auto;
409
+ touch-action: pan-y pinch-zoom;
410
+ cursor: grab;
411
+ }
412
+ :global(.carousel.interactive .summary) { cursor: grab; }
413
+ :global(.carousel.interactive .summary a),
414
+ :global(.carousel.interactive .summary button) { cursor: pointer; }
415
+ :global(.carousel.interactive [data-carousel-text-hit]) { cursor: text; }
416
+ :global(.carousel-drag-section[data-carousel-dragging]),
417
+ :global(.carousel-drag-section[data-carousel-dragging] *) { cursor: grabbing !important; user-select: none; }
418
+ .carousel.interactive { pointer-events: none; }
446
419
  .carousel {
447
420
  pointer-events: auto;
448
421
  margin-top: 24px;
449
422
  }
450
423
  .ring {
451
424
  container-type: inline-size;
425
+ display: grid;
426
+ grid-auto-flow: column;
427
+ grid-auto-columns: 100%;
452
428
  position: relative;
429
+ overflow-x: auto;
430
+ scroll-snap-type: x mandatory;
431
+ overscroll-behavior-x: contain;
432
+ scrollbar-width: auto;
433
+ scrollbar-color: var(--spatial-element-accent) transparent;
453
434
  touch-action: manipulation;
454
435
  }
455
- .interactive.populated .ring {
456
- min-height: var(--carousel-height, 560px);
436
+ .ring:focus-visible { outline: 2px solid var(--spatial-element-accent); outline-offset: 4px; }
437
+ .interactive .ring {
438
+ scrollbar-width: none;
439
+ grid-auto-flow: row;
440
+ grid-template-columns: 100%;
441
+ overflow: visible;
442
+ scroll-snap-type: none;
443
+ }
444
+ .carousel-arrows {
445
+ position: absolute;
446
+ left: 12%;
447
+ right: 50%;
448
+ top: 50%;
449
+ transform: translateY(-50%);
450
+ z-index: 1500;
451
+ display: flex;
452
+ justify-content: space-between;
453
+ pointer-events: none;
454
+ }
455
+ .carousel-arrows button {
456
+ pointer-events: auto;
457
+ width: 44px;
458
+ height: 44px;
459
+ display: grid;
460
+ place-items: center;
461
+ padding: 8px;
462
+ border: 0;
463
+ border-radius: 50%;
464
+ color: var(--spatial-element-accent);
465
+ background: transparent;
466
+ cursor: pointer;
467
+ }
468
+ .carousel-arrows button[hidden] { visibility: hidden; pointer-events: none; }
469
+ .carousel-arrows button:hover { background: color-mix(in srgb, var(--spatial-element-accent) 12%, transparent); }
470
+ .carousel-arrows button:focus-visible { outline: 2px solid var(--spatial-element-accent); }
471
+ .carousel-arrows svg { width: 24px; height: 24px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
472
+ @container (max-width: 700px) {
473
+ .carousel-arrows { left: 0; right: 0; top: 180px; }
457
474
  }
458
475
  .controls {
476
+ position: relative;
459
477
  display: flex;
460
478
  justify-content: center;
461
479
  flex-wrap: wrap;
462
480
  margin-top: 16px;
463
481
  }
464
482
  .controls button {
483
+ pointer-events: auto;
465
484
  display: grid;
466
485
  place-items: center;
467
486
  width: 44px;