what-core 0.1.1 → 0.3.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.
@@ -0,0 +1,540 @@
1
+ // What Framework - Animation Primitives
2
+ // Springs, tweens, gestures, and transition helpers
3
+
4
+ import { signal, effect, untrack, batch } from './reactive.js';
5
+ import { getCurrentComponent } from './dom.js';
6
+ import { scheduleRead, scheduleWrite } from './scheduler.js';
7
+
8
+ // Create an effect scoped to the current component's lifecycle
9
+ function scopedEffect(fn) {
10
+ const ctx = getCurrentComponent?.();
11
+ const dispose = effect(fn);
12
+ if (ctx) ctx.effects.push(dispose);
13
+ return dispose;
14
+ }
15
+
16
+ // --- Spring Animation ---
17
+ // Physics-based animation with natural feel
18
+
19
+ export function spring(initialValue, options = {}) {
20
+ const {
21
+ stiffness = 100,
22
+ damping = 10,
23
+ mass = 1,
24
+ precision = 0.01,
25
+ } = options;
26
+
27
+ const current = signal(initialValue);
28
+ const target = signal(initialValue);
29
+ const velocity = signal(0);
30
+ const isAnimating = signal(false);
31
+
32
+ let rafId = null;
33
+ let lastTime = null;
34
+
35
+ function tick(time) {
36
+ if (lastTime === null) {
37
+ lastTime = time;
38
+ rafId = requestAnimationFrame(tick);
39
+ return;
40
+ }
41
+
42
+ const dt = Math.min((time - lastTime) / 1000, 0.064); // Cap at ~15fps minimum
43
+ lastTime = time;
44
+
45
+ const currentVal = current.peek();
46
+ const targetVal = target.peek();
47
+ const vel = velocity.peek();
48
+
49
+ // Spring physics
50
+ const displacement = currentVal - targetVal;
51
+ const springForce = -stiffness * displacement;
52
+ const dampingForce = -damping * vel;
53
+ const acceleration = (springForce + dampingForce) / mass;
54
+
55
+ const newVelocity = vel + acceleration * dt;
56
+ const newValue = currentVal + newVelocity * dt;
57
+
58
+ batch(() => {
59
+ velocity.set(newVelocity);
60
+ current.set(newValue);
61
+ });
62
+
63
+ // Check if settled
64
+ if (Math.abs(newVelocity) < precision && Math.abs(displacement) < precision) {
65
+ batch(() => {
66
+ current.set(targetVal);
67
+ velocity.set(0);
68
+ isAnimating.set(false);
69
+ });
70
+ rafId = null;
71
+ lastTime = null;
72
+ return;
73
+ }
74
+
75
+ rafId = requestAnimationFrame(tick);
76
+ }
77
+
78
+ function set(newTarget) {
79
+ target.set(newTarget);
80
+ if (!isAnimating.peek()) {
81
+ isAnimating.set(true);
82
+ lastTime = null;
83
+ rafId = requestAnimationFrame(tick);
84
+ }
85
+ }
86
+
87
+ function stop() {
88
+ if (rafId) {
89
+ cancelAnimationFrame(rafId);
90
+ rafId = null;
91
+ }
92
+ isAnimating.set(false);
93
+ lastTime = null;
94
+ }
95
+
96
+ function snap(value) {
97
+ stop();
98
+ batch(() => {
99
+ current.set(value);
100
+ target.set(value);
101
+ velocity.set(0);
102
+ });
103
+ }
104
+
105
+ return {
106
+ current: () => current(),
107
+ target: () => target(),
108
+ velocity: () => velocity(),
109
+ isAnimating: () => isAnimating(),
110
+ set,
111
+ stop,
112
+ snap,
113
+ subscribe: current.subscribe,
114
+ };
115
+ }
116
+
117
+ // --- Tween Animation ---
118
+ // Easing-based animation
119
+
120
+ export function tween(from, to, options = {}) {
121
+ const {
122
+ duration = 300,
123
+ easing = (t) => t * (2 - t), // easeOutQuad
124
+ onUpdate,
125
+ onComplete,
126
+ } = options;
127
+
128
+ const progress = signal(0);
129
+ const value = signal(from);
130
+ const isAnimating = signal(true);
131
+
132
+ let startTime = null;
133
+ let rafId = null;
134
+
135
+ function tick(time) {
136
+ if (startTime === null) startTime = time;
137
+
138
+ const elapsed = time - startTime;
139
+ const t = Math.min(elapsed / duration, 1);
140
+ const easedT = easing(t);
141
+ const currentValue = from + (to - from) * easedT;
142
+
143
+ batch(() => {
144
+ progress.set(t);
145
+ value.set(currentValue);
146
+ });
147
+
148
+ if (onUpdate) onUpdate(currentValue, t);
149
+
150
+ if (t < 1) {
151
+ rafId = requestAnimationFrame(tick);
152
+ } else {
153
+ isAnimating.set(false);
154
+ if (onComplete) onComplete();
155
+ }
156
+ }
157
+
158
+ rafId = requestAnimationFrame(tick);
159
+
160
+ return {
161
+ progress: () => progress(),
162
+ value: () => value(),
163
+ isAnimating: () => isAnimating(),
164
+ cancel: () => {
165
+ if (rafId) cancelAnimationFrame(rafId);
166
+ isAnimating.set(false);
167
+ },
168
+ subscribe: value.subscribe,
169
+ };
170
+ }
171
+
172
+ // --- Easing Functions ---
173
+
174
+ export const easings = {
175
+ linear: (t) => t,
176
+ easeInQuad: (t) => t * t,
177
+ easeOutQuad: (t) => t * (2 - t),
178
+ easeInOutQuad: (t) => t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t,
179
+ easeInCubic: (t) => t * t * t,
180
+ easeOutCubic: (t) => (--t) * t * t + 1,
181
+ easeInOutCubic: (t) => t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1,
182
+ easeInElastic: (t) => t === 0 ? 0 : t === 1 ? 1 : -Math.pow(2, 10 * t - 10) * Math.sin((t * 10 - 10.75) * ((2 * Math.PI) / 3)),
183
+ easeOutElastic: (t) => t === 0 ? 0 : t === 1 ? 1 : Math.pow(2, -10 * t) * Math.sin((t * 10 - 0.75) * ((2 * Math.PI) / 3)) + 1,
184
+ easeOutBounce: (t) => {
185
+ const n1 = 7.5625;
186
+ const d1 = 2.75;
187
+ if (t < 1 / d1) return n1 * t * t;
188
+ if (t < 2 / d1) return n1 * (t -= 1.5 / d1) * t + 0.75;
189
+ if (t < 2.5 / d1) return n1 * (t -= 2.25 / d1) * t + 0.9375;
190
+ return n1 * (t -= 2.625 / d1) * t + 0.984375;
191
+ },
192
+ };
193
+
194
+ // --- useTransition Hook ---
195
+ // Animate between states
196
+
197
+ export function useTransition(options = {}) {
198
+ const { duration = 300, easing = easings.easeOutQuad } = options;
199
+
200
+ const isTransitioning = signal(false);
201
+ const progress = signal(0);
202
+
203
+ async function start(callback) {
204
+ isTransitioning.set(true);
205
+ progress.set(0);
206
+
207
+ return new Promise((resolve) => {
208
+ const startTime = performance.now();
209
+
210
+ function tick(time) {
211
+ const elapsed = time - startTime;
212
+ const t = Math.min(elapsed / duration, 1);
213
+ progress.set(easing(t));
214
+
215
+ if (t < 1) {
216
+ requestAnimationFrame(tick);
217
+ } else {
218
+ isTransitioning.set(false);
219
+ if (callback) callback();
220
+ resolve();
221
+ }
222
+ }
223
+
224
+ requestAnimationFrame(tick);
225
+ });
226
+ }
227
+
228
+ return {
229
+ isTransitioning: () => isTransitioning(),
230
+ progress: () => progress(),
231
+ start,
232
+ };
233
+ }
234
+
235
+ // --- Gesture Handlers ---
236
+
237
+ export function useGesture(element, handlers = {}) {
238
+ const {
239
+ onDrag,
240
+ onDragStart,
241
+ onDragEnd,
242
+ onPinch,
243
+ onSwipe,
244
+ onTap,
245
+ onLongPress,
246
+ } = handlers;
247
+
248
+ const state = {
249
+ isDragging: signal(false),
250
+ startX: 0,
251
+ startY: 0,
252
+ currentX: signal(0),
253
+ currentY: signal(0),
254
+ deltaX: signal(0),
255
+ deltaY: signal(0),
256
+ velocity: signal({ x: 0, y: 0 }),
257
+ };
258
+
259
+ let lastTime = 0;
260
+ let lastX = 0;
261
+ let lastY = 0;
262
+ let longPressTimer = null;
263
+
264
+ function handleStart(e) {
265
+ const touch = e.touches ? e.touches[0] : e;
266
+ state.startX = touch.clientX;
267
+ state.startY = touch.clientY;
268
+ lastX = touch.clientX;
269
+ lastY = touch.clientY;
270
+ lastTime = performance.now();
271
+
272
+ state.isDragging.set(true);
273
+ if (onDragStart) onDragStart({ x: state.startX, y: state.startY });
274
+
275
+ // Long press detection
276
+ if (onLongPress) {
277
+ longPressTimer = setTimeout(() => {
278
+ if (state.isDragging.peek()) {
279
+ onLongPress({ x: lastX, y: lastY });
280
+ }
281
+ }, 500);
282
+ }
283
+ }
284
+
285
+ function handleMove(e) {
286
+ if (!state.isDragging.peek()) return;
287
+
288
+ const touch = e.touches ? e.touches[0] : e;
289
+ const x = touch.clientX;
290
+ const y = touch.clientY;
291
+ const now = performance.now();
292
+ const dt = now - lastTime;
293
+
294
+ batch(() => {
295
+ state.currentX.set(x);
296
+ state.currentY.set(y);
297
+ state.deltaX.set(x - state.startX);
298
+ state.deltaY.set(y - state.startY);
299
+
300
+ if (dt > 0) {
301
+ state.velocity.set({
302
+ x: (x - lastX) / dt * 1000,
303
+ y: (y - lastY) / dt * 1000,
304
+ });
305
+ }
306
+ });
307
+
308
+ lastX = x;
309
+ lastY = y;
310
+ lastTime = now;
311
+
312
+ if (longPressTimer) {
313
+ // Cancel long press if moved too much
314
+ const distance = Math.sqrt(state.deltaX.peek() ** 2 + state.deltaY.peek() ** 2);
315
+ if (distance > 10) {
316
+ clearTimeout(longPressTimer);
317
+ longPressTimer = null;
318
+ }
319
+ }
320
+
321
+ if (onDrag) {
322
+ onDrag({
323
+ x,
324
+ y,
325
+ deltaX: state.deltaX.peek(),
326
+ deltaY: state.deltaY.peek(),
327
+ velocity: state.velocity.peek(),
328
+ });
329
+ }
330
+ }
331
+
332
+ function handleEnd(e) {
333
+ if (!state.isDragging.peek()) return;
334
+
335
+ if (longPressTimer) {
336
+ clearTimeout(longPressTimer);
337
+ longPressTimer = null;
338
+ }
339
+
340
+ const deltaX = state.deltaX.peek();
341
+ const deltaY = state.deltaY.peek();
342
+ const velocity = state.velocity.peek();
343
+ const distance = Math.sqrt(deltaX ** 2 + deltaY ** 2);
344
+
345
+ // Tap detection
346
+ if (distance < 10 && onTap) {
347
+ onTap({ x: state.startX, y: state.startY });
348
+ }
349
+
350
+ // Swipe detection
351
+ if (onSwipe && (Math.abs(velocity.x) > 500 || Math.abs(velocity.y) > 500)) {
352
+ const direction = Math.abs(velocity.x) > Math.abs(velocity.y)
353
+ ? (velocity.x > 0 ? 'right' : 'left')
354
+ : (velocity.y > 0 ? 'down' : 'up');
355
+ onSwipe({ direction, velocity });
356
+ }
357
+
358
+ if (onDragEnd) {
359
+ onDragEnd({
360
+ deltaX,
361
+ deltaY,
362
+ velocity,
363
+ });
364
+ }
365
+
366
+ state.isDragging.set(false);
367
+ }
368
+
369
+ // Pinch handling (touch only)
370
+ let initialPinchDistance = null;
371
+
372
+ function handlePinchMove(e) {
373
+ if (!onPinch || e.touches.length !== 2) return;
374
+
375
+ const touch1 = e.touches[0];
376
+ const touch2 = e.touches[1];
377
+ const distance = Math.sqrt(
378
+ (touch2.clientX - touch1.clientX) ** 2 +
379
+ (touch2.clientY - touch1.clientY) ** 2
380
+ );
381
+
382
+ if (initialPinchDistance === null) {
383
+ initialPinchDistance = distance;
384
+ }
385
+
386
+ const scale = distance / initialPinchDistance;
387
+ const centerX = (touch1.clientX + touch2.clientX) / 2;
388
+ const centerY = (touch1.clientY + touch2.clientY) / 2;
389
+
390
+ onPinch({ scale, centerX, centerY });
391
+ }
392
+
393
+ function handlePinchEnd() {
394
+ initialPinchDistance = null;
395
+ }
396
+
397
+ // Attach listeners
398
+ if (typeof element === 'function') {
399
+ // Ref function
400
+ scopedEffect(() => {
401
+ const el = untrack(element);
402
+ if (!el) return;
403
+ return attachListeners(el);
404
+ });
405
+ } else if (element?.current !== undefined) {
406
+ // Ref object
407
+ scopedEffect(() => {
408
+ const el = element.current;
409
+ if (!el) return;
410
+ return attachListeners(el);
411
+ });
412
+ } else if (element) {
413
+ attachListeners(element);
414
+ }
415
+
416
+ function attachListeners(el) {
417
+ el.addEventListener('mousedown', handleStart);
418
+ el.addEventListener('touchstart', handleStart, { passive: true });
419
+ window.addEventListener('mousemove', handleMove);
420
+ window.addEventListener('touchmove', handlePinchMove);
421
+ window.addEventListener('touchmove', handleMove);
422
+ window.addEventListener('mouseup', handleEnd);
423
+ window.addEventListener('touchend', handleEnd);
424
+ window.addEventListener('touchend', handlePinchEnd);
425
+
426
+ return () => {
427
+ el.removeEventListener('mousedown', handleStart);
428
+ el.removeEventListener('touchstart', handleStart);
429
+ window.removeEventListener('mousemove', handleMove);
430
+ window.removeEventListener('touchmove', handlePinchMove);
431
+ window.removeEventListener('touchmove', handleMove);
432
+ window.removeEventListener('mouseup', handleEnd);
433
+ window.removeEventListener('touchend', handleEnd);
434
+ window.removeEventListener('touchend', handlePinchEnd);
435
+ };
436
+ }
437
+
438
+ return state;
439
+ }
440
+
441
+ // --- useAnimatedValue Hook ---
442
+ // Like React Native's Animated.Value
443
+
444
+ export function useAnimatedValue(initialValue) {
445
+ const value = signal(initialValue);
446
+ const animations = [];
447
+
448
+ return {
449
+ value: () => value(),
450
+ setValue: (v) => value.set(v),
451
+
452
+ // Spring to target
453
+ spring(toValue, config = {}) {
454
+ const s = spring(value.peek(), config);
455
+ s.set(toValue);
456
+
457
+ const dispose = effect(() => {
458
+ value.set(s.current());
459
+ });
460
+
461
+ return {
462
+ stop: () => { s.stop(); dispose(); },
463
+ };
464
+ },
465
+
466
+ // Tween to target
467
+ timing(toValue, config = {}) {
468
+ const t = tween(value.peek(), toValue, {
469
+ ...config,
470
+ onUpdate: (v) => value.set(v),
471
+ });
472
+
473
+ return {
474
+ stop: () => t.cancel(),
475
+ };
476
+ },
477
+
478
+ // Interpolate value
479
+ interpolate(inputRange, outputRange) {
480
+ return () => {
481
+ const v = value();
482
+ // Find segment
483
+ for (let i = 0; i < inputRange.length - 1; i++) {
484
+ if (v >= inputRange[i] && v <= inputRange[i + 1]) {
485
+ const t = (v - inputRange[i]) / (inputRange[i + 1] - inputRange[i]);
486
+ return outputRange[i] + (outputRange[i + 1] - outputRange[i]) * t;
487
+ }
488
+ }
489
+ // Clamp
490
+ if (v <= inputRange[0]) return outputRange[0];
491
+ return outputRange[outputRange.length - 1];
492
+ };
493
+ },
494
+
495
+ subscribe: value.subscribe,
496
+ };
497
+ }
498
+
499
+ // --- CSS Transition Classes ---
500
+
501
+ export function createTransitionClasses(name) {
502
+ return {
503
+ enter: `${name}-enter`,
504
+ enterActive: `${name}-enter-active`,
505
+ enterDone: `${name}-enter-done`,
506
+ exit: `${name}-exit`,
507
+ exitActive: `${name}-exit-active`,
508
+ exitDone: `${name}-exit-done`,
509
+ };
510
+ }
511
+
512
+ // Apply CSS transition
513
+ export async function cssTransition(element, name, type = 'enter', duration = 300) {
514
+ const classes = createTransitionClasses(name);
515
+
516
+ return new Promise((resolve) => {
517
+ scheduleWrite(() => {
518
+ // Initial state
519
+ element.classList.add(classes[type]);
520
+
521
+ // Force reflow
522
+ scheduleRead(() => {
523
+ element.offsetHeight;
524
+
525
+ scheduleWrite(() => {
526
+ // Active state
527
+ element.classList.add(classes[`${type}Active`]);
528
+
529
+ setTimeout(() => {
530
+ scheduleWrite(() => {
531
+ element.classList.remove(classes[type], classes[`${type}Active`]);
532
+ element.classList.add(classes[`${type}Done`]);
533
+ resolve();
534
+ });
535
+ }, duration);
536
+ });
537
+ });
538
+ });
539
+ });
540
+ }