Repository navigation
Expand file tree
/
Copy pathgesture-plan.ts
More file actions
700 lines (661 loc) · 22.1 KB
/
Copy pathgesture-plan.ts
File metadata and controls
700 lines (661 loc) · 22.1 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
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,
} from './gesture-plan-types.ts';
import type {
GesturePlan,
GestureExecutionProfile,
GestureSemanticInput,
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 GESTURE_VIEWPORT_INSET_PX = 1;
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',
);
}
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,
): SinglePointerGesturePlan {
const start = finitePoint(from, `gesture ${intent} start`);
const end = finitePoint(to, `gesture ${intent} end`);
const samples: SinglePointerTrajectory['samples'] = [
{ offsetMs: 0, point: start },
{ offsetMs: durationMs, point: end },
];
assertSamplesInViewport(samples, viewport, { intent, pointerId: 0 });
return {
topology: 'single',
intent,
executionProfile,
durationMs,
viewport,
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),
);
}
/**
* Densifies a plan's own timed path onto one merged sampling grid: the profile grid and the
* canonical offsets merge, every merged offset interpolates inside its canonical segment, and the
* endpoints and duration stay the plan's — the duration IS the last canonical offset, so a
* disagreeing duration cannot be written. This is the one owner of the sampled-path rule; every
* transport lowering calls it instead of keeping its own merge-and-interpolate loop. The optional
* progress hook lets a transport reshape within-segment pacing (Android's controlled scroll) while
* the segment walk and the endpoint rule stay shared.
*/
export function densifyGesturePath(
canonical: readonly PointerTrajectorySample[],
profile: GestureSamplingProfile,
progress: (baseProgress: number, segmentDurationMs: number) => number = (p) => p,
): PointerTrajectorySample[] {
// The walk reads each segment's end, so a path of fewer than two timed samples has no
// interpolable segment; the last offset is the duration the sampling grid builds on.
const durationMs = canonical.at(-1)?.offsetMs ?? 0;
if (canonical.length < 2 || !Number.isFinite(durationMs) || durationMs <= 0) {
throw new AppError('INVALID_ARGS', 'gesture path needs at least two timed samples', {
reason: 'GESTURE_PATH_TOO_SHORT',
});
}
if (
canonical[0]!.offsetMs !== 0 ||
canonical.some(
({ offsetMs }, index) =>
!Number.isFinite(offsetMs) || (index > 0 && offsetMs <= canonical[index - 1]!.offsetMs),
)
) {
throw new AppError(
'INVALID_ARGS',
'gesture path needs a strictly increasing timeline from zero',
{
reason: 'GESTURE_PATH_INVALID_TIMELINE',
},
);
}
const offsets = [
...new Set([
...sampleGestureOffsets(durationMs, profile),
...canonical.map(({ offsetMs }) => offsetMs),
]),
].sort((left, right) => left - right);
let segmentIndex = 0;
return offsets.map((offsetMs) => {
while (
segmentIndex < canonical.length - 2 &&
offsetMs > canonical[segmentIndex + 1]!.offsetMs
) {
segmentIndex += 1;
}
const start = canonical[segmentIndex]!;
const end = canonical[segmentIndex + 1]!;
const segmentDurationMs = end.offsetMs - start.offsetMs;
const baseProgress =
segmentDurationMs === 0 ? 0 : (offsetMs - start.offsetMs) / segmentDurationMs;
return {
offsetMs,
point:
// Both endpoints and every zero-length segment keep the canonical
// point, so the hook only ever reshapes strictly interior offsets.
offsetMs === end.offsetMs || segmentDurationMs === 0
? end.point
: baseProgress === 0
? start.point
: interpolateGesturePoint(
start.point,
end.point,
progress(baseProgress, segmentDurationMs),
),
};
});
}
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;
}