Repository navigation
Expand file tree
/
Copy pathgesture-plan.ts
More file actions
943 lines (880 loc) · 31.2 KB
/
Copy pathgesture-plan.ts
File metadata and controls
943 lines (880 loc) · 31.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
import { AppError } from '@agent-device/kernel/errors';
import type { PublicPlatform } from '@agent-device/kernel/device';
import type { Point, Rect } from '@agent-device/kernel/snapshot';
import {
buildSwipePresetGesturePlan,
gestureDirectionDelta,
isScreenEdgeSwipePreset,
type SwipePreset,
} from './scroll-gesture.ts';
import {
DEFAULT_DRAG_DESTINATION_HOLD_MS,
DEFAULT_DRAG_MOVE_MS,
DEFAULT_DRAG_SOURCE_HOLD_MS,
DEFAULT_TAP_HOLD_MS,
GESTURE_DURATION_MAX_MS,
GESTURE_DURATION_MIN_MS,
GESTURE_MAX_CONTACTS,
GESTURE_TAP_MIN_CONTACTS,
GESTURE_VIEWPORT_INSET_PX,
} from './gesture-plan-types.ts';
import type {
GesturePlan,
GestureExecutionProfile,
GestureSemanticInput,
HumanTrajectoryMode,
PointerTrajectory,
PointerTrajectorySample,
SinglePointerGesturePlan,
SinglePointerTrajectory,
TapGesturePlan,
TapPointerId,
TwoContactGesturePlan,
} from './gesture-plan-types.ts';
export const GESTURE_SAMPLE_INTERVAL_MS = 16;
export const GESTURE_INITIAL_ANGLE_DEGREES = -90;
const GESTURE_FLING_DEFAULT_DISTANCE = 180;
const GESTURE_INITIAL_SPAN_RATIO = 0.25;
const GESTURE_PINCH_INITIAL_SPAN_RATIO = 0.4;
const GESTURE_HORIZONTAL_ANGLE_DEGREES = 0;
const GESTURE_MINIMUM_RELIABLE_SPAN_PX = 48;
const DEFAULT_PAN_DURATION_MS = 500;
export const GESTURE_FLING_DURATION_MS = 100;
const DEFAULT_MULTI_TOUCH_DURATION_MS = 300;
const MAX_ROTATION_DEGREES_PER_SAMPLE = 3;
const MAX_ROTATION_DEFAULT_DURATION_MS = 2_400;
export type GestureSamplingProfile = 'default' | 'android';
type GesturePlatformProfile = {
pinchAxisDegrees: number;
samplingProfile: GestureSamplingProfile;
};
const DEFAULT_GESTURE_PLATFORM_PROFILE: GesturePlatformProfile = {
pinchAxisDegrees: GESTURE_INITIAL_ANGLE_DEGREES,
samplingProfile: 'default',
};
const GESTURE_PLATFORM_PROFILES = {
ios: DEFAULT_GESTURE_PLATFORM_PROFILE,
macos: DEFAULT_GESTURE_PLATFORM_PROFILE,
android: {
pinchAxisDegrees: GESTURE_HORIZONTAL_ANGLE_DEGREES,
samplingProfile: 'android',
},
harmonyos: DEFAULT_GESTURE_PLATFORM_PROFILE,
vega: DEFAULT_GESTURE_PLATFORM_PROFILE,
linux: DEFAULT_GESTURE_PLATFORM_PROFILE,
web: DEFAULT_GESTURE_PLATFORM_PROFILE,
} satisfies Record<PublicPlatform, GesturePlatformProfile>;
/** Plans one physical gesture. Public aliases must be normalized before this boundary. */
export function buildGesturePlan(
input: GestureSemanticInput,
viewport: Rect,
platform?: PublicPlatform,
): GesturePlan {
const frame = normalizeViewport(viewport);
const profile = gesturePlatformProfile(platform);
switch (input.intent) {
case 'fling':
return buildFlingPlan(input, frame);
case 'pan':
return buildPanPlan(input, frame, profile);
case 'pinch':
return buildTransformPlan(
{
intent: 'pinch',
origin: input.origin ?? centerOfViewport(frame),
delta: { x: 0, y: 0 },
scale: normalizeScale(input.scale, 'gesture pinch scale'),
rotationDegrees: 0,
durationMs: DEFAULT_MULTI_TOUCH_DURATION_MS,
},
frame,
profile,
);
case 'rotate': {
const rotationDegrees = finiteNumber(input.degrees, 'gesture rotate degrees');
return buildTransformPlan(
{
intent: 'rotate',
origin: input.origin ?? centerOfViewport(frame),
delta: { x: 0, y: 0 },
scale: 1,
rotationDegrees,
durationMs: defaultTransformDuration(rotationDegrees),
},
frame,
profile,
);
}
case 'transform': {
const rotationDegrees = finiteNumber(input.degrees, 'gesture transform degrees');
return buildTransformPlan(
{
intent: 'transform',
origin: input.origin,
delta: input.delta,
scale: normalizeScale(input.scale, 'gesture transform scale'),
rotationDegrees,
durationMs: normalizeDuration(
input.durationMs,
defaultTransformDuration(rotationDegrees),
'gesture transform durationMs',
),
},
frame,
profile,
);
}
case 'tap':
return buildTapPlan(input, frame);
}
}
export function singlePointerPlanEndpoints(plan: SinglePointerGesturePlan): {
start: Point;
end: Point;
} {
const [{ samples }] = plan.pointers;
const start = samples[0];
const end = samples.at(-1)!;
return { start: start.point, end: end.point };
}
/**
* Plans one uninterrupted pointer contact: activate at the source, move to the
* destination, optionally hold there, then release. Element targets are
* resolved by the interaction runtime before this portable planning seam.
*/
export function buildDragGesturePlan(
input: {
from: Point;
to: Point;
sourceHoldMs?: number;
moveMs?: number;
destinationHoldMs?: number;
},
viewport: Rect,
): SinglePointerGesturePlan {
const frame = normalizeViewport(viewport);
const sourceHoldMs = normalizePositiveDuration(
input.sourceHoldMs,
DEFAULT_DRAG_SOURCE_HOLD_MS,
'gesture drag sourceHoldMs',
);
const moveMs = normalizeDuration(input.moveMs, DEFAULT_DRAG_MOVE_MS, 'gesture drag moveMs');
const destinationHoldMs = normalizeNonNegativeDuration(
input.destinationHoldMs,
DEFAULT_DRAG_DESTINATION_HOLD_MS,
'gesture drag destinationHoldMs',
);
const durationMs = sourceHoldMs + moveMs + destinationHoldMs;
if (durationMs > GESTURE_DURATION_MAX_MS) {
throw new AppError(
'INVALID_ARGS',
`gesture drag total duration must be at most ${GESTURE_DURATION_MAX_MS}`,
);
}
const move = buildSinglePointerPlan('pan', input.from, input.to, moveMs, frame, 'timed-pan');
return withContactHolds(move, sourceHoldMs, destinationHoldMs);
}
function withContactHolds(
plan: SinglePointerGesturePlan,
sourceHoldMs: number,
destinationHoldMs: number,
): SinglePointerGesturePlan {
const pointer = plan.pointers[0];
const [moveStart, moveEnd] = pointer.samples;
const durationMs = sourceHoldMs + plan.durationMs + destinationHoldMs;
const samples: SinglePointerTrajectory['samples'] = [
{ offsetMs: 0, point: moveStart.point },
{ ...moveStart, offsetMs: moveStart.offsetMs + sourceHoldMs },
{ ...moveEnd, offsetMs: moveEnd.offsetMs + sourceHoldMs },
...(destinationHoldMs > 0 ? [{ offsetMs: durationMs, point: moveEnd.point }] : []),
];
return {
...plan,
durationMs,
pointers: [
{
...pointer,
samples,
},
],
};
}
function buildFlingPlan(
input: Extract<GestureSemanticInput, { intent: 'fling' }>,
viewport: Rect,
): SinglePointerGesturePlan {
if ('preset' in input) {
const { from, to } = presetGestureEndpoints(input.preset, viewport);
const plan = buildSinglePointerPlan(
'fling',
from,
to,
GESTURE_FLING_DURATION_MS,
viewport,
'endpoint-hold',
);
return isScreenEdgeSwipePreset(input.preset) ? { ...plan, contactOrigin: 'screen-edge' } : plan;
}
if ('from' in input) {
return buildSinglePointerPlan(
'fling',
input.from,
input.to,
GESTURE_FLING_DURATION_MS,
viewport,
'endpoint-hold',
);
}
const start = finitePoint(input.origin, 'gesture fling origin');
const distance = positiveNumber(
input.distance ?? GESTURE_FLING_DEFAULT_DISTANCE,
'gesture fling distance',
);
return buildSinglePointerPlan(
'fling',
start,
addPoints(start, gestureDirectionDelta(input.direction, distance)),
GESTURE_FLING_DURATION_MS,
viewport,
'endpoint-hold',
);
}
function buildPanPlan(
input: Extract<GestureSemanticInput, { intent: 'pan' }>,
viewport: Rect,
profile: GesturePlatformProfile,
): GesturePlan {
const durationMs = normalizeDuration(
input.durationMs,
DEFAULT_PAN_DURATION_MS,
'gesture pan durationMs',
);
if ((input.pointerCount ?? 1) === 1) {
const start = finitePoint(input.origin, 'gesture pan origin');
const delta = finitePoint(input.delta, 'gesture pan delta');
return buildSinglePointerPlan(
'pan',
start,
addPoints(start, delta),
durationMs,
viewport,
input.executionProfile ?? 'timed-pan',
input.trajectory,
);
}
if (input.pointerCount !== 2) {
throw new AppError('INVALID_ARGS', 'gesture pan pointerCount must be 1 or 2');
}
return buildTransformPlan(
{
intent: 'pan',
origin: input.origin,
delta: input.delta,
scale: 1,
rotationDegrees: 0,
durationMs,
},
viewport,
profile,
);
}
function buildSinglePointerPlan(
intent: SinglePointerGesturePlan['intent'],
from: Point,
to: Point,
durationMs: number,
viewport: Rect,
executionProfile: GestureExecutionProfile,
trajectory?: HumanTrajectoryMode,
): SinglePointerGesturePlan {
const start = finitePoint(from, `gesture ${intent} start`);
const end = finitePoint(to, `gesture ${intent} end`);
const samples: SinglePointerTrajectory['samples'] =
trajectory === 'human'
? buildHumanTrajectorySamples({ from: start, to: end, durationMs, viewport })
: [
{ offsetMs: 0, point: start },
{ offsetMs: durationMs, point: end },
];
assertSamplesInViewport(samples, viewport, { intent, pointerId: 0 });
return {
topology: 'single',
intent,
executionProfile,
durationMs,
viewport,
...(trajectory === 'human' ? { trajectory } : {}),
pointers: [{ pointerId: 0, samples }],
};
}
function buildTransformPlan(
motion: {
intent: TwoContactGesturePlan['intent'];
origin: Point;
delta: Point;
scale: number;
rotationDegrees: number;
durationMs: number;
},
viewport: Rect,
profile: GesturePlatformProfile,
): TwoContactGesturePlan {
const start = finitePoint(motion.origin, `gesture ${motion.intent} origin`);
const delta = finitePoint(motion.delta, `gesture ${motion.intent} delta`);
const end = addPoints(start, delta);
const maximumSpan =
Math.min(viewport.width, viewport.height) * initialSpanRatioForIntent(motion.intent);
const initialSpan = motion.scale > 1 ? maximumSpan / motion.scale : maximumSpan;
const finalSpan = initialSpan * motion.scale;
if (Math.min(initialSpan, finalSpan) < GESTURE_MINIMUM_RELIABLE_SPAN_PX) {
throw trajectoryOutOfBounds({
intent: motion.intent,
viewport,
initialSpan,
finalSpan,
minimumReliableSpan: GESTURE_MINIMUM_RELIABLE_SPAN_PX,
});
}
const initialRadius = initialSpan / 2;
const offsets = sampleGestureOffsets(motion.durationMs, profile.samplingProfile);
const trajectory = (pointerId: 0 | 1, side: 1 | -1): PointerTrajectory => {
const samples = offsets.map((offsetMs) => ({
offsetMs,
point: transformPointAt({
...motion,
start,
end,
initialRadius,
offsetMs,
side,
profile,
}),
}));
assertSamplesInViewport(samples, viewport, { intent: motion.intent, pointerId });
return { pointerId, samples };
};
return {
topology: 'multi',
intent: motion.intent,
durationMs: motion.durationMs,
viewport,
pointers: [trajectory(0, 1), trajectory(1, -1)],
};
}
function transformPointAt(options: {
intent: TwoContactGesturePlan['intent'];
start: Point;
end: Point;
initialRadius: number;
scale: number;
rotationDegrees: number;
durationMs: number;
offsetMs: number;
side: 1 | -1;
profile: GesturePlatformProfile;
}): Point {
const progress = options.offsetMs / options.durationMs;
const centroid = interpolateGesturePoint(options.start, options.end, progress);
const radius = options.initialRadius * (1 + (options.scale - 1) * progress);
const angle = degreesToRadians(
initialAngleForIntent(options.intent, options.profile) + options.rotationDegrees * progress,
);
return {
x: centroid.x + Math.cos(angle) * radius * options.side,
y: centroid.y + Math.sin(angle) * radius * options.side,
};
}
function initialAngleForIntent(
intent: TwoContactGesturePlan['intent'],
profile: GesturePlatformProfile,
): number {
return intent === 'pinch' ? profile.pinchAxisDegrees : GESTURE_INITIAL_ANGLE_DEGREES;
}
function initialSpanRatioForIntent(intent: TwoContactGesturePlan['intent']): number {
return intent === 'pinch' ? GESTURE_PINCH_INITIAL_SPAN_RATIO : GESTURE_INITIAL_SPAN_RATIO;
}
function buildTapPlan(
input: Extract<GestureSemanticInput, { intent: 'tap' }>,
viewport: Rect,
): TapGesturePlan {
const durationMs = normalizeDuration(input.holdMs, DEFAULT_TAP_HOLD_MS, 'gesture tap holdMs');
const points = tapContactPoints(input.points);
const pointers = points.map((point, index): PointerTrajectory<TapPointerId> => {
const samples = [
{ offsetMs: 0, point },
{ offsetMs: durationMs, point },
];
assertSamplesInViewport(samples, viewport, { intent: 'tap', pointerId: index });
return { pointerId: index as TapPointerId, samples };
});
return {
topology: 'multi',
intent: 'tap',
durationMs,
viewport,
pointers: pointers as unknown as TapGesturePlan['pointers'],
};
}
function tapContactPoints(points: readonly Point[]): Point[] {
if (points.length < GESTURE_TAP_MIN_CONTACTS || points.length > GESTURE_MAX_CONTACTS) {
throw new AppError(
'INVALID_ARGS',
`gesture tap requires ${GESTURE_TAP_MIN_CONTACTS} to ${GESTURE_MAX_CONTACTS} points`,
{ pointCount: points.length, hint: 'Use press for a single contact.' },
);
}
const finite = points.map((point, index) => finitePoint(point, `gesture tap point ${index + 1}`));
finite.forEach((point, index) => {
const earlier = finite.findIndex((other) => other.x === point.x && other.y === point.y);
if (earlier !== index) {
throw new AppError('INVALID_ARGS', 'gesture tap points must be distinct', {
reason: 'GESTURE_TAP_DUPLICATE_POINT',
point,
hint: 'Give each contact its own coordinates.',
});
}
});
return finite;
}
/** The floor of three frames is what lets transport lowering claim a denser-than-endpoints path. */
export function sampleGestureOffsets(
durationMs: number,
profile: GestureSamplingProfile,
): number[] {
if (!Number.isFinite(durationMs) || durationMs <= 0) {
throw new AppError('INVALID_ARGS', 'gesture sample duration must be a positive finite number');
}
const rawFrameCount = durationMs / GESTURE_SAMPLE_INTERVAL_MS;
const frameCount = Math.max(
3,
profile === 'android' ? Math.round(rawFrameCount) : Math.floor(rawFrameCount),
);
return Array.from({ length: frameCount + 1 }, (_, index) =>
Math.round((durationMs * index) / frameCount),
);
}
function assertSamplesInViewport(
samples: readonly { offsetMs: number; point: Point }[],
viewport: Rect,
details: Record<string, unknown>,
): void {
const maxX = viewport.x + viewport.width - GESTURE_VIEWPORT_INSET_PX;
const maxY = viewport.y + viewport.height - GESTURE_VIEWPORT_INSET_PX;
for (const sample of samples) {
const { x, y } = sample.point;
if (!Number.isFinite(x) || !Number.isFinite(y)) {
throw new AppError('INVALID_ARGS', 'Gesture motion produces non-finite pointer coordinates', {
...details,
reason: 'GESTURE_TRAJECTORY_NON_FINITE',
hint: 'Reduce the requested rotation, translation, or scale.',
});
}
if (
x < viewport.x + GESTURE_VIEWPORT_INSET_PX ||
x > maxX ||
y < viewport.y + GESTURE_VIEWPORT_INSET_PX ||
y > maxY
) {
throw trajectoryOutOfBounds({ ...details, viewport, sample });
}
}
}
function trajectoryOutOfBounds(details: Record<string, unknown>): AppError {
return new AppError('INVALID_ARGS', 'Gesture trajectory does not fit inside the viewport', {
...details,
reason: 'GESTURE_TRAJECTORY_OUT_OF_BOUNDS',
hint: 'Move the gesture away from the edge or reduce its translation, scale, or rotation.',
});
}
function normalizeViewport(viewport: Rect): Rect {
const frame = {
x: finiteNumber(viewport.x, 'gesture viewport x'),
y: finiteNumber(viewport.y, 'gesture viewport y'),
width: finiteNumber(viewport.width, 'gesture viewport width'),
height: finiteNumber(viewport.height, 'gesture viewport height'),
};
if (frame.width <= 0 || frame.height <= 0) {
throw new AppError('INVALID_ARGS', 'gesture viewport width and height must be positive');
}
return frame;
}
function normalizeDuration(value: number | undefined, fallback: number, field: string): number {
const durationMs = value ?? fallback;
if (
!Number.isInteger(durationMs) ||
durationMs < GESTURE_DURATION_MIN_MS ||
durationMs > GESTURE_DURATION_MAX_MS
) {
throw new AppError(
'INVALID_ARGS',
`${field} must be an integer between ${GESTURE_DURATION_MIN_MS} and ${GESTURE_DURATION_MAX_MS}`,
);
}
return durationMs;
}
function normalizePositiveDuration(value: number | undefined, fallback: number, field: string) {
const durationMs = value ?? fallback;
if (!Number.isInteger(durationMs) || durationMs < 1 || durationMs > GESTURE_DURATION_MAX_MS) {
throw new AppError(
'INVALID_ARGS',
`${field} must be an integer between 1 and ${GESTURE_DURATION_MAX_MS}`,
);
}
return durationMs;
}
function normalizeNonNegativeDuration(value: number | undefined, fallback: number, field: string) {
const durationMs = value ?? fallback;
if (!Number.isInteger(durationMs) || durationMs < 0 || durationMs > GESTURE_DURATION_MAX_MS) {
throw new AppError(
'INVALID_ARGS',
`${field} must be an integer between 0 and ${GESTURE_DURATION_MAX_MS}`,
);
}
return durationMs;
}
function defaultTransformDuration(rotationDegrees: number): number {
const rotationDuration =
Math.ceil(Math.abs(rotationDegrees) / MAX_ROTATION_DEGREES_PER_SAMPLE) *
GESTURE_SAMPLE_INTERVAL_MS;
return Math.min(
Math.max(DEFAULT_MULTI_TOUCH_DURATION_MS, rotationDuration),
MAX_ROTATION_DEFAULT_DURATION_MS,
);
}
function finitePoint(point: Point, field: string): Point {
return {
x: finiteNumber(point.x, `${field} x`),
y: finiteNumber(point.y, `${field} y`),
};
}
function finiteNumber(value: number, field: string): number {
if (!Number.isFinite(value)) {
throw new AppError('INVALID_ARGS', `${field} must be a finite number`);
}
return value;
}
function normalizeScale(value: number, field: string): number {
const scale = finiteNumber(value, field);
if (scale <= 0) throw new AppError('INVALID_ARGS', `${field} must be greater than 0`);
return scale;
}
function positiveNumber(value: number, field: string): number {
const number = finiteNumber(value, field);
if (number <= 0) throw new AppError('INVALID_ARGS', `${field} must be a positive number`);
return number;
}
function centerOfViewport(viewport: Rect): Point {
return { x: viewport.x + viewport.width / 2, y: viewport.y + viewport.height / 2 };
}
function addPoints(left: Point, right: Point): Point {
return { x: left.x + right.x, y: left.y + right.y };
}
export function interpolateGesturePoint(start: Point, end: Point, progress: number): Point {
return {
x: start.x + (end.x - start.x) * progress,
y: start.y + (end.y - start.y) * progress,
};
}
function presetGestureEndpoints(preset: SwipePreset, viewport: Rect): { from: Point; to: Point } {
const relative = buildSwipePresetGesturePlan(preset, {
referenceWidth: viewport.width,
referenceHeight: viewport.height,
});
return {
from: { x: viewport.x + relative.x1, y: viewport.y + relative.y1 },
to: { x: viewport.x + relative.x2, y: viewport.y + relative.y2 },
};
}
function gesturePlatformProfile(platform: PublicPlatform | undefined): GesturePlatformProfile {
return platform === undefined
? DEFAULT_GESTURE_PLATFORM_PROFILE
: GESTURE_PLATFORM_PROFILES[platform];
}
function degreesToRadians(degrees: number): number {
return (degrees * Math.PI) / 180;
}
/**
* The canonical dense samples a human-hand gesture carries. The phases below share one
* parameterized generator so a caller requests realism, not a byte-exact curve: the same input
* always rebuilds the same samples, and different inputs never collide into one curve.
*/
export const HUMAN_TRAJECTORY_MIN_SAMPLES = 20;
const HUMAN_TRAJECTORY_SAMPLE_INTERVAL_MS = 16;
/** Main-path share of the sample timeline; the rest spends overshoot and settle-back. */
const MAIN_PATH_END_FRACTION = 0.72;
const OVERSHOOT_END_FRACTION = 0.86;
const DEFAULT_OVERSHOOT_RATIO = 0.05;
const DEFAULT_OVERSHOOT_MAX_PX = 24;
const DEFAULT_WOBBLE_PX = 1.5;
const WOBBLE_HARMONIES = 2;
const WOBBLE_FREQUENCY_MIN_HZ = 1.2;
const WOBBLE_FREQUENCY_MAX_HZ = 2.6;
export type HumanTrajectoryOptions = Readonly<{
/** Target spacing between samples; the count floor wins over a sparse timeline. */
sampleIntervalMs?: number;
/** Fraction of the travel distance the hand travels past the destination before settling. */
overshootRatio?: number;
/** Absolute cap on the overshoot excursion in pixels. */
overshootMaxPx?: number;
/** Cap on the perpendicular wobble amplitude in pixels. */
wobblePx?: number;
/** Seed for the deterministic wobble; defaults to a hash of the endpoints and duration. */
seed?: number;
}>;
export type HumanTrajectoryInput = Readonly<{
from: Point;
to: Point;
durationMs: number;
viewport: Rect;
options?: HumanTrajectoryOptions;
}>;
/**
* Builds the canonical samples of one human-like single-pointer stroke: a slow onset that
* accelerates along the main path, an overshoot past the destination, a settle back onto it, and
* a bounded perpendicular wobble. First and last samples sit exactly on `from` and `to`; every
* offset stays inside `durationMs`; every point stays inside the viewport insets the plan
* assertion enforces. Pure in its inputs, including the wobble seed.
*/
export function buildHumanTrajectorySamples(
input: HumanTrajectoryInput,
): [PointerTrajectorySample, PointerTrajectorySample, ...PointerTrajectorySample[]] {
const { from, to } = readStrokeEndpoints(input);
const durationMs = readStrokeDuration(input.durationMs);
const viewport = input.viewport;
const intervalMs = readSampleInterval(input.options?.sampleIntervalMs);
const sampleCount = sampleCountFor(durationMs, intervalMs);
const sampleOffsets = strokeOffsets(durationMs, sampleCount);
const prng = mulberry32(input.options?.seed ?? defaultStrokeSeed(input));
const wobblePx = positive(input.options?.wobblePx, DEFAULT_WOBBLE_PX, 'wobblePx');
const wobble = wobbleShape(from, to, wobblePx, prng);
const overshootPx = overshootDistance(from, to, viewport, input.options, prng);
const dense = sampleOffsets.map((offsetMs, index) => {
const progress = index / (sampleCount - 1);
return {
offsetMs,
point: strokePointAt({
from,
to,
progress,
overshootPx,
wobble,
viewport,
}),
};
});
// `sampleCountFor` floors the timeline at `HUMAN_TRAJECTORY_MIN_SAMPLES`, so the stroke always
// satisfies the canonical single-pointer tuple the plan builder assigns it to.
return dense as [PointerTrajectorySample, PointerTrajectorySample, ...PointerTrajectorySample[]];
}
/**
* The point one stroke carries at `progress` of its sample timeline. The main path eases in and
* out, the overshoot excursion leaves and decays, the settle lands exactly on the destination,
* and the envelope-narrowed wobble rides on top.
*/
function strokePointAt(stroke: {
from: Point;
to: Point;
progress: number;
overshootPx: number;
wobble: (progress: number) => number;
viewport: Rect;
}): Point {
const { from, to, progress } = stroke;
if (progress <= 0) return { ...from };
if (progress >= 1) return { ...to };
const basePoint = mainPathPoint(from, to, progress, stroke.overshootPx);
const wobbleOffset = stroke.wobble(progress);
const direction = strokeDirection(from, to);
const point = {
x: basePoint.x + direction.y * wobbleOffset,
y: basePoint.y - direction.x * wobbleOffset,
};
return clampToViewport(point, stroke.viewport);
}
/** Eases the main path and folds the overshoot excursion and settle-back into the tail. */
function mainPathPoint(from: Point, to: Point, progress: number, overshootPx: number): Point {
const dx = to.x - from.x;
const dy = to.y - from.y;
if (progress <= MAIN_PATH_END_FRACTION) {
const mainProgress = progress / MAIN_PATH_END_FRACTION;
// Inlined smoothstep: the freerange check cannot verify the call-argument flow here.
const eased = mainProgress * mainProgress * (3 - 2 * mainProgress);
return { x: from.x + dx * eased, y: from.y + dy * eased };
}
const direction = strokeDirection(from, to);
if (progress <= OVERSHOOT_END_FRACTION) {
// Leaves the destination along the stroke direction, decelerating into the excursion peak.
const overshootSpan = OVERSHOOT_END_FRACTION - MAIN_PATH_END_FRACTION;
const peak = easeOutQuad((progress - MAIN_PATH_END_FRACTION) / overshootSpan);
return {
x: to.x + direction.x * overshootPx * peak,
y: to.y + direction.y * overshootPx * peak,
};
}
// Settle-back: from the excursion peak onto the exact destination.
const settleTail = 1 - OVERSHOOT_END_FRACTION;
const settleProgress = (progress - OVERSHOOT_END_FRACTION) / settleTail;
const eased = smoothstep(settleProgress);
return {
x: to.x + direction.x * overshootPx * (1 - eased),
y: to.y + direction.y * overshootPx * (1 - eased),
};
}
function strokeDirection(from: Point, to: Point): Point {
const dx = to.x - from.x;
const dy = to.y - from.y;
const length = Math.hypot(dx, dy);
if (length === 0) return { x: 0, y: 0 };
return { x: dx / length, y: dy / length };
}
/**
* The seeded perpendicular wobble. Two incommensurate sine harmonics read as irregular hand
* drift; a sine envelope pins both stroke endpoints to zero wobble.
*/
function wobbleShape(
from: Point,
to: Point,
wobblePx: number,
prng: () => number,
): (progress: number) => number {
const length = Math.hypot(to.x - from.x, to.y - from.y);
if (length === 0) return () => 0;
const harmonics = Array.from({ length: WOBBLE_HARMONIES }, (_, index) => ({
frequency:
WOBBLE_FREQUENCY_MIN_HZ +
prng() * (WOBBLE_FREQUENCY_MAX_HZ - WOBBLE_FREQUENCY_MIN_HZ) +
index * WOBBLE_FREQUENCY_MIN_HZ,
phase: prng() * Math.PI * 2,
weight: index === 0 ? 0.6 : 0.4,
}));
return (progress: number) => {
const envelope = Math.sin(Math.PI * progress);
const drift = harmonics.reduce(
(sum, harmonic) =>
sum +
harmonic.weight * Math.sin(2 * Math.PI * harmonic.frequency * progress + harmonic.phase),
0,
);
return wobblePx * envelope * drift;
};
}
/** Overshoot scales with travel, caps absolutely, and never leaves the viewport. */
function overshootDistance(
from: Point,
to: Point,
viewport: Rect,
options: HumanTrajectoryOptions | undefined,
prng: () => number,
): number {
const distance = Math.hypot(to.x - from.x, to.y - from.y);
if (distance === 0) return 0;
const ratio = positive(options?.overshootRatio, DEFAULT_OVERSHOOT_RATIO, 'overshootRatio');
const maxPx = positive(options?.overshootMaxPx, DEFAULT_OVERSHOOT_MAX_PX, 'overshootMaxPx');
// A short stroke overshoots less: the excursion stays proportional until the cap bites.
const proportional = distance * ratio;
const bounded = Math.min(proportional, maxPx, distance / 2);
const direction = strokeDirection(from, to);
const candidate = bounded * (0.7 + 0.6 * prng());
const headroom = overshootHeadroom(to, direction, viewport);
return Math.min(candidate, headroom);
}
/** How far past `to` the stroke may travel before a viewport inset stops it. */
function overshootHeadroom(to: Point, direction: Point, viewport: Rect): number {
const maxX = viewport.x + viewport.width - GESTURE_VIEWPORT_INSET_PX;
const maxY = viewport.y + viewport.height - GESTURE_VIEWPORT_INSET_PX;
const bounds =
direction.x > 0 ? maxX : direction.x < 0 ? viewport.x + GESTURE_VIEWPORT_INSET_PX : to.x;
const vertical =
direction.y > 0 ? maxY : direction.y < 0 ? viewport.y + GESTURE_VIEWPORT_INSET_PX : to.y;
const roomX =
direction.x === 0 ? Number.POSITIVE_INFINITY : Math.abs(bounds - to.x) / Math.abs(direction.x);
const roomY =
direction.y === 0
? Number.POSITIVE_INFINITY
: Math.abs(vertical - to.y) / Math.abs(direction.y);
return Math.min(roomX, roomY);
}
function clampToViewport(point: Point, viewport: Rect): Point {
const minX = viewport.x + GESTURE_VIEWPORT_INSET_PX;
const minY = viewport.y + GESTURE_VIEWPORT_INSET_PX;
const maxX = viewport.x + viewport.width - GESTURE_VIEWPORT_INSET_PX;
const maxY = viewport.y + viewport.height - GESTURE_VIEWPORT_INSET_PX;
return {
x: Math.min(Math.max(point.x, minX), maxX),
y: Math.min(Math.max(point.y, minY), maxY),
};
}
/** Even integer offsets with a monotonic repair for the sub-millisecond tail. */
function strokeOffsets(durationMs: number, sampleCount: number): number[] {
const offsets: number[] = [];
let previous = -1;
for (let index = 0; index < sampleCount; index += 1) {
const linear = (durationMs * index) / (sampleCount - 1);
const offsetMs = Math.min(durationMs, Math.max(previous + 1, Math.round(linear)));
offsets.push(offsetMs);
previous = offsetMs;
}
return offsets;
}
function sampleCountFor(durationMs: number, intervalMs: number): number {
return Math.max(HUMAN_TRAJECTORY_MIN_SAMPLES, Math.floor(durationMs / intervalMs) + 1);
}
function readStrokeEndpoints(input: HumanTrajectoryInput): { from: Point; to: Point } {
const from = finiteStrokePoint(input.from, 'from');
const to = finiteStrokePoint(input.to, 'to');
return { from, to };
}
function readStrokeDuration(durationMs: number): number {
if (!Number.isInteger(durationMs) || durationMs <= 0) {
throw new AppError('INVALID_ARGS', 'human trajectory durationMs must be a positive integer');
}
return durationMs;
}
function readSampleInterval(intervalMs: number | undefined): number {
const value = intervalMs ?? HUMAN_TRAJECTORY_SAMPLE_INTERVAL_MS;
if (!Number.isInteger(value) || value <= 0) {
throw new AppError(
'INVALID_ARGS',
'human trajectory sampleIntervalMs must be a positive integer',
);
}
return value;
}
function finiteStrokePoint(point: Point, field: string): Point {
if (!Number.isFinite(point.x) || !Number.isFinite(point.y)) {
throw new AppError('INVALID_ARGS', `human trajectory ${field} must be a finite point`);
}
return point;
}
function positive(value: number | undefined, fallback: number, field: string): number {
const resolved = value ?? fallback;
if (!Number.isFinite(resolved) || resolved <= 0) {
throw new AppError('INVALID_ARGS', `human trajectory ${field} must be a positive number`);
}
return resolved;
}
function smoothstep(progress: number): number {
return progress * progress * (3 - 2 * progress);
}
function easeOutQuad(progress: number): number {
return 1 - (1 - progress) * (1 - progress);
}
/** Deterministic default seed so one request rebuilds one curve and two requests differ. */
function defaultStrokeSeed(input: HumanTrajectoryInput): number {
const source = `${input.from.x},${input.from.y},${input.to.x},${input.to.y},${input.durationMs}`;
let hash = 0x811c9dc5;
for (let index = 0; index < source.length; index += 1) {
hash ^= source.charCodeAt(index);
hash = Math.imul(hash, 0x01000193);
}
return hash >>> 0;
}
function mulberry32(seed: number): () => number {
let state = seed >>> 0;
return () => {
state = (state + 0x6d2b79f5) | 0;
let t = Math.imul(state ^ (state >>> 15), 1 | state);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}