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

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