@cloudlet/toast 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/CHANGELOG.md +165 -0
  2. package/README.md +3 -0
  3. package/dist/agent.d.ts.map +1 -1
  4. package/dist/agent.js +19 -15
  5. package/dist/agent.js.map +1 -1
  6. package/dist/center-react.d.ts +286 -0
  7. package/dist/center-react.d.ts.map +1 -0
  8. package/dist/center-react.js +2 -0
  9. package/dist/center.d.ts +3 -0
  10. package/dist/center.d.ts.map +1 -0
  11. package/dist/center.js +1 -0
  12. package/dist/core/agent-port.d.ts +2 -0
  13. package/dist/core/agent-port.d.ts.map +1 -1
  14. package/dist/core/agent-port.js +3 -0
  15. package/dist/core/agent-port.js.map +1 -1
  16. package/dist/react/card.d.ts +4 -0
  17. package/dist/react/card.d.ts.map +1 -1
  18. package/dist/react/card.js +3 -8
  19. package/dist/react/card.js.map +1 -1
  20. package/dist/react/center-backdrop.d.ts +69 -0
  21. package/dist/react/center-backdrop.d.ts.map +1 -0
  22. package/dist/react/center-backdrop.js +81 -0
  23. package/dist/react/center-backdrop.js.map +1 -0
  24. package/dist/react/center-clear.d.ts +16 -0
  25. package/dist/react/center-clear.d.ts.map +1 -0
  26. package/dist/react/center-clear.js +24 -0
  27. package/dist/react/center-clear.js.map +1 -0
  28. package/dist/react/center-gestures.d.ts +47 -0
  29. package/dist/react/center-gestures.d.ts.map +1 -0
  30. package/dist/react/center-gestures.js +74 -0
  31. package/dist/react/center-gestures.js.map +1 -0
  32. package/dist/react/center-motion.d.ts +174 -0
  33. package/dist/react/center-motion.d.ts.map +1 -0
  34. package/dist/react/center-motion.js +344 -0
  35. package/dist/react/center-motion.js.map +1 -0
  36. package/dist/react/center.d.ts +15 -0
  37. package/dist/react/center.d.ts.map +1 -0
  38. package/dist/react/center.js +1287 -0
  39. package/dist/react/center.js.map +1 -0
  40. package/dist/react/focus.d.ts +7 -0
  41. package/dist/react/focus.d.ts.map +1 -0
  42. package/dist/react/focus.js +14 -0
  43. package/dist/react/focus.js.map +1 -0
  44. package/dist/react/gestures.d.ts +33 -2
  45. package/dist/react/gestures.d.ts.map +1 -1
  46. package/dist/react/gestures.js +181 -149
  47. package/dist/react/gestures.js.map +1 -1
  48. package/dist/react/host.d.ts.map +1 -1
  49. package/dist/react/host.js +287 -283
  50. package/dist/react/host.js.map +1 -1
  51. package/dist/react/motion.d.ts +18 -11
  52. package/dist/react/motion.d.ts.map +1 -1
  53. package/dist/react/motion.js +6 -3
  54. package/dist/react/motion.js.map +1 -1
  55. package/dist/react/reduced.d.ts +24 -0
  56. package/dist/react/reduced.d.ts.map +1 -0
  57. package/dist/react/reduced.js +35 -0
  58. package/dist/react/reduced.js.map +1 -0
  59. package/dist/react/zoom.d.ts +12 -0
  60. package/dist/react/zoom.d.ts.map +1 -0
  61. package/dist/react/zoom.js +21 -0
  62. package/dist/react/zoom.js.map +1 -0
  63. package/dist/react.d.ts +4 -0
  64. package/dist/react.d.ts.map +1 -1
  65. package/dist/styles.css +1 -1
  66. package/package.json +2 -1
  67. package/src/agent.ts +11 -6
  68. package/src/center-react.ts +300 -0
  69. package/src/center.ts +27 -0
  70. package/src/core/agent-port.ts +3 -0
  71. package/src/react/card.tsx +5 -6
  72. package/src/react/center-backdrop.tsx +151 -0
  73. package/src/react/center-clear.ts +56 -0
  74. package/src/react/center-gestures.ts +143 -0
  75. package/src/react/center-motion.ts +504 -0
  76. package/src/react/center.tsx +1557 -0
  77. package/src/react/focus.ts +18 -0
  78. package/src/react/gestures.ts +127 -37
  79. package/src/react/host.tsx +17 -5
  80. package/src/react/motion.ts +16 -9
  81. package/src/react/reduced.ts +52 -0
  82. package/src/react/zoom.ts +26 -0
  83. package/src/react.ts +4 -0
@@ -0,0 +1,143 @@
1
+ import type { CenterMotion } from './center-motion.js';
2
+ import { createSwipe, decideRelease, rubberBand } from './gestures.js';
3
+ import type { SwipeCandidate, SwipeSession } from './gestures.js';
4
+ import { MOTION } from './motion.js';
5
+
6
+ /** What the center's swipes read from the panel at the moment they need it. */
7
+ interface CenterGestureOptions {
8
+ readonly motion: CenterMotion;
9
+ /** The column's width (CSS px): the drawer's threshold and, with `travel`, its full way. */
10
+ readonly width: () => number;
11
+ /** How far past its own width a closed card lies (`CENTER_MOTION.travel`). */
12
+ readonly travel: () => number;
13
+ /** The physical edge the drawer sits at: +1 right, -1 left (also in RTL). */
14
+ readonly edge: () => 1 | -1;
15
+ readonly open: () => boolean;
16
+ /** Asks the app to close the center (its `setOpen(false)`). */
17
+ readonly close: () => void;
18
+ /** The listed notification a card's motion key stands for, if it is still listed and can be dismissed. */
19
+ readonly idOf: (key: string) => string | null;
20
+ /** Asks the app to dismiss a notification (`onDismiss`). */
21
+ readonly dismiss: (id: string) => void;
22
+ /**
23
+ * Hands the release speed (px per second) and the side the card was swiped to (+1 right, -1 left)
24
+ * to the copy that leaves for a swiped card, should it leave.
25
+ */
26
+ readonly fling: (key: string, velocity: number, direction: 1 | -1) => void;
27
+ readonly now: () => number;
28
+ }
29
+
30
+ const towards = { negative: false, positive: true } as const;
31
+
32
+ /**
33
+ * The most speed (px/ms) a release short of its threshold springs back with: the drawer springs
34
+ * back open without passing closed on the way, whatever the swipe's own speed.
35
+ */
36
+ const RETURN_SPEED = 2;
37
+ const returnSpeed = (velocity: number) => Number.isFinite(velocity) ? Math.max(-RETURN_SPEED, Math.min(RETURN_SPEED, velocity)) : 0;
38
+
39
+ /**
40
+ * The notification center's swipes, on the Toaster's `createSwipe` and its thresholds
41
+ * (`MOTION.swipe`): sideways only, vertical stays the list's native scrolling.
42
+ *
43
+ * Towards the drawer's edge, anywhere on the column, the drawer follows the fingers (resisting
44
+ * outwards past open); let go past the threshold it asks the app to close and keeps the release
45
+ * speed for the closing spring, short of it it springs back open. Away from the edge on a card that
46
+ * can be dismissed, the card follows and fades; past the threshold the app is asked to dismiss it and
47
+ * springs back while the app decides; its copy flies on with the release speed when the app takes it
48
+ * out soon after, even from its place (a card the app keeps stays); a card of an expanded group
49
+ * swipes on its own. Away from the edge elsewhere, a
50
+ * collapsed stack included, nothing happens. A sideways trackpad stream over the
51
+ * panel never reaches the browser's back and forward swipe, and the rest of a committed stream is
52
+ * swallowed until it goes idle, even once the closing panel is inert. Reduced motion turns the
53
+ * swipes off; the buttons stay.
54
+ */
55
+ export function attachCenterGestures(root: HTMLElement, options: CenterGestureOptions) {
56
+ const { motion } = options;
57
+ const column = () => root.querySelector('.cloudlet-center-column');
58
+
59
+ function drawerSession(): SwipeSession {
60
+ const sign = options.edge();
61
+ const range = () => Math.max(1, options.width() + options.travel());
62
+ // The finger takes the drawer where it is, also in the middle of its spring.
63
+ motion.grab();
64
+ const from = Math.min(1, motion.value('p'));
65
+ const commits = (offset: number, velocity: number) => decideRelease(offset * sign, velocity * sign, options.width(), towards) !== 0;
66
+ return {
67
+ move(offset) {
68
+ if (!options.open()) return;
69
+ const p = from - offset * sign / range();
70
+ // Outwards past open the drawer resists.
71
+ motion.drag(p <= 1 ? p : 1 + rubberBand((p - 1) * range(), MOTION.swipe.resist) / range());
72
+ },
73
+ decide: commits,
74
+ end(offset, velocity) {
75
+ if (!options.open()) return;
76
+ // px/ms towards the edge → the position's speed in p per second.
77
+ const speed = (value: number) => -value * sign * 1000 / range();
78
+ // Released towards open with the swipe's own speed: when the app closes the center the spring
79
+ // turns from there, keeping it; when the app keeps it open the drawer settles back.
80
+ if (commits(offset, velocity)) {
81
+ motion.release(speed(velocity));
82
+ options.close();
83
+ return;
84
+ }
85
+ motion.release(speed(returnSpeed(velocity)));
86
+ },
87
+ cancel() { if (options.open()) motion.release(0); },
88
+ };
89
+ }
90
+
91
+ function cardSession(card: HTMLElement): SwipeSession | null {
92
+ const key = card.dataset.cloudletMotionKey;
93
+ const id = key ? options.idOf(key) : null;
94
+ if (!key || id === null) return null;
95
+ const sign = (options.edge() > 0 ? -1 : 1) as 1 | -1;
96
+ const width = card.offsetWidth || options.width();
97
+ const live = () => options.open() && card.isConnected;
98
+ const commits = (offset: number, velocity: number) => decideRelease(offset * sign, velocity * sign, width, towards) !== 0;
99
+ return {
100
+ move(offset) {
101
+ if (!live()) return;
102
+ // Towards the edge a card barely gives.
103
+ motion.dragCard(key, offset * sign >= 0 ? offset : rubberBand(offset, MOTION.swipe.resist));
104
+ },
105
+ decide: commits,
106
+ end(offset, velocity) {
107
+ if (!live()) return;
108
+ if (commits(offset, velocity)) {
109
+ options.fling(key, velocity * 1000, sign);
110
+ options.dismiss(id);
111
+ }
112
+ // The card springs back while the app decides; taken out soon after (the panel's fling
113
+ // window), it flies on from wherever the spring has taken it, with the swipe's speed.
114
+ motion.releaseCard(key, returnSpeed(velocity) * 1000);
115
+ },
116
+ cancel() { if (live()) motion.releaseCard(key, 0); },
117
+ };
118
+ }
119
+
120
+ function begin(target: Element): SwipeCandidate | null {
121
+ if (motion.reduced || !options.open() || !column()?.contains(target)) return null;
122
+ // A card of the list or of an expanded group; a collapsed stack is no card (it hides others).
123
+ const card = target.closest<HTMLElement>('.cloudlet-center-list .cloudlet-card[data-cloudlet-motion-key]:not([data-cloudlet-place])');
124
+ return {
125
+ x: true, y: false,
126
+ start: (_axis, direction) => direction === options.edge() ? drawerSession() : card ? cardSession(card) : null,
127
+ release() {},
128
+ };
129
+ }
130
+
131
+ const swipe = createSwipe(root, {
132
+ begin,
133
+ // Sideways streams over the open panel never turn into the browser's history swipe.
134
+ claimsWheel: target => options.open() && root.contains(target),
135
+ holdsStream: true,
136
+ now: options.now,
137
+ });
138
+ return {
139
+ /** Ends a running swipe; the swallowed rest of a committed trackpad stream goes on to its end. */
140
+ cancel() { if (swipe.active) swipe.cancel(); },
141
+ dispose: swipe.dispose,
142
+ };
143
+ }
@@ -0,0 +1,504 @@
1
+ import type { NotificationCenterMotionConstants, NotificationCenterMotionOverrides } from '../center-react.js';
2
+ import { spring, tween as tweenGenerator } from './generators.js';
3
+ import type { Generator } from './generators.js';
4
+
5
+ const critical = (stiffness: number, mass = 1) => 2 * Math.sqrt(stiffness * mass);
6
+
7
+ /**
8
+ * The notification center's motion, the one place to tune it (as MOTION is the Toaster's).
9
+ * Durations are milliseconds at `timeScale: 1`; offsets and blur are CSS px. Starting values, to
10
+ * be tuned on the laboratory.
11
+ */
12
+ export const CENTER_MOTION: NotificationCenterMotionConstants = {
13
+ /** The drawer's position opening: critically damped. */
14
+ open: { stiffness: 320, damping: critical(320), mass: 1 },
15
+ /** Closing: one and a half times stiffer, still critical. */
16
+ close: { stiffness: 480, damping: critical(480), mass: 1 },
17
+ /** A closed card lies this far past the column's own width, off the screen with its shadow. */
18
+ travel: 56,
19
+ /** Each next card trails the previous one by this share of the way (up to the eighth card). */
20
+ lag: 0.12,
21
+ /** A card that arrives in the open center grows like the Toaster's first pill. */
22
+ enter: { duration: 200, bounce: 0.25, scale: 0.25, fade: 160 },
23
+ /** A cleared card leaves like the Toaster's dismissed pill. */
24
+ exit: { duration: 300, bounce: 0 },
25
+ /** The other cards move to their new places on this spring. */
26
+ reflow: { stiffness: 448, damping: critical(448), mass: 1 },
27
+ /** The time and the clear button in its place swap with a blur. */
28
+ swap: 180, swapBlur: 4,
29
+ /** Reduced motion: opening, closing and the list change opacity only, for this long. */
30
+ reduced: 80,
31
+ /**
32
+ * A group: its cards move between the stack and the list on `expand` and `collapse` (the Island's
33
+ * shape springs, a little under critical: the cards pass their places slightly and settle);
34
+ * collapsed, each edge under the top card lies `step` px lower and `shrink` narrower than the one
35
+ * above; an edge's content shows over `reveal` ms from a `blur` px blur, as the heading row and
36
+ * the button under the stack swap; `cascade` 0 moves the cards together.
37
+ */
38
+ stack: {
39
+ expand: { stiffness: 900, damping: 60, mass: 2 },
40
+ collapse: { stiffness: 900, damping: 45, mass: 1 },
41
+ step: 10, shrink: 0.06, reveal: 160, blur: 4, cascade: 0,
42
+ },
43
+ };
44
+
45
+ /** Cards after the eighth trail like the eighth. */
46
+ export const LAG_CARDS = 8;
47
+
48
+ const positive = new Set(['stiffness', 'mass']);
49
+
50
+ /**
51
+ * Resolves `NotificationCenterMotion.overrides` (a debugging channel) onto the starting values with
52
+ * the Toaster's contract: a field that is not a finite number in range (stiffness and mass > 0, the
53
+ * rest ≥ 0) keeps its default; unknown keys are ignored.
54
+ */
55
+ export function resolveCenterMotion(overrides: NotificationCenterMotionOverrides | undefined): NotificationCenterMotionConstants {
56
+ if (!overrides || typeof overrides !== 'object') return CENTER_MOTION;
57
+ const valid = (key: string, value: unknown): value is number =>
58
+ typeof value === 'number' && Number.isFinite(value) && (positive.has(key) ? value > 0 : value >= 0);
59
+ // Nested to any depth (the stack's springs sit inside `stack`): every number of the defaults is a field.
60
+ const resolve = (base: Record<string, unknown>, override: unknown): Record<string, unknown> => {
61
+ const source = override && typeof override === 'object' ? override as Record<string, unknown> : {};
62
+ const result: Record<string, unknown> = {};
63
+ for (const [key, value] of Object.entries(base)) {
64
+ result[key] = typeof value === 'number' ? valid(key, source[key]) ? source[key] : value : resolve(value as Record<string, unknown>, source[key]);
65
+ }
66
+ return result;
67
+ };
68
+ return resolve(CENTER_MOTION as unknown as Record<string, unknown>, overrides) as unknown as NotificationCenterMotionConstants;
69
+ }
70
+
71
+ type Spring = NotificationCenterMotionConstants['reflow'];
72
+ const delays = new Map<string, number>();
73
+ /**
74
+ * How long (ms at `timeScale: 1`) a card waits so that it starts once the first card of its group
75
+ * has covered `share` of its way on `spring` from rest: the stack's cascade. Cached per spring.
76
+ */
77
+ export function cascadeDelay(spec: Spring, share: number): number {
78
+ if (!(share > 0)) return 0;
79
+ const goal = Math.min(share, 0.95) * PERMILLE;
80
+ const name = `${spec.stiffness}/${spec.damping}/${spec.mass}/${goal}`;
81
+ let delay = delays.get(name);
82
+ if (delay === undefined) {
83
+ const generator = spring({ from: 0, to: PERMILLE, velocity: 0, ...spec });
84
+ delay = 0;
85
+ while (delay < 5000 && generator.next(delay).value < goal) delay++;
86
+ if (delays.size > 64) delays.clear();
87
+ delays.set(name, delay);
88
+ }
89
+ return delay;
90
+ }
91
+
92
+ /**
93
+ * A card of a group in the group's own terms (px from the top of its `li`, layout values untouched
94
+ * by transforms). `plain` is a card in the flow, its look scaled from its top centre: the top card
95
+ * of a stack and every card of an expanded group. `edge` (levels 1 and 2) and `hidden` (behind the
96
+ * second edge, at level 2) are bottom-aligned with the top card (`list` + `first`), lowered by
97
+ * `step × level` and narrowed from their bottom centre by the CSS, and clipped at rest to the top
98
+ * card's height (`restClip`).
99
+ */
100
+ export interface StackBox {
101
+ readonly kind: 'plain' | 'edge' | 'hidden';
102
+ /** Plain: the card's layout top. */
103
+ readonly top: number;
104
+ /** The card's own height. */
105
+ readonly height: number;
106
+ /** The top of the group's list, and the height of the stack's top card. */
107
+ readonly list: number;
108
+ readonly first: number;
109
+ /** 0 for a plain card, 1 or 2 for an edge, 2 for a hidden card. */
110
+ readonly level: number;
111
+ }
112
+ /** A card's channels in its box's terms: offset, scale and clip from the top, with the speeds (per second). */
113
+ export interface StackLook { readonly y: number; readonly s: number; readonly c: number; readonly vy: number; readonly vs: number }
114
+ /** What a card looks like in the group: the visible top and bottom, its scale, and their speeds. */
115
+ export interface StackVisual { readonly top: number; readonly bottom: number; readonly scale: number; readonly vbottom: number; readonly vscale: number }
116
+ type StackGeometry = Pick<NotificationCenterMotionConstants['stack'], 'step' | 'shrink'>;
117
+
118
+ /** The clip from the top a card's place gives it at rest: an edge shows the top card's height. */
119
+ export const restClip = (box: StackBox) => box.kind === 'plain' ? 0 : Math.max(0, box.height - box.first);
120
+ const narrowing = (box: StackBox, geometry: StackGeometry) => Math.max(0.05, 1 - box.level * geometry.shrink);
121
+
122
+ /** How a card looks with `look` in `box`; the clip in force is the channel's while it runs (`clipping`), else the place's own. */
123
+ export function stackVisual(box: StackBox, look: StackLook & { readonly clipping: boolean }, geometry: StackGeometry): StackVisual {
124
+ const clip = look.clipping ? look.c : restClip(box);
125
+ if (box.kind === 'plain') {
126
+ const base = box.top + look.y;
127
+ return { top: base + clip * look.s, bottom: base + box.height * look.s, scale: look.s, vbottom: look.vy + box.height * look.vs, vscale: look.vs };
128
+ }
129
+ const narrow = narrowing(box, geometry);
130
+ const bottom = box.list + box.first + box.level * geometry.step + narrow * look.y;
131
+ const scale = narrow * look.s;
132
+ return { top: bottom - scale * (box.height - clip), bottom, scale, vbottom: narrow * look.vy, vscale: narrow * look.vs };
133
+ }
134
+
135
+ /** The channels that give a card in `box` the look `visual`: the inverse of `stackVisual`, the clip within the card. */
136
+ export function stackLook(box: StackBox, visual: StackVisual, geometry: StackGeometry): StackLook {
137
+ const scale = Math.max(1e-3, visual.scale);
138
+ const c = Math.min(box.height, Math.max(0, box.height - (visual.bottom - visual.top) / scale));
139
+ if (box.kind === 'plain') {
140
+ return { y: visual.bottom - box.top - box.height * scale, s: scale, c, vy: visual.vbottom - box.height * visual.vscale, vs: visual.vscale };
141
+ }
142
+ const narrow = narrowing(box, geometry);
143
+ return { y: (visual.bottom - box.list - box.first - box.level * geometry.step) / narrow, s: scale / narrow, c, vy: visual.vbottom / narrow, vs: visual.vscale / narrow };
144
+ }
145
+
146
+ /**
147
+ * The drawer's position runs on the spring in thousandths: the generators stop a spring within
148
+ * 0.5 units at under 2 units/s once its range is 5 units or more, so a 0–1000 range settles within
149
+ * 0.05 % of the travel (a fraction of a pixel), where 0–1 would snap the last 0.5 %.
150
+ */
151
+ const PERMILLE = 1000;
152
+
153
+ type Spec =
154
+ | { readonly stiffness: number; readonly damping: number; readonly mass: number }
155
+ | { readonly duration: number; readonly bounce: number }
156
+ | { readonly tween: number };
157
+ interface ChannelState {
158
+ value: number;
159
+ target: number;
160
+ /** Real-time units per second, independent of timeScale. */
161
+ velocity: number;
162
+ animation: { generator: Generator; start: number } | null;
163
+ }
164
+
165
+ /**
166
+ * Channels: `p` (drawer position in thousandths), `fade` (the panel's opacity, reduced motion only),
167
+ * `blur` (the backdrop's blur layers apart from the drawer: 0 while the page scrolls under the
168
+ * center, with the backdrop's scroll tint) and per card `x:<key>` (sideways offset under a finger, px), `y:<key>` (offset from its layout
169
+ * place, px), `s:<key>` (scale), `c:<key>` (clip from its top, px, while it moves in a group) and
170
+ * `o:<key>` (opacity).
171
+ */
172
+ const resting = (key: string) => key === 'p' || key.startsWith('x:') || key.startsWith('y:') || key.startsWith('c:') ? 0 : 1;
173
+ /** Spatial channels jump under reduced motion; opacity channels fade for `reduced` ms. */
174
+ const spatial = (key: string) => key === 'p' || key.startsWith('x:') || key.startsWith('y:') || key.startsWith('s:') || key.startsWith('c:');
175
+ const CARD_CHANNELS = ['x:', 'y:', 's:', 'c:', 'o:'] as const;
176
+
177
+ interface CenterMotionOptions {
178
+ readonly now: () => number;
179
+ readonly requestFrame: (callback: (time: number) => void) => number;
180
+ readonly cancelFrame: (frame: number) => void;
181
+ /** The sole DOM writer (CSSOM rules), with the channels that changed since the last write. */
182
+ readonly write: (changed: ReadonlySet<string>) => void;
183
+ readonly reducedMotion?: boolean | undefined;
184
+ readonly timeScale?: number | undefined;
185
+ readonly constants?: NotificationCenterMotionConstants | undefined;
186
+ }
187
+
188
+ const validScale = (value: number | undefined) => typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 1;
189
+
190
+ /**
191
+ * One RAF sampler per center over the generators of generators.ts. Every retarget starts from the
192
+ * current value and velocity, so opening in the middle of closing turns the drawer without a jerk;
193
+ * nothing is scheduled at rest; completion callbacks run from a frame, only for the latest request
194
+ * of their group. A finger (the gestures) can take the position over: `grab`, `drag`, then
195
+ * `release` back to the open position or `fling` before the center closes.
196
+ */
197
+ export function createCenterMotion(options: CenterMotionOptions) {
198
+ const channels = new Map<string, ChannelState>();
199
+ const groups = new Map<string, { keys: readonly string[]; done: () => void }>();
200
+ const changed = new Set<string>();
201
+ let frame: number | null = null;
202
+ let disposed = false;
203
+ let reduced = options.reducedMotion ?? false;
204
+ let timeScale = validScale(options.timeScale);
205
+ let m = options.constants ?? CENTER_MOTION;
206
+
207
+ function channel(key: string): ChannelState {
208
+ let state = channels.get(key);
209
+ if (!state) {
210
+ const value = resting(key);
211
+ channels.set(key, state = { value, target: value, velocity: 0, animation: null });
212
+ }
213
+ return state;
214
+ }
215
+ const busy = (keys: Iterable<string>) => { for (const key of keys) if (channels.get(key)?.animation) return true; return false; };
216
+ function sample(time: number) {
217
+ for (const [key, state] of channels) {
218
+ const animation = state.animation;
219
+ if (!animation) continue;
220
+ const elapsed = Math.max(0, (time - animation.start) * timeScale);
221
+ const next = animation.generator.next(elapsed);
222
+ state.value = next.value;
223
+ state.velocity = next.done ? 0 : (animation.generator.velocity?.(elapsed) ?? 0) * timeScale;
224
+ if (next.done) { state.animation = null; state.value = state.target; }
225
+ changed.add(key);
226
+ }
227
+ }
228
+ function flush() {
229
+ if (disposed || !changed.size) return;
230
+ const keys = new Set(changed);
231
+ changed.clear();
232
+ options.write(keys);
233
+ }
234
+ function schedule() {
235
+ if (!disposed && frame === null) frame = options.requestFrame(tick);
236
+ }
237
+ function complete() {
238
+ for (const [name, group] of [...groups]) {
239
+ if (disposed) return;
240
+ if (groups.get(name) !== group || busy(group.keys)) continue;
241
+ groups.delete(name);
242
+ group.done();
243
+ }
244
+ }
245
+ function tick() {
246
+ frame = null;
247
+ if (disposed) return;
248
+ // The sampler's own clock, as every request reads it: a frame's timestamp can precede a request
249
+ // made earlier in the same frame, which would step the curve back.
250
+ sample(options.now());
251
+ flush();
252
+ complete();
253
+ // A completion may place a channel (a hidden card's opacity back at rest).
254
+ flush();
255
+ if (groups.size || busy(channels.keys())) schedule();
256
+ }
257
+ function jump(key: string, value: number) {
258
+ const state = channel(key);
259
+ if (state.value !== value || state.animation) changed.add(key);
260
+ state.value = state.target = value;
261
+ state.velocity = 0;
262
+ state.animation = null;
263
+ }
264
+ /** Retargets a channel from its value and speed; `delay` (ms at `timeScale: 1`) holds it where it is first. */
265
+ function to(key: string, target: number, spec: Spec, time: number, delay = 0) {
266
+ const state = channel(key);
267
+ if (reduced) {
268
+ if (spatial(key)) return jump(key, target);
269
+ spec = { tween: m.reduced };
270
+ delay = 0;
271
+ }
272
+ state.target = target;
273
+ if (state.value === target && !state.animation) return;
274
+ const generator = 'tween' in spec
275
+ ? tweenGenerator(state.value, target, spec.tween)
276
+ : spring({ from: state.value, to: target, velocity: state.velocity / timeScale, ...spec });
277
+ state.animation = { generator, start: time + delay / timeScale };
278
+ }
279
+ /** Puts a channel at `value` with `velocity` (real-time units per second), for a retarget that follows. */
280
+ function set(key: string, value: number, velocity: number) {
281
+ const state = channel(key);
282
+ const next = Number.isFinite(value) ? value : state.target;
283
+ if (state.value !== next) changed.add(key);
284
+ state.value = next;
285
+ state.velocity = Number.isFinite(velocity) ? velocity : 0;
286
+ }
287
+ function after(name: string, keys: readonly string[], done?: () => void) {
288
+ if (done) groups.set(name, { keys, done }); else groups.delete(name);
289
+ }
290
+ function request(change: (time: number) => void) {
291
+ if (disposed) return;
292
+ const time = options.now();
293
+ sample(time);
294
+ change(time);
295
+ flush();
296
+ if (groups.size || busy(channels.keys())) schedule();
297
+ }
298
+ const enterSpring = () => ({ duration: m.enter.duration, bounce: m.enter.bounce });
299
+ const exitSpring = () => ({ duration: m.exit.duration, bounce: m.exit.bounce });
300
+
301
+ return {
302
+ /** The current value of a channel; `p` in 0–1 (a spring released with speed may pass 1). */
303
+ value(key: string): number {
304
+ const state = channels.get(key);
305
+ const value = state ? state.value : resting(key);
306
+ return key === 'p' ? value / PERMILLE : value;
307
+ },
308
+ /** Opens or closes on the position spring from where the drawer is and how fast it moves. */
309
+ setOpen(open: boolean, done?: () => void) {
310
+ request(time => {
311
+ if (reduced) {
312
+ // Calm: the cards stay in place and the panel fades in or out.
313
+ const fade = channel('fade');
314
+ if (open && fade.target === 1 && channel('p').value === 0) jump('fade', 0);
315
+ jump('p', PERMILLE);
316
+ to('fade', open ? 1 : 0, { tween: m.reduced }, time);
317
+ } else {
318
+ jump('fade', 1);
319
+ to('p', open ? PERMILLE : 0, open ? m.open : m.close, time);
320
+ }
321
+ after('drawer', ['p', 'fade'], done);
322
+ });
323
+ },
324
+ /**
325
+ * Shows (1) or hides (0) the backdrop's blur layers apart from the drawer, over `duration` ms
326
+ * from where they are; at once under reduced motion.
327
+ */
328
+ setBlur(shown: boolean, duration: number) {
329
+ request(time => {
330
+ if (reduced) jump('blur', shown ? 1 : 0);
331
+ else to('blur', shown ? 1 : 0, { tween: duration }, time);
332
+ });
333
+ },
334
+ /** Places the drawer without motion (an open center on the first client render). */
335
+ place(open: boolean) {
336
+ request(() => { jump('p', open ? PERMILLE : 0); jump('fade', 1); groups.delete('drawer'); });
337
+ },
338
+ /** A finger takes the position: the spring stops where it is. */
339
+ grab() {
340
+ request(() => { const state = channel('p'); jump('p', state.value); groups.delete('drawer'); });
341
+ },
342
+ /** The finger moves the drawer to `p` (0 closed, 1 open). */
343
+ drag(p: number) {
344
+ request(() => { if (Number.isFinite(p)) jump('p', p * PERMILLE); });
345
+ },
346
+ /** The finger lets go short of closing: back to open with its speed (p per second). */
347
+ release(velocity: number, done?: () => void) {
348
+ request(time => {
349
+ const state = channel('p');
350
+ state.velocity = Number.isFinite(velocity) ? velocity * PERMILLE : 0;
351
+ to('p', PERMILLE, m.open, time);
352
+ after('drawer', ['p', 'fade'], done);
353
+ });
354
+ },
355
+ /** Sets the speed (p per second) the following `setOpen(false)` starts with. */
356
+ fling(velocity: number) {
357
+ const state = channel('p');
358
+ if (!disposed && !state.animation) state.velocity = Number.isFinite(velocity) ? velocity * PERMILLE : 0;
359
+ },
360
+ /** A card that arrives in the open center grows in from the top. */
361
+ enter(key: string) {
362
+ request(time => {
363
+ if (!reduced) { jump(`s:${key}`, m.enter.scale); to(`s:${key}`, 1, enterSpring(), time); }
364
+ jump(`o:${key}`, 0);
365
+ to(`o:${key}`, 1, { tween: m.enter.fade }, time);
366
+ });
367
+ },
368
+ /** A card's layout place moved by `delta` px: it starts where it was and springs to the new place. */
369
+ shift(key: string, delta: number) {
370
+ request(time => {
371
+ if (!Number.isFinite(delta) || Math.abs(delta) < 0.5) return;
372
+ const state = channel(`y:${key}`);
373
+ state.value += delta;
374
+ changed.add(`y:${key}`);
375
+ to(`y:${key}`, 0, m.reflow, time);
376
+ });
377
+ },
378
+ /**
379
+ * A card of a group moved between places (the stack's top, its edges, behind them, the list of
380
+ * an expanded group): `rebase` turns its current channels into its new place's terms, so it
381
+ * looks where it was and keeps its speed, and it springs to the place on `spring` (the clip to
382
+ * `clip`, the place's own). `delay` holds a card that stands still (the cascade). `fade: 'in'`
383
+ * shows a card that was hidden over `stack.reveal` ms; `'out'` fades it out, then leaves it to
384
+ * its place's own hiding at full opacity.
385
+ */
386
+ fold(key: string, rebase: (look: StackLook & { readonly clipping: boolean }) => StackLook,
387
+ options: { readonly spring: Spec; readonly clip: number; readonly delay?: number | undefined; readonly fade?: 'in' | 'out' | undefined }) {
388
+ request(time => {
389
+ const y = channel(`y:${key}`);
390
+ const s = channel(`s:${key}`);
391
+ const c = channel(`c:${key}`);
392
+ const o = channel(`o:${key}`);
393
+ const still = !y.animation && !s.animation && !c.animation;
394
+ const next = rebase({ y: y.value, s: s.value, c: c.value, vy: y.velocity, vs: s.velocity, clipping: !!c.animation });
395
+ const delay = still ? Math.max(0, options.delay ?? 0) : 0;
396
+ set(`y:${key}`, next.y, next.vy);
397
+ set(`s:${key}`, next.s, next.vs);
398
+ set(`c:${key}`, next.c, 0);
399
+ to(`y:${key}`, 0, options.spring, time, delay);
400
+ to(`s:${key}`, 1, options.spring, time, delay);
401
+ to(`c:${key}`, options.clip, options.spring, time, delay);
402
+ const fade = { tween: m.stack.reveal };
403
+ if (options.fade === 'out') {
404
+ to(`o:${key}`, 0, fade, time, delay);
405
+ after(`fade:${key}`, [`o:${key}`], () => jump(`o:${key}`, 1));
406
+ return;
407
+ }
408
+ groups.delete(`fade:${key}`);
409
+ if (options.fade === 'in' && !o.animation && o.value === 1) jump(`o:${key}`, 0);
410
+ if (o.value !== 1 || o.animation) to(`o:${key}`, 1, fade, time, delay);
411
+ });
412
+ },
413
+ /**
414
+ * Starts a leaving card (its inert copy) from a card's current look, then fades and shrinks it.
415
+ * A swiped card (`fling`) instead keeps flying sideways to `fling.to` px from where the finger let
416
+ * it go, with the release speed (px per second), and fades. `rest` is where the copy's card lay,
417
+ * in the copy's terms (an edge of a stack: lower, narrower, clipped); it shrinks from there.
418
+ */
419
+ exit(key: string, from: { x?: number; y: number; scale: number; opacity: number; clip?: number }, done: () => void,
420
+ fling?: { readonly to: number; readonly velocity: number }, rest?: { readonly y: number; readonly s: number; readonly c: number }) {
421
+ request(time => {
422
+ jump(`x:${key}`, from.x ?? 0); jump(`y:${key}`, from.y); jump(`s:${key}`, from.scale); jump(`o:${key}`, from.opacity);
423
+ jump(`c:${key}`, from.clip ?? 0);
424
+ const home = rest ?? { y: 0, s: 1, c: 0 };
425
+ // Calm: the copy only fades where it stands.
426
+ if (!reduced && fling) {
427
+ channel(`x:${key}`).velocity = Number.isFinite(fling.velocity) ? fling.velocity : 0;
428
+ to(`x:${key}`, fling.to, m.reflow, time);
429
+ to(`y:${key}`, home.y, m.reflow, time);
430
+ } else if (!reduced) {
431
+ to(`x:${key}`, 0, m.reflow, time);
432
+ to(`y:${key}`, home.y, m.reflow, time);
433
+ to(`s:${key}`, home.s * m.enter.scale, exitSpring(), time);
434
+ to(`c:${key}`, home.c, m.reflow, time);
435
+ }
436
+ to(`o:${key}`, 0, exitSpring(), time);
437
+ after(`exit:${key}`, CARD_CHANNELS.map(prefix => prefix + key), done);
438
+ });
439
+ },
440
+ /** A finger moves a card sideways to `x` px. */
441
+ dragCard(key: string, x: number) {
442
+ request(() => { if (Number.isFinite(x)) jump(`x:${key}`, x); });
443
+ },
444
+ /** The finger lets a card go short of clearing it: back to its place with its speed (px per second). */
445
+ releaseCard(key: string, velocity: number) {
446
+ request(time => {
447
+ const state = channel(`x:${key}`);
448
+ state.velocity = Number.isFinite(velocity) ? velocity : 0;
449
+ to(`x:${key}`, 0, m.reflow, time);
450
+ });
451
+ },
452
+ /** Drops a card's channels (it left the list, or its copy finished leaving). */
453
+ forget(key: string) {
454
+ for (const prefix of CARD_CHANNELS) channels.delete(prefix + key);
455
+ groups.delete(`exit:${key}`);
456
+ groups.delete(`fade:${key}`);
457
+ },
458
+ /** True while a channel runs (or waits out its delay). */
459
+ moving(key: string): boolean { return !!channels.get(key)?.animation; },
460
+ setReducedMotion(next: boolean) {
461
+ if (disposed || reduced === next) return;
462
+ request(time => {
463
+ reduced = next;
464
+ if (!reduced) {
465
+ // Leave the calm state: the panel is fully shown, the position carries on.
466
+ if (channel('fade').target === 1) jump('fade', 1);
467
+ return;
468
+ }
469
+ for (const [key, state] of channels) {
470
+ if (!state.animation) continue;
471
+ if (spatial(key) || key === 'blur') jump(key, state.target);
472
+ else { state.animation = null; state.velocity = 0; to(key, state.target, { tween: m.reduced }, time); }
473
+ }
474
+ });
475
+ },
476
+ setTimeScale(next: number | undefined) {
477
+ const scale = validScale(next);
478
+ if (disposed || scale === timeScale) return;
479
+ const time = options.now();
480
+ sample(time);
481
+ // Rebase running animations so their generator time stays continuous.
482
+ for (const state of channels.values()) {
483
+ if (state.animation) state.animation.start = time - (time - state.animation.start) * timeScale / scale;
484
+ }
485
+ timeScale = scale;
486
+ },
487
+ /** New constants apply to transitions started from now on; running ones keep their curves. */
488
+ setConstants(next: NotificationCenterMotionConstants) { m = next; },
489
+ get constants() { return m; },
490
+ get reduced() { return reduced; },
491
+ /** True while a frame is scheduled; a center at rest never keeps a RAF loop. */
492
+ get running() { return frame !== null; },
493
+ dispose() {
494
+ if (disposed) return;
495
+ disposed = true;
496
+ if (frame !== null) options.cancelFrame(frame);
497
+ frame = null;
498
+ groups.clear();
499
+ channels.clear();
500
+ },
501
+ };
502
+ }
503
+
504
+ export type CenterMotion = ReturnType<typeof createCenterMotion>;