@krate/motion 0.0.0-stage → 0.5.0-rc.18

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,584 @@
1
+ // Pan and drag. A PanSession follows one pointer from pointerdown (offset,
2
+ // delta, velocity per frame); drag moves the node's x/y motion values, with
3
+ // constraints (an object or a ref to a containing element), elastic edges,
4
+ // direction lock, a momentum (inertia) animation on release and drag
5
+ // controls. Loaded only by elements that use drag or pan props. Ported from
6
+ // framer-motion (MIT, Copyright (c) 2018 Framer B.V.), see NOTICE.
7
+
8
+ import { animateMotionValue } from './animation.js';
9
+ import { cancelFrame, frame, frameData, time } from './frameloop.js';
10
+ import { addDomEvent, addPointerEvent, extractEventInfo, isPrimaryPointer, setDragLock, type EventInfo } from './gestures.js';
11
+ import type { MotionValue } from './motion-value.js';
12
+ import { Feature, type FeatureDefinition, type MotionNode } from './node.js';
13
+ import { percent } from './values.js';
14
+ import { clamp, millisecondsToSeconds, mixNumber, noop, progress, secondsToMilliseconds } from './utils.js';
15
+
16
+ export interface Point {
17
+ x: number;
18
+ y: number;
19
+ }
20
+
21
+ export interface PanInfo {
22
+ point: Point;
23
+ delta: Point;
24
+ offset: Point;
25
+ velocity: Point;
26
+ }
27
+
28
+ interface TimestampedPoint extends Point {
29
+ timestamp: number;
30
+ }
31
+
32
+ interface PanHandlers {
33
+ onSessionStart?: (e: PointerEvent, info: PanInfo) => void;
34
+ onStart?: (e: PointerEvent, info: PanInfo) => void;
35
+ onMove?: (e: PointerEvent, info: PanInfo) => void;
36
+ onEnd?: (e: PointerEvent, info: PanInfo) => void;
37
+ onSessionEnd?: (e: PointerEvent, info: PanInfo) => void;
38
+ resumeAnimation?: () => void;
39
+ }
40
+
41
+ const sub = (a: Point, b: Point): Point => ({ x: a.x - b.x, y: a.y - b.y });
42
+
43
+ function getVelocity(history: TimestampedPoint[], timeDelta: number): Point {
44
+ if (history.length < 2) return { x: 0, y: 0 };
45
+ let i = history.length - 1;
46
+ let p: TimestampedPoint | null = null;
47
+ const last = history[history.length - 1];
48
+ while (i >= 0) {
49
+ p = history[i];
50
+ if (last.timestamp - p.timestamp > secondsToMilliseconds(timeDelta)) break;
51
+ i--;
52
+ }
53
+ if (!p) return { x: 0, y: 0 };
54
+ const t = millisecondsToSeconds(last.timestamp - p.timestamp);
55
+ if (t === 0) return { x: 0, y: 0 };
56
+ const v = { x: (last.x - p.x) / t, y: (last.y - p.y) / t };
57
+ if (v.x === Infinity) v.x = 0;
58
+ if (v.y === Infinity) v.y = 0;
59
+ return v;
60
+ }
61
+
62
+ function getPanInfo({ point }: EventInfo, history: TimestampedPoint[]): PanInfo {
63
+ return { point, delta: sub(point, history[history.length - 1]), offset: sub(point, history[0]), velocity: getVelocity(history, 0.1) };
64
+ }
65
+
66
+ /** Tracks one pointer gesture until release. */
67
+ export class PanSession {
68
+ private startEvent: PointerEvent | null = null;
69
+ private lastMoveEvent: PointerEvent | null = null;
70
+ private lastMoveEventInfo: EventInfo | null = null;
71
+ private pendingMove = false;
72
+ private history: TimestampedPoint[] = [];
73
+ private handlers: PanHandlers = {};
74
+ private removeListeners?: () => void;
75
+ private transformPagePoint?: (p: Point) => Point;
76
+ private distanceThreshold = 3;
77
+ private dragSnapToOrigin = false;
78
+
79
+ constructor(event: PointerEvent, handlers: PanHandlers, { transformPagePoint, dragSnapToOrigin = false, distanceThreshold = 3 }: { transformPagePoint?: (p: Point) => Point; dragSnapToOrigin?: boolean; distanceThreshold?: number } = {}) {
80
+ if (!isPrimaryPointer(event)) return;
81
+ this.dragSnapToOrigin = dragSnapToOrigin;
82
+ this.handlers = handlers;
83
+ this.transformPagePoint = transformPagePoint;
84
+ this.distanceThreshold = distanceThreshold;
85
+ const initial = this.transform(extractEventInfo(event));
86
+ this.history = [{ ...initial.point, timestamp: frameData.timestamp }];
87
+ handlers.onSessionStart?.(event, getPanInfo(initial, this.history));
88
+ const offMove = addPointerEvent(window, 'pointermove', this.handlePointerMove);
89
+ const offUp = addPointerEvent(window, 'pointerup', this.handlePointerUp);
90
+ const offCancel = addPointerEvent(window, 'pointercancel', this.handlePointerUp);
91
+ this.removeListeners = () => {
92
+ offMove();
93
+ offUp();
94
+ offCancel();
95
+ };
96
+ }
97
+
98
+ private transform(info: EventInfo): EventInfo {
99
+ return this.transformPagePoint ? { point: this.transformPagePoint(info.point) } : info;
100
+ }
101
+
102
+ private updatePoint = (): void => {
103
+ this.applyPoint(frameData.timestamp);
104
+ };
105
+
106
+ private applyPoint(timestamp: number): void {
107
+ this.pendingMove = false;
108
+ if (!(this.lastMoveEvent && this.lastMoveEventInfo)) return;
109
+ const info = getPanInfo(this.lastMoveEventInfo, this.history);
110
+ const started = this.startEvent !== null;
111
+ if (!started && Math.hypot(info.offset.x, info.offset.y) < this.distanceThreshold) return;
112
+ this.history.push({ ...info.point, timestamp });
113
+ const { onStart, onMove } = this.handlers;
114
+ if (!started) {
115
+ onStart?.(this.lastMoveEvent, info);
116
+ this.startEvent = this.lastMoveEvent;
117
+ }
118
+ onMove?.(this.lastMoveEvent, info);
119
+ }
120
+
121
+ private handlePointerMove = (event: PointerEvent, info: EventInfo): void => {
122
+ this.lastMoveEvent = event;
123
+ this.lastMoveEventInfo = this.transform(info);
124
+ this.pendingMove = true;
125
+ frame.update(this.updatePoint, true);
126
+ };
127
+
128
+ private handlePointerUp = (event: PointerEvent, info: EventInfo): void => {
129
+ // A move whose frame has not run yet is applied now: a quick drag, or a
130
+ // browser that runs no frame between the moves and the release (WebKit
131
+ // under a burst of input), would otherwise end where the last frame was,
132
+ // or not move at all.
133
+ if (this.pendingMove) {
134
+ cancelFrame(this.updatePoint);
135
+ this.applyPoint(time.now());
136
+ }
137
+ this.end();
138
+ const { onEnd, onSessionEnd, resumeAnimation } = this.handlers;
139
+ if (this.dragSnapToOrigin) resumeAnimation?.();
140
+ if (!(this.lastMoveEvent && this.lastMoveEventInfo)) return;
141
+ const panInfo = getPanInfo(event.type === 'pointercancel' ? this.lastMoveEventInfo : this.transform(info), this.history);
142
+ if (this.startEvent && onEnd) onEnd(event, panInfo);
143
+ onSessionEnd?.(event, panInfo);
144
+ };
145
+
146
+ updateHandlers(handlers: PanHandlers): void {
147
+ this.handlers = handlers;
148
+ }
149
+
150
+ end(): void {
151
+ this.removeListeners?.();
152
+ cancelFrame(this.updatePoint);
153
+ }
154
+ }
155
+
156
+ const asyncHandler = (handler?: (e: PointerEvent, info: PanInfo) => void) => (e: PointerEvent, info: PanInfo) => {
157
+ if (handler) frame.postRender(() => handler(e, info));
158
+ };
159
+
160
+ class PanGesture extends Feature {
161
+ private session?: PanSession;
162
+ private removeListener: () => void = noop as () => void;
163
+ private handlers(): PanHandlers {
164
+ const { onPanSessionStart, onPanStart, onPan, onPanEnd } = this.node.getProps();
165
+ return {
166
+ onSessionStart: asyncHandler(onPanSessionStart),
167
+ onStart: asyncHandler(onPanStart),
168
+ onMove: onPan,
169
+ onEnd: (e, info) => {
170
+ delete this.session;
171
+ if (onPanEnd) frame.postRender(() => onPanEnd(e, info));
172
+ },
173
+ };
174
+ }
175
+ mount(): void {
176
+ this.removeListener = addPointerEvent(this.node.current!, 'pointerdown', (e) => {
177
+ this.session = new PanSession(e, this.handlers(), { transformPagePoint: this.node.getTransformPagePoint() });
178
+ });
179
+ }
180
+ update(): void {
181
+ this.session?.updateHandlers(this.handlers());
182
+ }
183
+ unmount(): void {
184
+ this.removeListener();
185
+ this.session?.end();
186
+ }
187
+ }
188
+
189
+ // Boxes
190
+
191
+ export interface Axis {
192
+ min: number;
193
+ max: number;
194
+ }
195
+
196
+ export interface Box {
197
+ x: Axis;
198
+ y: Axis;
199
+ }
200
+
201
+ const calcLength = (a: Axis): number => a.max - a.min;
202
+
203
+ /** The element's box in page coordinates, measured without its own transform. */
204
+ export function measureLayoutBox(el: HTMLElement | SVGElement): Box {
205
+ const prev = el.style.transform;
206
+ el.style.transform = 'none';
207
+ const r = el.getBoundingClientRect();
208
+ el.style.transform = prev;
209
+ const sx = typeof window !== 'undefined' ? window.scrollX : 0;
210
+ const sy = typeof window !== 'undefined' ? window.scrollY : 0;
211
+ return { x: { min: r.left + sx, max: r.right + sx }, y: { min: r.top + sy, max: r.bottom + sy } };
212
+ }
213
+
214
+ export function measurePageBox(el: Element): Box {
215
+ const r = el.getBoundingClientRect();
216
+ const sx = typeof window !== 'undefined' ? window.scrollX : 0;
217
+ const sy = typeof window !== 'undefined' ? window.scrollY : 0;
218
+ return { x: { min: r.left + sx, max: r.right + sx }, y: { min: r.top + sy, max: r.bottom + sy } };
219
+ }
220
+
221
+ // Constraints
222
+
223
+ export interface Constraint {
224
+ min?: number;
225
+ max?: number;
226
+ }
227
+
228
+ export function applyConstraints(point: number, { min, max }: Constraint, elastic?: Axis): number {
229
+ if (min !== undefined && point < min) point = elastic ? mixNumber(min, point, elastic.min) : Math.max(point, min);
230
+ else if (max !== undefined && point > max) point = elastic ? mixNumber(max, point, elastic.max) : Math.min(point, max);
231
+ return point;
232
+ }
233
+
234
+ export function calcViewportAxisConstraints(layout: Axis, constraints: Axis): Constraint {
235
+ let min = constraints.min - layout.min;
236
+ let max = constraints.max - layout.max;
237
+ if (constraints.max - constraints.min < layout.max - layout.min) [min, max] = [max, min];
238
+ return { min, max };
239
+ }
240
+
241
+ export function calcOrigin(source: Axis, target: Axis): number {
242
+ let origin = 0.5;
243
+ const s = calcLength(source);
244
+ const t = calcLength(target);
245
+ if (t > s) origin = progress(target.min, target.max - s, source.min);
246
+ else if (s > t) origin = progress(source.min, source.max - t, target.min);
247
+ return clamp(0, 1, origin);
248
+ }
249
+
250
+ export const defaultElastic = 0.35;
251
+
252
+ export function resolveDragElastic(elastic: number | boolean | Partial<Record<'top' | 'left' | 'right' | 'bottom', number>> = defaultElastic): { x: Axis; y: Axis } {
253
+ if (elastic === false) elastic = 0;
254
+ else if (elastic === true) elastic = defaultElastic;
255
+ const point = (label: string): number => (typeof elastic === 'number' ? elastic : (elastic as Record<string, number>)[label] || 0);
256
+ return { x: { min: point('left'), max: point('right') }, y: { min: point('top'), max: point('bottom') } };
257
+ }
258
+
259
+ const isRefObject = (v: unknown): v is { current: Element | null } => typeof v === 'object' && v !== null && Object.prototype.hasOwnProperty.call(v, 'current');
260
+
261
+ function shouldDrag(axis: 'x' | 'y', drag: unknown, current: 'x' | 'y' | null): boolean {
262
+ return (drag === true || drag === axis) && (current === null || current === axis);
263
+ }
264
+
265
+ function getCurrentDirection(offset: Point, threshold = 10): 'x' | 'y' | null {
266
+ if (Math.abs(offset.y) > threshold) return 'y';
267
+ if (Math.abs(offset.x) > threshold) return 'x';
268
+ return null;
269
+ }
270
+
271
+ const axes: Array<'x' | 'y'> = ['x', 'y'];
272
+
273
+ /** The drag of one node; also what DragControls start. */
274
+ export class NodeDragControls {
275
+ private openDragLock: (() => void) | null = null;
276
+ isDragging = false;
277
+ private currentDirection: 'x' | 'y' | null = null;
278
+ private originPoint: Point = { x: 0, y: 0 };
279
+ private constraints: false | { x: Constraint; y: Constraint } = false;
280
+ private hasMutatedConstraints = false;
281
+ private elastic = resolveDragElastic();
282
+ private panSession?: PanSession;
283
+ private latestEvent: PointerEvent | null = null;
284
+ private latestInfo: PanInfo | null = null;
285
+ layoutBox?: Box;
286
+
287
+ constructor(public node: MotionNode) {}
288
+
289
+ getProps(): Record<string, any> {
290
+ const p = this.node.getProps();
291
+ return {
292
+ ...p,
293
+ drag: p.drag ?? false,
294
+ dragDirectionLock: p.dragDirectionLock ?? false,
295
+ dragPropagation: p.dragPropagation ?? false,
296
+ dragConstraints: p.dragConstraints ?? false,
297
+ dragElastic: p.dragElastic ?? defaultElastic,
298
+ dragMomentum: p.dragMomentum ?? true,
299
+ };
300
+ }
301
+
302
+ getAxisMotionValue(axis: 'x' | 'y'): MotionValue {
303
+ const props = this.node.getProps();
304
+ const external = props[`_drag${axis.toUpperCase()}`];
305
+ return external || this.node.getValue(axis, (props.initial && typeof props.initial === 'object' ? props.initial[axis] : undefined) || 0)!;
306
+ }
307
+
308
+ start(originEvent: PointerEvent, { snapToCursor = false, distanceThreshold }: { snapToCursor?: boolean; distanceThreshold?: number } = {}): void {
309
+ if (this.node.presence && this.node.presence.isPresent === false) return;
310
+ const onSessionStart = (e: PointerEvent): void => {
311
+ if (this.getProps().dragSnapToOrigin) this.pauseAnimation();
312
+ else this.stopAnimation();
313
+ if (snapToCursor) this.snapToCursor(extractEventInfo(e).point);
314
+ };
315
+ const onStart = (e: PointerEvent, info: PanInfo): void => {
316
+ const { drag, dragPropagation, onDragStart } = this.getProps();
317
+ if (drag && !dragPropagation) {
318
+ this.openDragLock?.();
319
+ this.openDragLock = setDragLock(drag);
320
+ if (!this.openDragLock) return;
321
+ }
322
+ this.latestEvent = e;
323
+ this.latestInfo = info;
324
+ this.isDragging = true;
325
+ this.currentDirection = null;
326
+ this.resolveConstraints();
327
+ if (this.node.projection) this.node.projection.isAnimationBlocked = true;
328
+ for (const axis of axes) {
329
+ let current: any = this.getAxisMotionValue(axis).get() || 0;
330
+ if (percent.test(current) && this.layoutBox) current = calcLength(this.layoutBox[axis]) * (parseFloat(current) / 100);
331
+ this.originPoint[axis] = current;
332
+ }
333
+ if (onDragStart) frame.postRender(() => onDragStart(e, info));
334
+ void this.node.animationState?.setActive('whileDrag', true);
335
+ };
336
+ const onMove = (e: PointerEvent, info: PanInfo): void => {
337
+ this.latestEvent = e;
338
+ this.latestInfo = info;
339
+ const { dragPropagation, dragDirectionLock, onDirectionLock, onDrag } = this.getProps();
340
+ if (!dragPropagation && !this.openDragLock) return;
341
+ const { offset } = info;
342
+ if (dragDirectionLock && this.currentDirection === null) {
343
+ this.currentDirection = getCurrentDirection(offset);
344
+ if (this.currentDirection !== null && onDirectionLock) onDirectionLock(this.currentDirection);
345
+ return;
346
+ }
347
+ this.updateAxis('x', offset);
348
+ this.updateAxis('y', offset);
349
+ this.node.render();
350
+ if (onDrag) onDrag(e, info);
351
+ };
352
+ const onSessionEnd = (e: PointerEvent, info: PanInfo): void => {
353
+ this.latestEvent = e;
354
+ this.latestInfo = info;
355
+ this.stop(e, info);
356
+ this.latestEvent = null;
357
+ this.latestInfo = null;
358
+ };
359
+ const resumeAnimation = (): void => {
360
+ for (const axis of axes) {
361
+ const mv = this.getAxisMotionValue(axis);
362
+ if (mv.animation?.state === 'paused') mv.animation.play();
363
+ }
364
+ };
365
+ this.panSession = new PanSession(
366
+ originEvent,
367
+ { onSessionStart, onStart, onMove, onSessionEnd, resumeAnimation },
368
+ { transformPagePoint: this.node.getTransformPagePoint(), dragSnapToOrigin: this.getProps().dragSnapToOrigin, distanceThreshold },
369
+ );
370
+ }
371
+
372
+ stop(event?: PointerEvent, panInfo?: PanInfo): void {
373
+ const e = event || this.latestEvent;
374
+ const info = panInfo || this.latestInfo;
375
+ const wasDragging = this.isDragging;
376
+ this.cancel();
377
+ if (!wasDragging || !info || !e) return;
378
+ void this.startAnimation(info.velocity);
379
+ const { onDragEnd } = this.getProps();
380
+ if (onDragEnd) frame.postRender(() => onDragEnd(e, info));
381
+ }
382
+
383
+ cancel(): void {
384
+ this.isDragging = false;
385
+ if (this.node.projection) this.node.projection.isAnimationBlocked = false;
386
+ this.panSession?.end();
387
+ this.panSession = undefined;
388
+ if (!this.getProps().dragPropagation && this.openDragLock) {
389
+ this.openDragLock();
390
+ this.openDragLock = null;
391
+ }
392
+ void this.node.animationState?.setActive('whileDrag', false);
393
+ }
394
+
395
+ private updateAxis(axis: 'x' | 'y', offset: Point): void {
396
+ const { drag } = this.getProps();
397
+ if (!offset || !shouldDrag(axis, drag, this.currentDirection)) return;
398
+ let next = this.originPoint[axis] + offset[axis];
399
+ if (this.constraints && this.constraints[axis]) next = applyConstraints(next, this.constraints[axis], this.elastic[axis]);
400
+ this.getAxisMotionValue(axis).set(next);
401
+ }
402
+
403
+ private resolveConstraints(): void {
404
+ const { dragConstraints, dragElastic } = this.getProps();
405
+ if (dragConstraints && isRefObject(dragConstraints)) {
406
+ this.constraints = this.resolveRefConstraints();
407
+ } else if (dragConstraints && typeof dragConstraints === 'object') {
408
+ const { top, left, bottom, right } = dragConstraints as Record<string, number | undefined>;
409
+ this.constraints = { x: { min: left, max: right }, y: { min: top, max: bottom } };
410
+ } else {
411
+ this.constraints = false;
412
+ }
413
+ this.elastic = resolveDragElastic(dragElastic);
414
+ }
415
+
416
+ /** Constraints from a containing element: how far the box can move and stay inside it. */
417
+ private resolveRefConstraints(): false | { x: Constraint; y: Constraint } {
418
+ const { dragConstraints, onMeasureDragConstraints } = this.getProps();
419
+ const el = dragConstraints && dragConstraints.current;
420
+ if (!el || !this.node.current) return false;
421
+ const offset = { x: Number(this.getAxisMotionValue('x').get()) || 0, y: Number(this.getAxisMotionValue('y').get()) || 0 };
422
+ const visual = measurePageBox(this.node.current);
423
+ // The layout box is where the element is with its drag offset removed.
424
+ const layout: Box = { x: { min: visual.x.min - offset.x, max: visual.x.max - offset.x }, y: { min: visual.y.min - offset.y, max: visual.y.max - offset.y } };
425
+ this.layoutBox = layout;
426
+ const box = measurePageBox(el);
427
+ let measured = { x: calcViewportAxisConstraints(layout.x, box.x), y: calcViewportAxisConstraints(layout.y, box.y) };
428
+ if (onMeasureDragConstraints) {
429
+ const user = onMeasureDragConstraints({ top: measured.y.min, left: measured.x.min, bottom: measured.y.max, right: measured.x.max });
430
+ this.hasMutatedConstraints = !!user;
431
+ if (user) measured = { x: { min: user.left, max: user.right }, y: { min: user.top, max: user.bottom } };
432
+ }
433
+ return measured as { x: Constraint; y: Constraint };
434
+ }
435
+
436
+ private startAnimation(velocity: Point): Promise<void> {
437
+ const { drag, dragMomentum, dragElastic, dragTransition, dragSnapToOrigin, onDragTransitionEnd } = this.getProps();
438
+ const constraints: any = this.constraints || {};
439
+ const animations = axes.map((axis) => {
440
+ if (!shouldDrag(axis, drag, this.currentDirection)) return undefined;
441
+ let transition = (constraints && constraints[axis]) || {};
442
+ if (dragSnapToOrigin) transition = { min: 0, max: 0 };
443
+ const inertiaTransition = {
444
+ type: 'inertia',
445
+ velocity: dragMomentum ? velocity[axis] : 0,
446
+ bounceStiffness: dragElastic ? 200 : 1000000,
447
+ bounceDamping: dragElastic ? 40 : 10000000,
448
+ timeConstant: 750,
449
+ restDelta: 1,
450
+ restSpeed: 10,
451
+ ...dragTransition,
452
+ ...transition,
453
+ };
454
+ const mv = this.getAxisMotionValue(axis);
455
+ return mv.start(animateMotionValue(axis, mv, 0, inertiaTransition as any, this.node));
456
+ });
457
+ return Promise.all(animations).then(() => onDragTransitionEnd?.());
458
+ }
459
+
460
+ private stopAnimation(): void {
461
+ for (const axis of axes) this.getAxisMotionValue(axis).stop();
462
+ }
463
+
464
+ private pauseAnimation(): void {
465
+ for (const axis of axes) this.getAxisMotionValue(axis).animation?.pause();
466
+ }
467
+
468
+ private snapToCursor(point: Point): void {
469
+ const { drag } = this.getProps();
470
+ if (!this.node.current) return;
471
+ const box = measureLayoutBox(this.node.current);
472
+ for (const axis of axes) {
473
+ if (!shouldDrag(axis, drag, this.currentDirection)) continue;
474
+ this.getAxisMotionValue(axis).set(point[axis] - mixNumber(box[axis].min, box[axis].max, 0.5));
475
+ }
476
+ }
477
+
478
+ /** On resize, keeps the element at the same relative place inside ref constraints. */
479
+ private scalePositionWithinConstraints(): void {
480
+ const { drag, dragConstraints } = this.getProps();
481
+ if (!isRefObject(dragConstraints) || !this.constraints || !this.node.current) return;
482
+ this.stopAnimation();
483
+ const boxProgress = { x: 0, y: 0 };
484
+ for (const axis of axes) {
485
+ const latest = Number(this.getAxisMotionValue(axis).get()) || 0;
486
+ boxProgress[axis] = calcOrigin({ min: latest, max: latest }, this.constraints[axis] as Axis);
487
+ }
488
+ this.resolveConstraints();
489
+ if (!this.constraints) return;
490
+ for (const axis of axes) {
491
+ if (!shouldDrag(axis, drag, null)) continue;
492
+ const { min = 0, max = 0 } = this.constraints[axis];
493
+ this.getAxisMotionValue(axis).set(mixNumber(min, max, boxProgress[axis]));
494
+ }
495
+ }
496
+
497
+ addListeners(): () => void {
498
+ const el = this.node.current;
499
+ if (!el) return noop as () => void;
500
+ const offDown = addPointerEvent(el, 'pointerdown', (e) => {
501
+ const { drag, dragListener = true } = this.getProps();
502
+ if (drag && dragListener) this.start(e);
503
+ });
504
+ const offResize = addDomEvent(window, 'resize', () => this.scalePositionWithinConstraints());
505
+ let offLayout: (() => void) | undefined;
506
+ frame.read(() => {
507
+ const { dragConstraints } = this.getProps();
508
+ if (isRefObject(dragConstraints) && dragConstraints.current) this.constraints = this.resolveRefConstraints();
509
+ // While dragging, a layout change (a Reorder list moving this item)
510
+ // must not move the element under the pointer.
511
+ const projection = this.node.projection;
512
+ if (projection && projection.addEventListener) {
513
+ offLayout = projection.addEventListener('didUpdate', ({ delta, hasLayoutChanged }: { delta: Point; hasLayoutChanged: boolean }) => {
514
+ if (!this.isDragging || !hasLayoutChanged) return;
515
+ for (const axis of axes) {
516
+ const mv = this.getAxisMotionValue(axis);
517
+ this.originPoint[axis] += delta[axis];
518
+ mv.set((Number(mv.get()) || 0) + delta[axis]);
519
+ }
520
+ this.node.render();
521
+ });
522
+ }
523
+ });
524
+ return () => {
525
+ offDown();
526
+ offResize();
527
+ offLayout?.();
528
+ };
529
+ }
530
+ }
531
+
532
+ /** Starts drags of the elements it is passed to (`dragControls`) from another element's pointerdown. */
533
+ export class DragControls {
534
+ private componentControls = new Set<NodeDragControls>();
535
+ subscribe(controls: NodeDragControls): () => void {
536
+ this.componentControls.add(controls);
537
+ return () => this.componentControls.delete(controls);
538
+ }
539
+ start(event: PointerEvent | { nativeEvent: PointerEvent }, options?: { snapToCursor?: boolean; distanceThreshold?: number }): void {
540
+ const e = (event as { nativeEvent?: PointerEvent }).nativeEvent || (event as PointerEvent);
541
+ this.componentControls.forEach((c) => c.start(e, options));
542
+ }
543
+ cancel(): void {
544
+ this.componentControls.forEach((c) => c.cancel());
545
+ }
546
+ stop(): void {
547
+ this.componentControls.forEach((c) => c.stop());
548
+ }
549
+ }
550
+
551
+ export const createDragControls = (): DragControls => new DragControls();
552
+
553
+ class DragGesture extends Feature {
554
+ controls: NodeDragControls;
555
+ private removeGroupControls: () => void = noop as () => void;
556
+ private removeListeners: () => void = noop as () => void;
557
+ constructor(node: MotionNode) {
558
+ super(node);
559
+ this.controls = new NodeDragControls(node);
560
+ }
561
+ mount(): void {
562
+ const { dragControls } = this.node.getProps();
563
+ if (dragControls) this.removeGroupControls = dragControls.subscribe(this.controls);
564
+ this.removeListeners = this.controls.addListeners();
565
+ const el = this.node.current as HTMLElement | null;
566
+ const { drag, dragListener } = this.node.getProps();
567
+ if (el && drag && dragListener !== false) {
568
+ el.draggable = false;
569
+ el.style.userSelect = 'none';
570
+ (el.style as any).webkitUserSelect = 'none';
571
+ el.style.touchAction = drag === true ? 'none' : `pan-${drag === 'x' ? 'y' : 'x'}`;
572
+ }
573
+ }
574
+ unmount(): void {
575
+ this.removeGroupControls();
576
+ this.removeListeners();
577
+ }
578
+ }
579
+
580
+ /** The drag and pan features (`drag`, `onPan*`). */
581
+ export const dragFeatures: Record<string, FeatureDefinition> = {
582
+ pan: { isEnabled: (p) => !!(p.onPan || p.onPanStart || p.onPanEnd || p.onPanSessionStart), Feature: PanGesture },
583
+ drag: { isEnabled: (p) => !!p.drag || !!p.dragControls, Feature: DragGesture },
584
+ };
@@ -0,0 +1,108 @@
1
+ // Easing functions. Ported from motion-utils (MIT, Copyright (c) 2018 Framer
2
+ // B.V.); the cubic bezier solver is adapted from Gaetan Renaudeau's
3
+ // bezier-easing (MIT). See NOTICE.
4
+
5
+ import { clamp, noop, wrap, type Easing } from './utils.js';
6
+
7
+ export type { Easing };
8
+ export type BezierDefinition = readonly [number, number, number, number];
9
+ export type EasingDefinition =
10
+ | BezierDefinition
11
+ | 'linear'
12
+ | 'easeIn'
13
+ | 'easeOut'
14
+ | 'easeInOut'
15
+ | 'circIn'
16
+ | 'circOut'
17
+ | 'circInOut'
18
+ | 'backIn'
19
+ | 'backOut'
20
+ | 'backInOut'
21
+ | 'anticipate';
22
+ export type EasingModifier = (easing: Easing) => Easing;
23
+
24
+ const calcBezier = (t: number, a1: number, a2: number): number => (((1 - 3 * a2 + 3 * a1) * t + (3 * a2 - 6 * a1)) * t + 3 * a1) * t;
25
+
26
+ function binarySubdivide(x: number, lower: number, upper: number, x1: number, x2: number): number {
27
+ let currentX: number;
28
+ let currentT: number;
29
+ let i = 0;
30
+ do {
31
+ currentT = lower + (upper - lower) / 2;
32
+ currentX = calcBezier(currentT, x1, x2) - x;
33
+ if (currentX > 0) upper = currentT;
34
+ else lower = currentT;
35
+ } while (Math.abs(currentX) > 0.0000001 && ++i < 12);
36
+ return currentT;
37
+ }
38
+
39
+ /** A cubic-bezier easing, like CSS `cubic-bezier(x1, y1, x2, y2)`. */
40
+ export function cubicBezier(x1: number, y1: number, x2: number, y2: number): Easing {
41
+ if (x1 === y1 && x2 === y2) return noop;
42
+ const tForX = (x: number): number => binarySubdivide(x, 0, 1, x1, x2);
43
+ return (t) => (t === 0 || t === 1 ? t : calcBezier(tForX(t), y1, y2));
44
+ }
45
+
46
+ /** Mirrors an easing for the second half: easeIn becomes easeInOut. */
47
+ export const mirrorEasing: EasingModifier = (easing) => (p) => (p <= 0.5 ? easing(2 * p) / 2 : (2 - easing(2 * (1 - p))) / 2);
48
+
49
+ /** Reverses an easing: easeIn becomes easeOut. */
50
+ export const reverseEasing: EasingModifier = (easing) => (p) => 1 - easing(1 - p);
51
+
52
+ export const linear: Easing = noop;
53
+ export const easeIn: Easing = /*@__PURE__*/ cubicBezier(0.42, 0, 1, 1);
54
+ export const easeOut: Easing = /*@__PURE__*/ cubicBezier(0, 0, 0.58, 1);
55
+ export const easeInOut: Easing = /*@__PURE__*/ cubicBezier(0.42, 0, 0.58, 1);
56
+ export const circIn: Easing = (p) => 1 - Math.sin(Math.acos(p));
57
+ export const circOut: Easing = /*@__PURE__*/ reverseEasing(circIn);
58
+ export const circInOut: Easing = /*@__PURE__*/ mirrorEasing(circIn);
59
+ export const backOut: Easing = /*@__PURE__*/ cubicBezier(0.33, 1.53, 0.69, 0.99);
60
+ export const backIn: Easing = /*@__PURE__*/ reverseEasing(backOut);
61
+ export const backInOut: Easing = /*@__PURE__*/ mirrorEasing(backIn);
62
+ export const anticipate: Easing = (p) => ((p *= 2) < 1 ? 0.5 * backIn(p) : 0.5 * (2 - 2 ** (-10 * (p - 1))));
63
+
64
+ /** A stepped easing, like CSS `steps(n, direction)`. */
65
+ export function steps(numSteps: number, direction: 'start' | 'end' = 'end'): Easing {
66
+ return (p) => {
67
+ p = direction === 'end' ? Math.min(p, 0.999) : Math.max(p, 0.001);
68
+ const expanded = p * numSteps;
69
+ const rounded = direction === 'end' ? Math.floor(expanded) : Math.ceil(expanded);
70
+ return clamp(0, 1, rounded / numSteps);
71
+ };
72
+ }
73
+
74
+ const lookup: Record<string, Easing> = {
75
+ linear,
76
+ easeIn,
77
+ easeInOut,
78
+ easeOut,
79
+ circIn,
80
+ circInOut,
81
+ circOut,
82
+ backIn,
83
+ backInOut,
84
+ backOut,
85
+ anticipate,
86
+ };
87
+
88
+ export const isBezierDefinition = (e: unknown): e is BezierDefinition => Array.isArray(e) && typeof e[0] === 'number';
89
+ export const isEasingArray = (e: unknown): e is Array<Easing | EasingDefinition> => Array.isArray(e) && typeof e[0] !== 'number';
90
+
91
+ /** Resolves an easing name, a bezier array or a function to a function. */
92
+ export function easingDefinitionToFunction(def: Easing | EasingDefinition | undefined): Easing {
93
+ if (def === undefined) return noop;
94
+ if (isBezierDefinition(def)) {
95
+ const [x1, y1, x2, y2] = def;
96
+ return cubicBezier(x1, y1, x2, y2);
97
+ }
98
+ if (typeof def === 'string') {
99
+ const fn = lookup[def];
100
+ if (!fn) throw new Error(`@krate/motion: invalid easing type '${def}'`);
101
+ return fn;
102
+ }
103
+ return def;
104
+ }
105
+
106
+ export function getEasingForSegment(easing: any, i: number): any {
107
+ return isEasingArray(easing) ? easing[wrap(0, easing.length, i)] : easing;
108
+ }