@klex/mascot 0.0.0-stage → 0.1.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.
package/src/glide.ts ADDED
@@ -0,0 +1,848 @@
1
+ import { gsap } from 'gsap';
2
+
3
+ import { createActivity, type KlexActivity } from './activity';
4
+ import {
5
+ type Emote,
6
+ type EmoteLook,
7
+ emoteLook,
8
+ emotePose,
9
+ REST_EMOTE,
10
+ } from './emotes';
11
+ import { fitGaze, gazeRoom } from './gaze';
12
+ import { mirroredOutline, phoneAnchor, waveAnchor } from './geometry';
13
+ import { BODY_SHAPES, type BodyShape, DEFAULT_GLIDE } from './presets';
14
+ import { roundedPath } from './svg';
15
+
16
+ export { DEFAULT_GLIDE } from './presets';
17
+
18
+ type GlideSettings = typeof DEFAULT_GLIDE;
19
+ export type KlexPosition = { x: number; y: number };
20
+
21
+ function setAttribute(
22
+ element: Element | null | undefined,
23
+ name: string,
24
+ value: string,
25
+ ) {
26
+ if (element && element.getAttribute(name) !== value)
27
+ element.setAttribute(name, value);
28
+ }
29
+
30
+ function transformSetter(
31
+ element: HTMLElement | SVGElement,
32
+ property: string,
33
+ unit?: string,
34
+ ) {
35
+ const set = gsap.quickSetter(element, property, unit);
36
+ let previous: number | undefined;
37
+ return (value: number) => {
38
+ if (value === previous) return;
39
+ previous = value;
40
+ set(value);
41
+ };
42
+ }
43
+
44
+ const REST = {
45
+ facing: 1,
46
+ look: 1,
47
+ lean: 0,
48
+ drag: 0,
49
+ energy: 0,
50
+ phase: 0,
51
+ crawl: 1,
52
+ floating: 0,
53
+ compression: 0,
54
+ };
55
+
56
+ const damp = (from: number, to: number, rate: number, dt: number) =>
57
+ to + (from - to) * Math.exp(-rate * dt);
58
+
59
+ function crawlReach(pose: typeof REST, settings: GlideSettings) {
60
+ return (
61
+ Math.sin(pose.phase) *
62
+ pose.energy *
63
+ pose.crawl *
64
+ settings.softness *
65
+ Math.min(18, settings.wavelength / (Math.PI * 2))
66
+ );
67
+ }
68
+
69
+ function compressPoint(x: number, y: number, compression: number) {
70
+ return [
71
+ 80 + (x - 80) * (1 + compression * 0.5),
72
+ 128 + (y - 128) * (1 - compression),
73
+ ] as const;
74
+ }
75
+
76
+ function headMotion(
77
+ pose: typeof REST,
78
+ settings: GlideSettings,
79
+ shape: BodyShape,
80
+ reaction = REST_EMOTE,
81
+ ) {
82
+ const nod =
83
+ settings.nod *
84
+ settings.softness *
85
+ pose.energy *
86
+ Math.sin(pose.phase + 0.35);
87
+ const angle =
88
+ pose.facing *
89
+ (nod * 0.065 + reaction.nod * 0.14 + (reaction.headTilt * Math.PI) / 180);
90
+ const pivotX =
91
+ 80 +
92
+ (shape.eyeX - 8) * pose.facing +
93
+ pose.facing * crawlReach(pose, settings) +
94
+ settings.softness * pose.lean * 8;
95
+ return {
96
+ angle: (angle * 180) / Math.PI,
97
+ point(x: number, y: number, weight = 1, point: [number, number] = [0, 0]) {
98
+ const rotation = angle * weight;
99
+ const dx = x - pivotX;
100
+ const pivotY = shape.eyeY + 39;
101
+ const dy = y - pivotY;
102
+ point[0] =
103
+ pivotX +
104
+ dx * Math.cos(rotation) -
105
+ dy * Math.sin(rotation) +
106
+ (reaction.headSway * pose.facing + reaction.gazeHeadX) * weight ** 2;
107
+ point[1] =
108
+ pivotY +
109
+ dx * Math.sin(rotation) +
110
+ dy * Math.cos(rotation) +
111
+ (nod + reaction.nod) * 2 * weight +
112
+ reaction.gazeHeadY * weight ** 2;
113
+ return point;
114
+ },
115
+ };
116
+ }
117
+
118
+ function deformPoint(
119
+ x: number,
120
+ y: number,
121
+ reaction: typeof REST_EMOTE,
122
+ bodyHeight: number,
123
+ eyeOffset: number,
124
+ point: [number, number] = [0, 0],
125
+ ) {
126
+ const height = (128 - y) / 110;
127
+ const h = Math.min(1, Math.max(0, (128 - y) / bodyHeight));
128
+ // A moving band swells both sides of the belly. The crown and sole have
129
+ // zero weight, so this reads as jelly travelling upwards, not a head shake.
130
+ const ripple =
131
+ reaction.ripple === 0
132
+ ? 0
133
+ : reaction.ripple *
134
+ Math.sin(reaction.ripplePhase - h * Math.PI * 2) *
135
+ Math.sin(h * Math.PI) ** 2;
136
+ const center = 80 + eyeOffset * h;
137
+ point[0] =
138
+ 80 +
139
+ (x - 80) * (1 + reaction.puff * 0.12) +
140
+ (reaction.wave === 0
141
+ ? 0
142
+ : reaction.wave * Math.sin(height * Math.PI * 2) * height) +
143
+ (x - center) * ripple * 0.48;
144
+ point[1] = 128 + (y - 128) * (1 + reaction.puff * 0.04) + ripple * 2;
145
+ return point;
146
+ }
147
+
148
+ function rotatePoint(x: number, y: number, angle: number) {
149
+ const radians = (angle * Math.PI) / 180;
150
+ return [
151
+ 80 + (x - 80) * Math.cos(radians) - (y - 126) * Math.sin(radians),
152
+ 126 + (x - 80) * Math.sin(radians) + (y - 126) * Math.cos(radians),
153
+ ] as const;
154
+ }
155
+
156
+ const bodyHeights = new WeakMap<BodyShape, number>();
157
+
158
+ export function bodyRig(
159
+ pose: typeof REST,
160
+ settings: GlideSettings,
161
+ shape: BodyShape,
162
+ reaction: typeof REST_EMOTE,
163
+ points: [number, number][] = [],
164
+ ) {
165
+ const { facing, lean, drag, energy, phase } = pose;
166
+ const { softness } = settings;
167
+ const reach = crawlReach(pose, settings);
168
+ const head = headMotion(pose, settings, shape, reaction);
169
+ const outline = shape.outline;
170
+ const mirrored = mirroredOutline(shape);
171
+ let bodyHeight = bodyHeights.get(shape);
172
+ if (bodyHeight === undefined) {
173
+ bodyHeight = 128 - Math.min(...outline.map((point) => point[1]));
174
+ bodyHeights.set(shape, bodyHeight);
175
+ }
176
+ const blend = (facing + 1) / 2;
177
+ const shoulder = shape.eyeY + 7;
178
+ const gathering =
179
+ pose.crawl * softness * energy * Math.max(0, -Math.sin(phase));
180
+ const compression = Math.min(
181
+ 0.45,
182
+ Math.max(-0.2, pose.compression + reaction.compression),
183
+ );
184
+ const radians = (reaction.roll * facing * Math.PI) / 180;
185
+ const cosine = Math.cos(radians);
186
+ const sine = Math.sin(radians);
187
+ let minX = Infinity;
188
+ let maxX = -Infinity;
189
+ let maxY = -Infinity;
190
+ points.length = outline.length;
191
+ for (let index = 0; index < outline.length; index++) {
192
+ const [rightX, rightY] = outline[index] ?? [80, 128];
193
+ let point = points[index];
194
+ if (!point) {
195
+ point = [0, 0];
196
+ points[index] = point;
197
+ }
198
+ const [leftX, leftY] = mirrored[index] ?? [160 - rightX, rightY];
199
+ let x = leftX * (1 - blend) + rightX * blend;
200
+ let y = leftY * (1 - blend) + rightY * blend;
201
+ const belly = Math.min(1, Math.max(0, (y - shoulder) / (128 - shoulder)));
202
+ // The trailing mass tucks behind the body in front view, not out to its sides.
203
+ x = 80 + (x - 80) * (1 - (0.05 + 0.15 * belly) * (1 - facing * facing));
204
+ const tail = Math.max(0, (-facing * (x - 80)) / 66);
205
+ const segment =
206
+ 1 -
207
+ belly +
208
+ belly * Math.min(1, Math.max(-1, (facing * (x - 80) + 8) / 38));
209
+ // Front and tail alternate their advance. Mass bunches above the sole
210
+ // as the rear catches up; the underside never lifts like a fabric hem.
211
+ x += facing * reach * segment;
212
+ x += softness * (lean * 8 * (1 - belly) - drag * 5 * tail);
213
+ x -= facing * gathering * 5 * tail;
214
+ y += pose.crawl * softness * energy * 12 * (1 - belly);
215
+ y -= gathering * 28 * belly * (1 - belly);
216
+ y -= pose.floating * 8 * belly * Math.min(1, Math.abs(x - 80) / 55);
217
+ head.point(x, y, 1 - belly, point);
218
+ const compressedX = 80 + (point[0] - 80) * (1 + compression * 0.5);
219
+ const compressedY = 128 + (point[1] - 128) * (1 - compression);
220
+ deformPoint(
221
+ compressedX,
222
+ compressedY,
223
+ reaction,
224
+ bodyHeight,
225
+ shape.eyeX * facing,
226
+ point,
227
+ );
228
+ const [deformedX, deformedY] = point;
229
+ const angle = (index / outline.length) * Math.PI * 2;
230
+ const meltedX =
231
+ reaction.melt === 0
232
+ ? deformedX
233
+ : deformedX * (1 - reaction.melt) +
234
+ (80 + 61 * Math.sin(angle)) * reaction.melt;
235
+ const meltedY =
236
+ reaction.melt === 0
237
+ ? deformedY
238
+ : deformedY * (1 - reaction.melt) +
239
+ (116 - 12 * Math.cos(angle)) * reaction.melt;
240
+ point[0] = 80 + (meltedX - 80) * cosine - (meltedY - 126) * sine;
241
+ point[1] = 126 + (meltedX - 80) * sine + (meltedY - 126) * cosine;
242
+ if (reaction.roll) {
243
+ minX = Math.min(minX, point[0]);
244
+ maxX = Math.max(maxX, point[0]);
245
+ maxY = Math.max(maxY, point[1]);
246
+ }
247
+ }
248
+ // Rotate the body and face together, keeping the silhouette above the floor.
249
+ const floorOffset = reaction.roll ? maxY - 128 : 0;
250
+ const sideOffset = reaction.roll
251
+ ? ((minX + maxX) / 2 - 80) * Math.min(1, Math.abs(reaction.roll) / 90)
252
+ : 0;
253
+ for (const point of points) {
254
+ point[0] = 80 + (point[0] - sideOffset - 80) * (1 + reaction.impact * 0.3);
255
+ point[1] = 128 + (point[1] - floorOffset - 128) * (1 - reaction.impact);
256
+ }
257
+ return {
258
+ points,
259
+ head,
260
+ floorOffset,
261
+ sideOffset,
262
+ bodyHeight,
263
+ };
264
+ }
265
+
266
+ // The rounded tail and broad sole keep the crawl soft and grounded.
267
+ export function klexBody(
268
+ pose = REST,
269
+ settings = DEFAULT_GLIDE,
270
+ shape: BodyShape = BODY_SHAPES[0],
271
+ reaction = REST_EMOTE,
272
+ ) {
273
+ reaction = fitGaze(
274
+ reaction,
275
+ reaction.lookX || reaction.lookY ? gazeRoom(shape) : 0,
276
+ );
277
+ const displayPose = {
278
+ ...pose,
279
+ facing: pose.facing * (1 - 2 * reaction.turn),
280
+ };
281
+ return roundedPath(bodyRig(displayPose, settings, shape, reaction).points);
282
+ }
283
+
284
+ type GlideElements = {
285
+ travel: HTMLDivElement | SVGGElement;
286
+ actor: HTMLDivElement | SVGGElement;
287
+ shadow: SVGEllipseElement;
288
+ body: SVGPathElement;
289
+ eyes: SVGGElement;
290
+ laptop?: SVGGElement;
291
+ };
292
+
293
+ // Keep one controller for the mounted figure, including interrupted moves.
294
+ export function createGlide(
295
+ { travel, actor, shadow, body, eyes, laptop }: GlideElements,
296
+ onComplete: () => void,
297
+ onEmoteComplete: () => void = () => {},
298
+ onLookChange: (look: EmoteLook) => void = () => {},
299
+ initialSettings: GlideSettings = DEFAULT_GLIDE,
300
+ initialPosition: KlexPosition = { x: 0, y: 0 },
301
+ onDepthChange: (y: number) => void = () => {},
302
+ onArrival: () => void = () => {},
303
+ ) {
304
+ const flyingInitially = initialSettings.mode === 'fly';
305
+ const pose = {
306
+ ...REST,
307
+ crawl: flyingInitially ? 0 : 1,
308
+ floating: flyingInitially ? 1 : 0,
309
+ energy: flyingInitially ? 1 : 0,
310
+ };
311
+ const setX = transformSetter(travel, 'xPercent');
312
+ const setGroundY = transformSetter(travel, 'y', 'px');
313
+ const setY = transformSetter(actor, 'y', 'px');
314
+ const setShake = transformSetter(actor, 'x', 'px');
315
+ const setRotation = transformSetter(actor, 'rotation', 'deg');
316
+ gsap.set(actor, { transformOrigin: '50% 90%' });
317
+ const rigPoints: [number, number][] = [];
318
+ let settings = initialSettings;
319
+ let shape: BodyShape = BODY_SHAPES[0];
320
+ let scale = 1;
321
+ let eyeRoom = gazeRoom(shape);
322
+ let reducedMotion = false;
323
+ let position = gsap.utils.clamp(-50, 50, initialPosition.x);
324
+ let positionY = initialPosition.y;
325
+ let velocity = 0;
326
+ let velocityY = 0;
327
+ let target = position;
328
+ let targetY = positionY;
329
+ let reportedY: number | undefined;
330
+ let direction = 1;
331
+ let paused = false;
332
+ let running = false;
333
+ let busy = false;
334
+ let arrivalPending = false;
335
+ let transitioning = false;
336
+ let disposed = false;
337
+ let height = flyingInitially ? 64 : 0;
338
+ let activity: KlexActivity | false = false;
339
+ const activityMotion = createActivity();
340
+ let emote: { action: Emote; time: number } | null = null;
341
+ let lastLook: EmoteLook = {};
342
+ const leftEye = eyes.querySelector<SVGGElement>('[data-eye="left"]');
343
+ const rightEye = eyes.querySelector<SVGGElement>('[data-eye="right"]');
344
+ const leftClosed = eyes.querySelector<SVGPathElement>(
345
+ '[data-eye-closed="left"]',
346
+ );
347
+ const rightClosed = eyes.querySelector<SVGPathElement>(
348
+ '[data-eye-closed="right"]',
349
+ );
350
+ let hand = eyes.querySelector('[data-wave-anchor]');
351
+ let phone = eyes.querySelector('[data-phone-anchor]');
352
+ let hop: {
353
+ from: number;
354
+ to: number;
355
+ fromY: number;
356
+ toY: number;
357
+ time: number;
358
+ duration: number;
359
+ height: number;
360
+ load: number;
361
+ } | null = null;
362
+
363
+ function render() {
364
+ const laptopScale = reducedMotion
365
+ ? Number(activity === 'working')
366
+ : activityMotion.laptopScale;
367
+ const laptopX = 98 + shape.eyeX * 0.4;
368
+ const laptopY = (Math.max(76, shape.eyeY + 20) + 120) / 2;
369
+ setAttribute(
370
+ laptop,
371
+ 'transform',
372
+ `translate(${shape.eyeX * 0.4 * (pose.facing - 1)} ${reducedMotion ? 0 : activityMotion.workingBob}) translate(${laptopX} ${laptopY}) scale(${laptopScale}) translate(${-laptopX} ${-laptopY})`,
373
+ );
374
+ setAttribute(laptop, 'opacity', String(Number(laptopScale > 0)));
375
+ const resting = !busy && !transitioning && !emote;
376
+ const restingPose = activityMotion.pose(
377
+ reducedMotion ? activity : undefined,
378
+ );
379
+ const rawReaction = emote
380
+ ? emotePose(emote.action.id, emote.time / emote.action.duration)
381
+ : REST_EMOTE;
382
+ const reaction = fitGaze(
383
+ {
384
+ ...rawReaction,
385
+ compression: rawReaction.compression + restingPose.compression,
386
+ headSway: rawReaction.headSway + restingPose.headSway,
387
+ headTilt: rawReaction.headTilt + restingPose.headTilt,
388
+ nod: rawReaction.nod + restingPose.nod,
389
+ lookX: rawReaction.lookX + restingPose.lookX,
390
+ lookY: rawReaction.lookY + restingPose.lookY,
391
+ blinkLeft: emote ? rawReaction.blinkLeft : restingPose.blinkLeft,
392
+ blinkRight: emote ? rawReaction.blinkRight : restingPose.blinkRight,
393
+ },
394
+ eyeRoom,
395
+ );
396
+ const look: EmoteLook = emote
397
+ ? emoteLook(emote.action.id, emote.time / emote.action.duration)
398
+ : resting && activity === 'working'
399
+ ? {
400
+ expression: 'neutral',
401
+ extra:
402
+ !reducedMotion && activityMotion.thinking
403
+ ? 'question'
404
+ : undefined,
405
+ }
406
+ : resting && activity === 'calling'
407
+ ? {
408
+ extra: 'phone',
409
+ expression: reducedMotion
410
+ ? 'neutral'
411
+ : activityMotion.callingExpression,
412
+ }
413
+ : resting && activity === 'sleeping'
414
+ ? { extra: 'sleep' }
415
+ : {};
416
+ if (
417
+ look.expression !== lastLook.expression ||
418
+ look.extra !== lastLook.extra
419
+ ) {
420
+ lastLook = look;
421
+ onLookChange(look);
422
+ }
423
+ const displayPose = {
424
+ ...pose,
425
+ facing: pose.facing * (1 - 2 * reaction.turn),
426
+ };
427
+ const displayHeight = height + reaction.lift;
428
+ setX(position);
429
+ setGroundY(positionY);
430
+ if (positionY !== reportedY) {
431
+ reportedY = positionY;
432
+ onDepthChange(positionY);
433
+ }
434
+ setY(-displayHeight * scale);
435
+ setShake(reaction.shake * pose.facing * scale);
436
+ setRotation(pose.floating * pose.lean * 5);
437
+ setAttribute(
438
+ shadow,
439
+ 'rx',
440
+ String(51 * Math.max(0.25, 1 - displayHeight / 180)),
441
+ );
442
+ setAttribute(
443
+ shadow,
444
+ 'opacity',
445
+ String(0.12 * Math.max(0.15, 1 - displayHeight / 140)),
446
+ );
447
+ const rig = bodyRig(displayPose, settings, shape, reaction, rigPoints);
448
+ setAttribute(body, 'd', roundedPath(rig.points));
449
+ const head = rig.head;
450
+ const [headX, headY] = head.point(
451
+ 80 +
452
+ shape.eyeX * displayPose.facing +
453
+ 3 * (pose.look - pose.facing) +
454
+ displayPose.facing * crawlReach(pose, settings) +
455
+ settings.softness * pose.lean * 8,
456
+ shape.eyeY + pose.crawl * settings.softness * pose.energy * 12,
457
+ );
458
+ const compressed = compressPoint(
459
+ headX,
460
+ headY,
461
+ gsap.utils.clamp(-0.2, 0.45, pose.compression + reaction.compression),
462
+ );
463
+ const [deformedX, deformedY] = deformPoint(
464
+ ...compressed,
465
+ reaction,
466
+ rig.bodyHeight,
467
+ shape.eyeX * displayPose.facing,
468
+ );
469
+ const [eyeX, eyeY] = rotatePoint(
470
+ deformedX * (1 - reaction.melt) +
471
+ (80 + shape.eyeX * displayPose.facing * 0.3) * reaction.melt,
472
+ deformedY * (1 - reaction.melt) + 116 * reaction.melt,
473
+ reaction.roll * displayPose.facing,
474
+ );
475
+ const faceX =
476
+ 80 + (eyeX - rig.sideOffset - 80) * (1 + reaction.impact * 0.3);
477
+ const faceY = 128 + (eyeY - rig.floorOffset - 128) * (1 - reaction.impact);
478
+ const faceAngle =
479
+ head.angle * (1 - reaction.melt) + reaction.roll * displayPose.facing;
480
+ setAttribute(
481
+ eyes,
482
+ 'transform',
483
+ `translate(${faceX} ${faceY}) rotate(${faceAngle})`,
484
+ );
485
+ for (const [attachment, locate] of [
486
+ [hand, waveAnchor],
487
+ [phone, phoneAnchor],
488
+ ] as const) {
489
+ if (!attachment) continue;
490
+ const anchor = locate({
491
+ ...shape,
492
+ outline: rig.points,
493
+ eyeX: faceX - 80,
494
+ eyeY: faceY,
495
+ });
496
+ // Keep attachments on the deformed contour while the face tilts.
497
+ const angle = (-faceAngle * Math.PI) / 180;
498
+ const x = anchor.x * Math.cos(angle) - anchor.y * Math.sin(angle);
499
+ const y = anchor.x * Math.sin(angle) + anchor.y * Math.cos(angle);
500
+ setAttribute(attachment, 'transform', `translate(${x} ${y})`);
501
+ }
502
+ setAttribute(eyes, 'opacity', String(1 - reaction.hideEyes));
503
+ for (const [eye, closed, blink] of [
504
+ [leftEye, leftClosed, reaction.blinkLeft],
505
+ [rightEye, rightClosed, reaction.blinkRight],
506
+ ] as const) {
507
+ const openness = Math.max(0, 1 - blink);
508
+ setAttribute(
509
+ eye,
510
+ 'transform',
511
+ `translate(${reaction.lookX} ${reaction.lookY}) scale(1 ${openness})`,
512
+ );
513
+ // Crossfade into a closed lid rather than making the eye disappear.
514
+ const visible = Math.min(1, openness * 4);
515
+ setAttribute(eye, 'opacity', String(visible));
516
+ setAttribute(closed, 'opacity', String(1 - visible));
517
+ setAttribute(
518
+ closed,
519
+ 'transform',
520
+ `translate(${reaction.lookX} ${reaction.lookY})`,
521
+ );
522
+ }
523
+ }
524
+
525
+ function stop() {
526
+ gsap.ticker.remove(tick);
527
+ running = false;
528
+ }
529
+
530
+ // Resting pose for the current mode, after arrival or when skipping travel.
531
+ function rest() {
532
+ const flying = settings.mode === 'fly';
533
+ height = flying ? 64 : 0;
534
+ Object.assign(pose, REST, {
535
+ facing: direction,
536
+ look: direction,
537
+ crawl: settings.mode === 'crawl' ? 1 : 0,
538
+ floating: flying ? 1 : 0,
539
+ energy: flying ? 1 : 0,
540
+ });
541
+ }
542
+
543
+ function tick(_time: number, deltaMs: number) {
544
+ const flying = settings.mode === 'fly';
545
+ if (reducedMotion) {
546
+ position = target;
547
+ positionY = targetY;
548
+ velocity = 0;
549
+ velocityY = 0;
550
+ hop = null;
551
+ rest();
552
+ transitioning = false;
553
+ stop();
554
+ render();
555
+ if (arrivalPending) {
556
+ arrivalPending = false;
557
+ onArrival();
558
+ if (disposed || arrivalPending) return;
559
+ }
560
+ const completed = busy;
561
+ busy = false;
562
+ render();
563
+ if (completed) onComplete();
564
+ return;
565
+ }
566
+ // Substeps keep braking stable at lower frame rates. Limit elapsed time
567
+ // so returning to a background tab cannot jump the character ahead.
568
+ const elapsed = Math.min(deltaMs / 1000, 0.05);
569
+ const resting = !busy && !transitioning && !emote;
570
+ activityMotion.advance(elapsed, resting ? activity : false);
571
+ if (emote) {
572
+ emote.time += elapsed;
573
+ if (emote.time >= emote.action.duration) {
574
+ emote = null;
575
+ onEmoteComplete();
576
+ }
577
+ }
578
+ // Completion callbacks can start travel. Only then do pixel distances matter;
579
+ // resting avatars avoid flushing layout after another avatar's SVG updates.
580
+ const width = busy ? Math.max(1, travel.clientWidth) : 1;
581
+ const steps = Math.max(1, Math.ceil(elapsed * 120));
582
+ const dt = elapsed / steps;
583
+ for (let i = 0; i < steps; i++) {
584
+ const distance = ((target - position) * width) / 100;
585
+ const distanceY = targetY - positionY;
586
+ const length = Math.hypot(distance, distanceY);
587
+ const desiredSpeed = Math.min(settings.speed, length * 3);
588
+ const desiredY = length ? (distanceY / length) * desiredSpeed : 0;
589
+ let compression = 0;
590
+ if (settings.mode === 'hop') {
591
+ if (!hop && height < 0.1 && busy && length > 0.1) {
592
+ // Equal strides avoid a tiny correction hop at the destination.
593
+ const strides = Math.ceil(length / settings.wavelength);
594
+ const stride = distance / strides;
595
+ const strideY = distanceY / strides;
596
+ const strideLength = Math.hypot(stride, strideY);
597
+ hop = {
598
+ from: position,
599
+ to: position + (stride * 100) / width,
600
+ fromY: positionY,
601
+ toY: positionY + strideY,
602
+ time: 0,
603
+ duration: gsap.utils.clamp(
604
+ 0.55,
605
+ 1.2,
606
+ strideLength / settings.speed,
607
+ ),
608
+ height: Math.min(76, 24 + strideLength * 0.3),
609
+ load: pose.compression,
610
+ };
611
+ }
612
+ if (hop) {
613
+ hop.time = Math.min(hop.duration, hop.time + dt);
614
+ const progress = hop.time / hop.duration;
615
+ const air = gsap.utils.clamp(0, 1, (progress - 0.14) / 0.68);
616
+ position = hop.from + (hop.to - hop.from) * air * air * (3 - 2 * air);
617
+ positionY =
618
+ hop.fromY + (hop.toY - hop.fromY) * air * air * (3 - 2 * air);
619
+ velocity =
620
+ ((((hop.to - hop.from) * width) / 100) * 6 * air * (1 - air)) /
621
+ (hop.duration * 0.68);
622
+ velocityY =
623
+ ((hop.toY - hop.fromY) * 6 * air * (1 - air)) /
624
+ (hop.duration * 0.68);
625
+ height = 4 * hop.height * air * (1 - air);
626
+ pose.phase = progress * Math.PI * 2;
627
+ compression =
628
+ progress < 0.14
629
+ ? hop.load +
630
+ (0.24 * settings.softness - hop.load) *
631
+ Math.sin(((progress / 0.14) * Math.PI) / 2)
632
+ : progress < 0.82
633
+ ? -0.12 * settings.softness * Math.sin(air * Math.PI)
634
+ : 0.24 *
635
+ settings.softness *
636
+ Math.sin((((progress - 0.82) / 0.18) * Math.PI) / 2);
637
+ if (progress === 1) hop = null;
638
+ } else {
639
+ velocity = damp(velocity, 0, 12, dt);
640
+ velocityY = damp(velocityY, 0, 12, dt);
641
+ height = damp(height, 0, 10, dt);
642
+ }
643
+ } else {
644
+ const desired = length ? (distance / length) * desiredSpeed : 0;
645
+ velocity = damp(velocity, desired, 12, dt);
646
+ position += (velocity * dt * 100) / width;
647
+ velocityY = damp(velocityY, desiredY, 12, dt);
648
+ positionY += velocityY * dt;
649
+ pose.phase +=
650
+ ((flying ? settings.speed * 0.45 : Math.hypot(velocity, velocityY)) *
651
+ dt *
652
+ Math.PI *
653
+ 2) /
654
+ settings.wavelength;
655
+ height = damp(
656
+ height,
657
+ flying ? 64 + 7 * Math.sin(pose.phase) : 0,
658
+ 8,
659
+ dt,
660
+ );
661
+ }
662
+ pose.crawl = damp(pose.crawl, settings.mode === 'crawl' ? 1 : 0, 10, dt);
663
+ pose.floating = damp(pose.floating, flying ? 1 : 0, 8, dt);
664
+ pose.compression = damp(pose.compression, compression, 24, dt);
665
+ pose.facing = damp(pose.facing, direction, settings.turn, dt);
666
+ pose.look = damp(pose.look, direction, 15, dt);
667
+ pose.lean = damp(pose.lean, velocity / 180, 11, dt);
668
+ pose.drag = damp(pose.drag, velocity / 180, 5 / settings.lag, dt);
669
+ pose.energy = damp(
670
+ pose.energy,
671
+ flying || hop ? 1 : Math.min(1, Math.hypot(velocity, velocityY) / 80),
672
+ 8,
673
+ dt,
674
+ );
675
+ }
676
+
677
+ // Conversation can begin at the destination while the body settles.
678
+ if (
679
+ arrivalPending &&
680
+ !hop &&
681
+ Math.hypot(((target - position) * width) / 100, targetY - positionY) <
682
+ 2 &&
683
+ Math.hypot(velocity, velocityY) < 12
684
+ ) {
685
+ arrivalPending = false;
686
+ onArrival();
687
+ if (disposed || arrivalPending) return;
688
+ }
689
+
690
+ const arrived =
691
+ !hop &&
692
+ Math.abs(((target - position) * width) / 100) < 0.1 &&
693
+ Math.abs(targetY - positionY) < 0.1 &&
694
+ Math.abs(velocity) < 0.2 &&
695
+ Math.abs(velocityY) < 0.2 &&
696
+ Math.abs(pose.drag) < 0.003 &&
697
+ Math.abs(pose.facing - direction) < 0.003;
698
+ const settled =
699
+ pose.energy < 0.003 &&
700
+ height < 0.1 &&
701
+ Math.abs(pose.compression) < 0.003 &&
702
+ pose.floating < 0.003;
703
+ if (arrived && (flying || settled)) {
704
+ position = target;
705
+ positionY = targetY;
706
+ velocity = 0;
707
+ velocityY = 0;
708
+ transitioning = false;
709
+ if (!flying) {
710
+ rest();
711
+ if (!emote && !activity && !activityMotion.active) stop();
712
+ }
713
+ render();
714
+ if (busy) {
715
+ busy = false;
716
+ onComplete();
717
+ }
718
+ return;
719
+ }
720
+ render();
721
+ }
722
+
723
+ function wake() {
724
+ if (
725
+ !disposed &&
726
+ !running &&
727
+ !paused &&
728
+ (busy ||
729
+ transitioning ||
730
+ emote ||
731
+ ((activity || activityMotion.active) && !reducedMotion) ||
732
+ (settings.mode === 'fly' && !reducedMotion))
733
+ ) {
734
+ running = true;
735
+ gsap.ticker.add(tick);
736
+ }
737
+ }
738
+
739
+ render();
740
+ return {
741
+ playEmote(action: Emote) {
742
+ if (disposed || reducedMotion || emote) return false;
743
+ emote = { action, time: 0 };
744
+ render();
745
+ wake();
746
+ return true;
747
+ },
748
+ cancelEmote() {
749
+ if (!emote) return;
750
+ emote = null;
751
+ onEmoteComplete();
752
+ render();
753
+ },
754
+ moveTo(next: number | KlexPosition) {
755
+ target = gsap.utils.clamp(
756
+ -50,
757
+ 50,
758
+ typeof next === 'number' ? next : next.x,
759
+ );
760
+ targetY = typeof next === 'number' ? positionY : next.y;
761
+ if (target !== position) direction = target < position ? -1 : 1;
762
+ busy = true;
763
+ arrivalPending = true;
764
+ wake();
765
+ },
766
+ shiftBy(offset: KlexPosition) {
767
+ position += offset.x;
768
+ positionY += offset.y;
769
+ target += offset.x;
770
+ targetY += offset.y;
771
+ if (hop) {
772
+ hop.from += offset.x;
773
+ hop.to += offset.x;
774
+ hop.fromY += offset.y;
775
+ hop.toY += offset.y;
776
+ }
777
+ render();
778
+ },
779
+ snapTo(next: KlexPosition) {
780
+ position = target = gsap.utils.clamp(-50, 50, next.x);
781
+ positionY = targetY = next.y;
782
+ velocity = velocityY = 0;
783
+ hop = null;
784
+ busy = false;
785
+ arrivalPending = false;
786
+ rest();
787
+ render();
788
+ },
789
+ face(side: 'left' | 'right') {
790
+ direction = side === 'left' ? -1 : 1;
791
+ pose.facing = pose.look = direction;
792
+ render();
793
+ },
794
+ stopMoving() {
795
+ target = position;
796
+ targetY = positionY;
797
+ velocity = 0;
798
+ velocityY = 0;
799
+ hop = null;
800
+ busy = false;
801
+ arrivalPending = false;
802
+ },
803
+ configure(
804
+ next: GlideSettings,
805
+ reduced: boolean,
806
+ nextShape: BodyShape = BODY_SHAPES[0],
807
+ nextScale = 1,
808
+ nextIdle = false,
809
+ nextActivity: KlexActivity = 'idle',
810
+ ) {
811
+ hand = eyes.querySelector('[data-wave-anchor]');
812
+ phone = eyes.querySelector('[data-phone-anchor]');
813
+ const modeChanged = settings.mode !== next.mode;
814
+ const motionChanged = reducedMotion !== reduced;
815
+ settings = next;
816
+ reducedMotion = reduced;
817
+ activity = nextActivity === 'idle' && !nextIdle ? false : nextActivity;
818
+ if (reduced) activityMotion.snapLaptop(activity === 'working');
819
+ if (reduced && emote) {
820
+ emote = null;
821
+ onEmoteComplete();
822
+ }
823
+ if (modeChanged || motionChanged) {
824
+ hop = null;
825
+ transitioning = modeChanged || reduced;
826
+ wake();
827
+ }
828
+ if (shape !== nextShape || scale !== nextScale) {
829
+ shape = nextShape;
830
+ scale = nextScale;
831
+ eyeRoom = gazeRoom(shape);
832
+ }
833
+ render();
834
+ wake();
835
+ },
836
+ pause(next: boolean) {
837
+ paused = next;
838
+ if (paused) stop();
839
+ else wake();
840
+ },
841
+ dispose() {
842
+ disposed = true;
843
+ busy = false;
844
+ emote = null;
845
+ stop();
846
+ },
847
+ };
848
+ }