@tschk/moonshine-svelte 0.4.49 → 0.4.80

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/motion.ts ADDED
@@ -0,0 +1,504 @@
1
+ /** Independent host-free Svelte 5 motion primitives (`svelte/motion`). */
2
+ import { createSignal, untrack } from "@tschk/moonshine";
3
+ import {
4
+ createComputed,
5
+ getOwner,
6
+ onCleanup,
7
+ } from "@tschk/moonshine-dom/reactive";
8
+ import { linear, type EasingFunction } from "./easing";
9
+ import { MediaQuery } from "./reactivity";
10
+ import {
11
+ writable,
12
+ type Readable,
13
+ type Subscriber,
14
+ type Unsubscriber,
15
+ } from "./store";
16
+
17
+ export interface SpringOptions {
18
+ stiffness?: number;
19
+ damping?: number;
20
+ precision?: number;
21
+ }
22
+
23
+ export interface SpringUpdateOptions {
24
+ hard?: boolean;
25
+ soft?: boolean | number;
26
+ preserveMomentum?: number;
27
+ }
28
+
29
+ export interface TweenedOptions<T> {
30
+ delay?: number;
31
+ duration?: number | ((from: T, to: T) => number);
32
+ easing?: EasingFunction;
33
+ interpolate?: (a: T, b: T) => (t: number) => T;
34
+ }
35
+
36
+ function defaultInterpolate<T>(a: T, b: T): (t: number) => T {
37
+ if (a === b || a !== a) return () => a;
38
+ const type = typeof a;
39
+ if (type !== typeof b || Array.isArray(a) !== Array.isArray(b)) {
40
+ throw new TypeError("Cannot interpolate values of different types");
41
+ }
42
+ if (Array.isArray(a) && Array.isArray(b)) {
43
+ const interpolators = b.map((bi, i) => defaultInterpolate(a[i], bi));
44
+ return (t: number) => interpolators.map((fn) => fn(t)) as unknown as T;
45
+ }
46
+ if (type === "object" && a !== null && b !== null) {
47
+ if (a instanceof Date && b instanceof Date) {
48
+ const fromTime = a.getTime();
49
+ const toTime = b.getTime();
50
+ const delta = toTime - fromTime;
51
+ return (t: number) => new Date(fromTime + t * delta) as unknown as T;
52
+ }
53
+ const keys = Object.keys(b as object);
54
+ const interpolators: Record<string, (t: number) => unknown> = {};
55
+ for (const k of keys) {
56
+ interpolators[k] = defaultInterpolate(
57
+ (a as Record<string, unknown>)[k],
58
+ (b as Record<string, unknown>)[k],
59
+ );
60
+ }
61
+ return (t: number) => {
62
+ const res: Record<string, unknown> = {};
63
+ for (const k of keys) {
64
+ res[k] = interpolators[k]!(t);
65
+ }
66
+ return res as unknown as T;
67
+ };
68
+ }
69
+ if (type === "number") {
70
+ const fromNum = a as unknown as number;
71
+ const delta = (b as unknown as number) - fromNum;
72
+ return (t: number) => (fromNum + t * delta) as unknown as T;
73
+ }
74
+ throw new TypeError(`Cannot interpolate ${type} values`);
75
+ }
76
+
77
+ function cloneMotionValue<T>(value: T): T {
78
+ if (value instanceof Date) {
79
+ return new Date(value.getTime()) as unknown as T;
80
+ }
81
+ if (Array.isArray(value)) {
82
+ return value.map((item) => cloneMotionValue(item)) as unknown as T;
83
+ }
84
+ if (value !== null && typeof value === "object") {
85
+ const out: Record<string, unknown> = {};
86
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
87
+ out[k] = cloneMotionValue(v);
88
+ }
89
+ return out as unknown as T;
90
+ }
91
+ return value;
92
+ }
93
+
94
+ function stepSpringValue<T>(
95
+ current: T,
96
+ last: T,
97
+ target: T,
98
+ stiffness: number,
99
+ damping: number,
100
+ precision: number,
101
+ dt: number,
102
+ ): { value: T; settled: boolean } {
103
+ if (typeof target === "number" && typeof current === "number") {
104
+ const lastNum = typeof last === "number" ? last : current;
105
+ const d = target - current;
106
+ const velocity = (current - lastNum) / (dt || 1 / 60);
107
+ const springForce = stiffness * d;
108
+ const damperForce = damping * velocity;
109
+ const acceleration = (springForce - damperForce) * dt;
110
+ const nextDelta = (velocity + acceleration) * dt;
111
+ if (Math.abs(nextDelta) < precision && Math.abs(d) < precision) {
112
+ return { value: target, settled: true };
113
+ }
114
+ return {
115
+ value: (current + nextDelta) as unknown as T,
116
+ settled: false,
117
+ };
118
+ }
119
+ if (target instanceof Date && current instanceof Date) {
120
+ const lastDate = last instanceof Date ? last : current;
121
+ const step = stepSpringValue(
122
+ current.getTime(),
123
+ lastDate.getTime(),
124
+ target.getTime(),
125
+ stiffness,
126
+ damping,
127
+ precision,
128
+ dt,
129
+ );
130
+ return {
131
+ value: new Date(step.value) as unknown as T,
132
+ settled: step.settled,
133
+ };
134
+ }
135
+ if (Array.isArray(target) && Array.isArray(current)) {
136
+ const lastArr = Array.isArray(last) ? last : current;
137
+ let allSettled = true;
138
+ const nextArr = target.map((tItem, i) => {
139
+ const step = stepSpringValue(
140
+ current[i],
141
+ lastArr[i],
142
+ tItem,
143
+ stiffness,
144
+ damping,
145
+ precision,
146
+ dt,
147
+ );
148
+ if (!step.settled) allSettled = false;
149
+ return step.value;
150
+ });
151
+ return { value: nextArr as unknown as T, settled: allSettled };
152
+ }
153
+ if (
154
+ target !== null &&
155
+ typeof target === "object" &&
156
+ current !== null &&
157
+ typeof current === "object"
158
+ ) {
159
+ const lastObj =
160
+ last !== null && typeof last === "object"
161
+ ? (last as Record<string, unknown>)
162
+ : (current as Record<string, unknown>);
163
+ let allSettled = true;
164
+ const nextObj: Record<string, unknown> = {};
165
+ for (const k of Object.keys(target as object)) {
166
+ const step = stepSpringValue(
167
+ (current as Record<string, unknown>)[k],
168
+ lastObj[k],
169
+ (target as Record<string, unknown>)[k],
170
+ stiffness,
171
+ damping,
172
+ precision,
173
+ dt,
174
+ );
175
+ if (!step.settled) allSettled = false;
176
+ nextObj[k] = step.value;
177
+ }
178
+ return { value: nextObj as unknown as T, settled: allSettled };
179
+ }
180
+ return { value: target, settled: true };
181
+ }
182
+
183
+ export class Spring<T> {
184
+ stiffness: number;
185
+ damping: number;
186
+ precision: number;
187
+
188
+ readonly #currentSig;
189
+ readonly #targetSig;
190
+ #lastValue: T;
191
+ #timer: ReturnType<typeof setTimeout> | undefined;
192
+ #pendingResolve: (() => void) | undefined;
193
+
194
+ constructor(value: T, options: SpringOptions = {}) {
195
+ this.stiffness = options.stiffness ?? 0.15;
196
+ this.damping = options.damping ?? 0.8;
197
+ this.precision = options.precision ?? 0.01;
198
+ const initial = cloneMotionValue(value);
199
+ this.#currentSig = createSignal<T>(initial);
200
+ this.#targetSig = createSignal<T>(cloneMotionValue(value));
201
+ this.#lastValue = cloneMotionValue(value);
202
+ }
203
+
204
+ static of<U>(fn: () => U, options?: SpringOptions): Spring<U> {
205
+ const instance = new Spring<U>(untrack(fn), options);
206
+ if (getOwner()) {
207
+ let first = true;
208
+ createComputed(() => {
209
+ const next = fn();
210
+ if (first) {
211
+ first = false;
212
+ return;
213
+ }
214
+ untrack(() => {
215
+ void instance.set(next);
216
+ });
217
+ });
218
+ onCleanup(() => {
219
+ instance.#cancel();
220
+ });
221
+ }
222
+ return instance;
223
+ }
224
+
225
+ get current(): T {
226
+ return this.#currentSig();
227
+ }
228
+
229
+ get target(): T {
230
+ return this.#targetSig();
231
+ }
232
+
233
+ set target(value: T) {
234
+ void this.set(value);
235
+ }
236
+
237
+ #cancel(): void {
238
+ if (this.#timer !== undefined) {
239
+ clearTimeout(this.#timer);
240
+ this.#timer = undefined;
241
+ }
242
+ if (this.#pendingResolve) {
243
+ const res = this.#pendingResolve;
244
+ this.#pendingResolve = undefined;
245
+ res();
246
+ }
247
+ }
248
+
249
+ set(newValue: T, options?: SpringUpdateOptions): Promise<void> {
250
+ this.#targetSig.set(() => cloneMotionValue(newValue));
251
+ this.#cancel();
252
+
253
+ if (options?.hard || (this.stiffness >= 1 && this.damping >= 1)) {
254
+ const cloned = cloneMotionValue(newValue);
255
+ this.#lastValue = cloneMotionValue(newValue);
256
+ this.#currentSig.set(() => cloned);
257
+ return Promise.resolve();
258
+ }
259
+
260
+ return new Promise<void>((resolve) => {
261
+ this.#pendingResolve = resolve;
262
+ let steps = 0;
263
+ const tick = () => {
264
+ steps++;
265
+ const current = untrack(this.#currentSig);
266
+ const target = untrack(this.#targetSig);
267
+ const { value: next, settled } = stepSpringValue(
268
+ current,
269
+ this.#lastValue,
270
+ target,
271
+ this.stiffness,
272
+ this.damping,
273
+ this.precision,
274
+ 1 / 60,
275
+ );
276
+ this.#lastValue = current;
277
+ this.#currentSig.set(() => next);
278
+ if (settled || steps >= 120) {
279
+ this.#currentSig.set(() => cloneMotionValue(target));
280
+ this.#lastValue = cloneMotionValue(target);
281
+ this.#timer = undefined;
282
+ const done = this.#pendingResolve;
283
+ this.#pendingResolve = undefined;
284
+ done?.();
285
+ return;
286
+ }
287
+ this.#timer = setTimeout(tick, 4);
288
+ };
289
+ this.#timer = setTimeout(tick, 4);
290
+ });
291
+ }
292
+ }
293
+
294
+ export class Tween<T> {
295
+ readonly #currentSig;
296
+ readonly #targetSig;
297
+ readonly #defaults: TweenedOptions<T>;
298
+ #timer: ReturnType<typeof setTimeout> | undefined;
299
+ #pendingResolve: (() => void) | undefined;
300
+
301
+ constructor(value: T, options: TweenedOptions<T> = {}) {
302
+ this.#defaults = options;
303
+ this.#currentSig = createSignal<T>(cloneMotionValue(value));
304
+ this.#targetSig = createSignal<T>(cloneMotionValue(value));
305
+ }
306
+
307
+ static of<U>(fn: () => U, options?: TweenedOptions<U>): Tween<U> {
308
+ const instance = new Tween<U>(untrack(fn), options);
309
+ if (getOwner()) {
310
+ let first = true;
311
+ createComputed(() => {
312
+ const next = fn();
313
+ if (first) {
314
+ first = false;
315
+ return;
316
+ }
317
+ untrack(() => {
318
+ void instance.set(next);
319
+ });
320
+ });
321
+ onCleanup(() => {
322
+ instance.#cancel();
323
+ });
324
+ }
325
+ return instance;
326
+ }
327
+
328
+ get current(): T {
329
+ return this.#currentSig();
330
+ }
331
+
332
+ get target(): T {
333
+ return this.#targetSig();
334
+ }
335
+
336
+ set target(value: T) {
337
+ void this.set(value);
338
+ }
339
+
340
+ #cancel(): void {
341
+ if (this.#timer !== undefined) {
342
+ clearTimeout(this.#timer);
343
+ this.#timer = undefined;
344
+ }
345
+ if (this.#pendingResolve) {
346
+ const res = this.#pendingResolve;
347
+ this.#pendingResolve = undefined;
348
+ res();
349
+ }
350
+ }
351
+
352
+ set(newValue: T, options?: TweenedOptions<T>): Promise<void> {
353
+ const merged: TweenedOptions<T> = { ...this.#defaults, ...options };
354
+ const fromVal = untrack(this.#currentSig);
355
+ this.#targetSig.set(() => cloneMotionValue(newValue));
356
+ this.#cancel();
357
+
358
+ const duration =
359
+ typeof merged.duration === "function"
360
+ ? merged.duration(fromVal, newValue)
361
+ : (merged.duration ?? 400);
362
+ const delay = merged.delay ?? 0;
363
+ const easing = merged.easing ?? linear;
364
+ const interpolate =
365
+ merged.interpolate ??
366
+ (defaultInterpolate as (a: T, b: T) => (t: number) => T);
367
+
368
+ if (duration <= 0 && delay <= 0) {
369
+ this.#currentSig.set(() => cloneMotionValue(newValue));
370
+ return Promise.resolve();
371
+ }
372
+
373
+ const fn = interpolate(fromVal, newValue);
374
+ const startTime = performance.now() + delay;
375
+
376
+ return new Promise<void>((resolve) => {
377
+ this.#pendingResolve = resolve;
378
+ const step = () => {
379
+ const now = performance.now();
380
+ if (now < startTime) {
381
+ this.#timer = setTimeout(step, 4);
382
+ return;
383
+ }
384
+ const elapsed = now - startTime;
385
+ if (duration <= 0 || elapsed >= duration) {
386
+ this.#currentSig.set(() => cloneMotionValue(newValue));
387
+ this.#timer = undefined;
388
+ const done = this.#pendingResolve;
389
+ this.#pendingResolve = undefined;
390
+ done?.();
391
+ return;
392
+ }
393
+ const progress = easing(elapsed / duration);
394
+ this.#currentSig.set(() => fn(progress));
395
+ this.#timer = setTimeout(step, 4);
396
+ };
397
+ this.#timer = setTimeout(step, 4);
398
+ });
399
+ }
400
+ }
401
+
402
+ export interface SpringStore<T> extends Readable<T> {
403
+ set(newValue: T, opts?: SpringUpdateOptions): Promise<void>;
404
+ update(
405
+ fn: (target: T, value: T) => T,
406
+ opts?: SpringUpdateOptions,
407
+ ): Promise<void>;
408
+ precision: number;
409
+ damping: number;
410
+ stiffness: number;
411
+ }
412
+
413
+ export function spring<T = any>(
414
+ value?: T,
415
+ opts: SpringOptions = {},
416
+ ): SpringStore<T> {
417
+ const store = writable<T>(value as T);
418
+ const instance = new Spring<T>(value as T, opts);
419
+ let currentVal = value as T;
420
+ let targetVal = value as T;
421
+
422
+ return {
423
+ subscribe(run: Subscriber<T>, invalidate?: () => void): Unsubscriber {
424
+ return store.subscribe(run, invalidate);
425
+ },
426
+ async set(newValue: T, updateOpts?: SpringUpdateOptions): Promise<void> {
427
+ targetVal = newValue;
428
+ instance.stiffness = this.stiffness;
429
+ instance.damping = this.damping;
430
+ instance.precision = this.precision;
431
+ if (updateOpts?.hard || (this.stiffness >= 1 && this.damping >= 1)) {
432
+ currentVal = cloneMotionValue(newValue);
433
+ store.set(currentVal);
434
+ return;
435
+ }
436
+ const p = instance.set(newValue, updateOpts);
437
+ store.set(instance.current);
438
+ await p;
439
+ currentVal = instance.current;
440
+ store.set(currentVal);
441
+ },
442
+ update(
443
+ fn: (target: T, value: T) => T,
444
+ updateOpts?: SpringUpdateOptions,
445
+ ): Promise<void> {
446
+ return this.set(fn(targetVal, currentVal), updateOpts);
447
+ },
448
+ stiffness: opts.stiffness ?? 0.15,
449
+ damping: opts.damping ?? 0.8,
450
+ precision: opts.precision ?? 0.01,
451
+ };
452
+ }
453
+
454
+ export interface Tweened<T> extends Readable<T> {
455
+ set(value: T, opts?: TweenedOptions<T>): Promise<void>;
456
+ update(
457
+ updater: (target: T, value: T) => T,
458
+ opts?: TweenedOptions<T>,
459
+ ): Promise<void>;
460
+ }
461
+
462
+ export function tweened<T = any>(
463
+ value?: T,
464
+ defaults: TweenedOptions<T> = {},
465
+ ): Tweened<T> {
466
+ const store = writable<T>(value as T);
467
+ const instance = new Tween<T>(value as T, defaults);
468
+ let currentVal = value as T;
469
+ let targetVal = value as T;
470
+
471
+ return {
472
+ subscribe(run: Subscriber<T>, invalidate?: () => void): Unsubscriber {
473
+ return store.subscribe(run, invalidate);
474
+ },
475
+ async set(newValue: T, opts?: TweenedOptions<T>): Promise<void> {
476
+ targetVal = newValue;
477
+ const merged = { ...defaults, ...opts };
478
+ const duration =
479
+ typeof merged.duration === "function"
480
+ ? merged.duration(currentVal, newValue)
481
+ : (merged.duration ?? 400);
482
+ if (duration <= 0 && (merged.delay ?? 0) <= 0) {
483
+ currentVal = cloneMotionValue(newValue);
484
+ store.set(currentVal);
485
+ return;
486
+ }
487
+ const p = instance.set(newValue, opts);
488
+ await p;
489
+ currentVal = instance.current;
490
+ store.set(currentVal);
491
+ },
492
+ update(
493
+ updater: (target: T, value: T) => T,
494
+ opts?: TweenedOptions<T>,
495
+ ): Promise<void> {
496
+ return this.set(updater(targetVal, currentVal), opts);
497
+ },
498
+ };
499
+ }
500
+
501
+ export const prefersReducedMotion: MediaQuery = new MediaQuery(
502
+ "(prefers-reduced-motion: reduce)",
503
+ false,
504
+ );