@spatial-elements/sveltekit 1.0.0-beta.4 → 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.
Files changed (43) hide show
  1. package/README.md +6 -2
  2. package/dist/catalog/catalogTransition.css +12 -0
  3. package/dist/index.d.ts +3 -0
  4. package/dist/index.js +2 -0
  5. package/dist/spatial-element/BrandStageShell.svelte +9 -59
  6. package/dist/spatial-element/BrandStageShell.svelte.d.ts +2 -0
  7. package/dist/spatial-element/CarouselSection.svelte +339 -323
  8. package/dist/spatial-element/CarouselSection.svelte.d.ts +2 -7
  9. package/dist/spatial-element/CarouselSpatialElement.svelte +142 -127
  10. package/dist/spatial-element/CarouselSpatialElement.svelte.d.ts +5 -1
  11. package/dist/spatial-element/ContentPage.svelte +2 -1
  12. package/dist/spatial-element/PointerHint.svelte +78 -0
  13. package/dist/spatial-element/PointerHint.svelte.d.ts +3 -0
  14. package/dist/spatial-element/SpatialElementCard.svelte +68 -2
  15. package/dist/spatial-element/SpatialElementHelp.svelte +23 -14
  16. package/dist/spatial-element/SpatialElementMediaRail.svelte +22 -3
  17. package/dist/spatial-element/SpatialElementPage.svelte +2 -4
  18. package/dist/spatial-element/SpatialElementSummaryContent.svelte +182 -0
  19. package/dist/spatial-element/SpatialElementSummaryContent.svelte.d.ts +18 -0
  20. package/dist/spatial-element/SpatialElementSummaryPanel.svelte +29 -375
  21. package/dist/spatial-element/SpatialElementTabs.svelte +2 -1
  22. package/dist/spatial-element/SpatialElementViewToggle.svelte +53 -0
  23. package/dist/spatial-element/SpatialElementViewToggle.svelte.d.ts +8 -0
  24. package/dist/spatial-element/SpatialIconButton.svelte +2 -1
  25. package/dist/spatial-element/brandContext.d.ts +1 -1
  26. package/dist/spatial-element/brandContext.js +1 -1
  27. package/dist/spatial-element/carouselTextHit.d.ts +2 -0
  28. package/dist/spatial-element/carouselTextHit.js +17 -0
  29. package/dist/spatial-element/spatialThemeStyle.d.ts +3 -0
  30. package/dist/spatial-element/spatialThemeStyle.js +48 -0
  31. package/dist/spatial-element/truncatedTitle.d.ts +5 -0
  32. package/dist/spatial-element/truncatedTitle.js +28 -0
  33. package/dist/stage/ButtonGroup.svelte +163 -0
  34. package/dist/stage/ButtonGroup.svelte.d.ts +24 -0
  35. package/dist/stage/Panel.svelte +24 -9
  36. package/dist/stage/Stage.svelte +91 -5
  37. package/dist/stage/Stage.svelte.d.ts +2 -0
  38. package/dist/stage/StageViewport.svelte +7 -1
  39. package/dist/stage/authoredStyle.d.ts +4 -0
  40. package/dist/stage/authoredStyle.js +17 -0
  41. package/dist/stage/buttonGroup.d.ts +9 -0
  42. package/dist/stage/buttonGroup.js +1 -0
  43. package/package.json +2 -2
@@ -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,132 +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
- interactive = true;
300
- // The model owns both single-finger axes; passive events still allow native pinch zoom.
301
- ring.addEventListener('touchstart', touchstart, { passive: true });
269
+ mounted = true;
270
+ const carouselRing = ring;
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;
302
274
  const release = sections?.register(section.id, {
303
275
  read: () => selected,
304
- restore: (key) => {
305
- stopScrollMomentum();
306
- selectionDirty = false;
307
- requested = resolveCarouselSelection(keys, key ?? initialItemKey);
308
- cancelAnimationFrame(frame);
309
- frame = 0;
310
- releaseDrag();
311
- phase = Math.max(0, keys.indexOf(requested ?? ''));
312
- announced = requested;
313
- }
314
- });
315
- const observer = new IntersectionObserver(([entry]) => {
316
- visible = entry.isIntersecting;
317
- // The same touch must keep scrolling after carrying the carousel out of view.
318
- if (!visible && drag?.kind !== 'touch') {
319
- 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); });
320
281
  }
321
282
  });
322
- observer.observe(ring);
323
- let sizingFrame = 0;
324
- const measure = () => {
325
- sizingFrame = 0;
326
- const heights = [...ring.querySelectorAll<HTMLElement>('.summary')].map(
327
- (panel) => panel.offsetHeight
328
- );
329
- const contentHeight = Math.max(0, ...heights);
330
- const height =
331
- ring.clientWidth < 700 ? 408 + contentHeight : Math.max(560, contentHeight + 64);
332
- const value = height + 'px';
333
- if (ring.style.getPropertyValue('--carousel-height') !== value)
334
- ring.style.setProperty('--carousel-height', value);
335
- };
336
- const scheduleSize = () => {
337
- if (!sizingFrame) sizingFrame = requestAnimationFrame(measure);
338
- };
339
- const sizing = new ResizeObserver(scheduleSize);
340
- const contentChanges = new MutationObserver(() => {
341
- sizing.disconnect();
342
- sizing.observe(ring);
343
- for (const panel of ring.querySelectorAll('.summary')) sizing.observe(panel);
344
- scheduleSize();
345
- });
346
- contentChanges.observe(ring, { childList: true, subtree: true });
347
- sizing.observe(ring);
348
- for (const panel of ring.querySelectorAll('.summary')) sizing.observe(panel);
349
- const stop = () => pointercancel();
350
- let viewportWidth = window.innerWidth;
351
- const resize = () => {
352
- // Mobile browser chrome resizes the height during scrolling; keep that gesture alive.
353
- if (window.innerWidth !== viewportWidth) stop();
354
- viewportWidth = window.innerWidth;
355
- };
356
- window.addEventListener('resize', resize);
283
+ measureLayout();
284
+ const observer = new ResizeObserver(measureLayout);
285
+ observer.observe(carouselRing);
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(); };
357
291
  window.addEventListener('blur', stop);
358
- const hidden = () => {
359
- if (document.hidden) {
360
- stopScrollMomentum();
361
- settle();
362
- }
363
- };
364
- document.addEventListener('visibilitychange', hidden);
365
- const escape = (event: KeyboardEvent) => {
366
- if (event.key === 'Escape') stop();
367
- };
368
292
  window.addEventListener('keydown', escape);
293
+ window.addEventListener('resize', measureLayout);
294
+ document.addEventListener('visibilitychange', hidden);
369
295
  return () => {
296
+ mounted = false;
297
+ generation++;
370
298
  cancelAnimationFrame(frame);
371
- stopScrollMomentum();
299
+ cancelAnimationFrame(nativeFrame);
372
300
  clearTimeout(clickTimer);
373
301
  releaseDrag();
374
- ring.removeEventListener('touchstart', touchstart);
375
302
  observer.disconnect();
376
- sizing.disconnect();
377
- contentChanges.disconnect();
378
- cancelAnimationFrame(sizingFrame);
379
303
  release?.();
380
- window.removeEventListener('resize', resize);
304
+ dragSection.removeEventListener('wheel', wheel);
381
305
  window.removeEventListener('blur', stop);
382
306
  window.removeEventListener('keydown', escape);
307
+ window.removeEventListener('resize', measureLayout);
383
308
  document.removeEventListener('visibilitychange', hidden);
384
309
  };
385
310
  });
386
311
  </script>
387
312
 
388
- <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}
389
325
  <div
390
326
  class="carousel"
391
327
  class:interactive
392
328
  class:populated={list.length > 0}
393
329
  data-carousel-section={section.id}
394
330
  >
331
+ <!-- svelte-ignore a11y_no_noninteractive_tabindex (The native scroll rail must be keyboard-scrollable without JavaScript.) -->
395
332
  <div
396
333
  class="ring"
334
+ id={`carousel-ring-${section.id}`}
335
+ tabindex={interactive ? undefined : 0}
397
336
  bind:this={ring}
398
- onpointerdown={pointerdown}
399
- onpointermove={pointermove}
400
- onpointerup={pointerup}
401
- onpointercancel={pointercancel}
402
- onlostpointercapture={() => {
403
- if (drag?.kind === 'pointer') pointercancel();
404
- }}
337
+ onscroll={nativeScroll}
405
338
  role="group"
406
339
  aria-label={section.title}
407
340
  >
408
- {#each list as spatialElement, index (carouselKey(spatialElement))}
341
+ {#each orderedItems as [index, spatialElement] (carouselKey(spatialElement))}
409
342
  <CarouselSpatialElement
410
343
  {spatialElement}
411
344
  sectionId={section.id}
412
345
  {presentation}
346
+ {layout}
413
347
  {index}
414
348
  count={list.length}
415
349
  {phase}
350
+ emphasis={emphasis?.[index]}
351
+ {focus}
416
352
  {windowPhase}
417
353
  selected={selected === carouselKey(spatialElement)}
418
354
  {interactive}
419
355
  onselect={() => {
420
356
  if (!suppressClick) select(carouselKey(spatialElement));
421
357
  }}
358
+ canActivate={() => !suppressClick}
422
359
  />
423
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}
424
376
  </div>
425
377
  {#if interactive && list.length > 1}
426
378
  <div class="controls" role="group" aria-label={`${section.title}: element selection`}>
@@ -428,7 +380,7 @@
428
380
  <button
429
381
  onkeydown={keydown}
430
382
  aria-label={spatialElement.eyebrow}
431
- aria-pressed={selected === carouselKey(spatialElement)}
383
+ aria-pressed={indicated === carouselKey(spatialElement)}
432
384
  onclick={() => select(carouselKey(spatialElement))}><span aria-hidden="true"></span></button
433
385
  >
434
386
  {/each}
@@ -441,25 +393,89 @@
441
393
  </Section>
442
394
 
443
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; }
444
414
  .carousel {
445
415
  pointer-events: auto;
446
416
  margin-top: 24px;
447
417
  }
448
418
  .ring {
449
419
  container-type: inline-size;
420
+ display: grid;
421
+ grid-auto-flow: column;
422
+ grid-auto-columns: 100%;
450
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;
451
429
  touch-action: manipulation;
452
430
  }
453
- .interactive.populated .ring {
454
- 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; }
455
469
  }
456
470
  .controls {
471
+ position: relative;
457
472
  display: flex;
458
473
  justify-content: center;
459
474
  flex-wrap: wrap;
460
475
  margin-top: 16px;
461
476
  }
462
477
  .controls button {
478
+ pointer-events: auto;
463
479
  display: grid;
464
480
  place-items: center;
465
481
  width: 44px;