Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Mascots hold still at rest; eased blinks, spring blends, authored loops and hover gaze (#6689)
Milind Soni336b1d8d2ccb
diff --git a/DESIGN.md b/DESIGN.mdindex fbe7160db9..9d3947de9b 100644--- a/DESIGN.md+++ b/DESIGN.md@@ -257,6 +257,10 @@ Motion explains a change. It never decorates.animate layout.- **No loops** except a live status that is really live (a bot working).Never animate something just to draw the eye.+- **Mascots hold still at rest.** A mascot moves while its bot is doing+ something, for a beat that explains a change, and under the pointer (its+ eyes follow, it blinks). Every change blends in over about 300ms, and it+ settles and stops when the reason ends.- **Respect reduced motion.** Pair every transition with`motion-reduce:transition-none` and every animation with`motion-reduce:animate-none`, or gate it in CSS ondiff --git a/src/components/Avatar.tsx b/src/components/Avatar.tsxindex d4849c5937..609aee9b6d 100644--- a/src/components/Avatar.tsx+++ b/src/components/Avatar.tsx@@ -5,13 +5,13 @@ import {useImperativeHandle,useRef,useState,- type PointerEvent as ReactPointerEvent,type ReactNode,} from "react";import { cn } from "@/lib/cn";import { avatarMarks, type AvatarKind } from "@/lib/avatar-marks";import { CHROME_EYES, CHROME_GRADIENT, MAUS_COLORS, type MausColor, type MausMotion, type MausState } from "@/lib/mascot";import { CursorAvatar, type CursorAvatarHandle } from "./CursorAvatar";+import { ACTIVE_STATES } from "./mascot-motion";import { avatarCropRadius, botAvatarProfile, clampAvatarFocus, clampAvatarZoom, mascotFaceInk, type BotAvatarCrop, type MascotFaceColor } from "../../shared/bot-avatar";import { MASCOT_BODIES, botMascotBody } from "../../shared/mascot-bodies";import { isCarvedBody, type BotBodyId } from "../../shared/bot-body";@@ -97,6 +97,7 @@ export type MausAvatarProps = {forward?: boolean;lookAround?: number;trackPointer?: boolean;+ /** Left out, the mascot moves only while its state is an activity or a beat plays; at rest it holds still until the pointer comes near. */animated?: boolean;bodyId?: BotBodyId;gradient?: [string, string, string];@@ -147,7 +148,7 @@ function GradientAvatarComponent(forward = true,lookAround,trackPointer = true,- animated = true,+ animated,bodyId,gradient,faceColor,@@ -167,7 +168,7 @@ function GradientAvatarComponent(const [motionState, setMotionState] = useState<MausState | null>(null);useEffect(() => {- if (motion === "none" || !animated) return;+ if (motion === "none" || animated === false) return;const beat = MOTION_FACE[motion];if (!beat) return;if (beat.blink) inner.current?.blink();@@ -178,24 +179,11 @@ function GradientAvatarComponent(return () => clearTimeout(timer);}, [motion, motionKey, animated]);- const [pointer, setPointer] = useState({ x: 0, y: 0 });- const range = forward ? POINTER_GAZE.forward : POINTER_GAZE.authored;- const onPointerMove = (event: ReactPointerEvent<HTMLSpanElement>) => {- if (!trackPointer || !animated) return;- const rect = event.currentTarget.getBoundingClientRect();- setPointer({- x: Math.max(-1, Math.min(1, ((event.clientX - rect.left) / rect.width) * 2 - 1)) * range,- y: Math.max(-1, Math.min(1, ((event.clientY - rect.top) / rect.height) * 2 - 1)) * range,- });- };- const onPointerLeave = () => setPointer({ x: 0, y: 0 });-+ const live = animated ?? (ACTIVE_STATES.has(state) || motionState !== null);return (<span{...avatarMarks(kind, "mascot")}className="inline-flex shrink-0"- onPointerMove={trackPointer && animated ? onPointerMove : undefined}- onPointerLeave={trackPointer && animated ? onPointerLeave : undefined}><CursorAvatarref={inner}@@ -208,13 +196,14 @@ function GradientAvatarComponent(eyeColor={faceInk ?? (chrome ? CHROME_EYES : undefined)}title={label ?? null}lookAround={lookAround ?? (forward ? 0 : 1)}- gaze={{ x: (gaze?.x ?? 0) + pointer.x, y: (gaze?.y ?? 0) + pointer.y }}+ gaze={gaze}turn={turn}spring={spring}eyeScale={eyeScale}showMouth={showMouth}mouthStroke={mouthStroke}- paused={!animated}+ resting={!live}+ pointerGaze={trackPointer ? (forward ? POINTER_GAZE.forward : POINTER_GAZE.authored) : 0}/></span>);diff --git a/src/components/CarvedAvatar.tsx b/src/components/CarvedAvatar.tsxindex 318b821255..4513a614fc 100644--- a/src/components/CarvedAvatar.tsx+++ b/src/components/CarvedAvatar.tsx@@ -12,8 +12,8 @@ import { MAUS_COLORS, type MausColor, type MausMotion, type MausState } from "@/import { avatarMarks, type AvatarKind } from "@/lib/avatar-marks";import { CARVED_BODIES, type CarvedBody, type CarvedBodyId } from "../../shared/carved-bodies";import type { CursorAvatarHandle } from "./CursorAvatar";-import { mascotClock, usePrefersReducedMotion } from "./mascot-clock";-import { frameFloorMs, nextFrameAt } from "./mascot-motion";+import { mascotClock, put, usePrefersReducedMotion, type MascotTicket } from "./mascot-clock";+import { ACTIVE_STATES, HOVER_BLINK_MS, blinkOpenness, frameFloorMs, nextFrameAt } from "./mascot-motion";import { mascotFaceInk, type MascotFaceColor } from "../../shared/bot-avatar";/** Where the face looks and how it feels. */@@ -159,22 +159,23 @@ export type CarvedAvatarProps = {};function CarvedAvatarComponent(- { body: bodyId, color, faceColor, size = 44, state = "idle", motion = "none", motionKey = 0, gaze, trackPointer = true, animated = true, label, kind }: CarvedAvatarProps,+ { body: bodyId, color, faceColor, size = 44, state = "idle", motion = "none", motionKey = 0, gaze, trackPointer = true, animated, label, kind }: CarvedAvatarProps,ref: React.Ref<CursorAvatarHandle>,) {const body = CARVED_BODIES[bodyId];const faceInk = mascotFaceInk(faceColor);const uid = useId().replace(/:/g, "");const reduced = usePrefersReducedMotion();- const live = animated && !reduced;+ const live = !reduced && (animated ?? ACTIVE_STATES.has(state));const group = useRef<SVGGElement>(null);const eyes = [useRef<SVGRectElement>(null), useRef<SVGRectElement>(null)] as const;const smile = useRef<SVGPathElement>(null);const open = useRef<SVGEllipseElement>(null);const pose = useRef<CarvedPose>(moodPose(state));- const cue = useRef({ blinkAt: -1, startleUntil: 0, pointer: null as null | { x: number; y: number } });- const props = useRef({ state, gaze });- props.current = { state, gaze };+ const cue = useRef({ blinkAt: -1, startleUntil: 0, pointer: null as null | { x: number; y: number }, hovered: false });+ const props = useRef({ state, gaze, live });+ props.current = { state, gaze, live };+ const ticket = useRef<MascotTicket | null>(null);const [initial] = useState(() => carvedGeometry(body, pose.current));const startle = () => {@@ -182,41 +183,45 @@ function CarvedAvatarComponent(cue.current.blinkAt = performance.now();};useImperativeHandle(ref, () => ({- blink: () => { cue.current.blinkAt = performance.now(); },- spin: () => startle(),+ blink: () => { cue.current.blinkAt = performance.now(); ticket.current?.wake(); },+ spin: () => {+ startle();+ ticket.current?.wake();+ },setExpression: () => {},}));useEffect(() => {- if (!live || motion === "none") return;+ if (reduced || animated === false || motion === "none") return;if (motion === "blink") cue.current.blinkAt = performance.now();else if (STARTLE.has(motion)) startle();- }, [motion, motionKey, live]);+ ticket.current?.wake();+ }, [motion, motionKey, animated, reduced]);const paint = (p: CarvedPose) => {const g = carvedGeometry(body, p);- group.current?.setAttribute("transform", g.body);+ if (group.current) put(group.current, "transform", g.body);g.eyes.forEach((rect, i) => {const el = eyes[i].current;if (!el) return;- for (const [k, v] of Object.entries(rect)) el.setAttribute(k, String(v));+ for (const [k, v] of Object.entries(rect)) put(el, k, String(v));});if (smile.current) {- smile.current.setAttribute("d", g.smile.d);- smile.current.setAttribute("transform", g.smile.transform);- smile.current.setAttribute("opacity", String(g.smile.opacity));+ put(smile.current, "d", g.smile.d);+ put(smile.current, "transform", g.smile.transform);+ put(smile.current, "opacity", String(g.smile.opacity));}- if (open.current) for (const [k, v] of Object.entries(g.open)) open.current.setAttribute(k, String(v));+ if (open.current) for (const [k, v] of Object.entries(g.open)) put(open.current, k, String(v));};useEffect(() => {- if (live) return;+ if (!reduced) return;pose.current = moodPose(state);paint(pose.current);- }, [state, live, body]);+ }, [state, reduced, body]);useEffect(() => {- if (!live) return;+ if (reduced) return;let last = performance.now();let glanceAt = last + 900 + Math.random() * 2600;let blinkAt = last + 1500 + Math.random() * 3500;@@ -230,15 +235,18 @@ function CarvedAvatarComponent(target = GLANCES[Math.floor(Math.random() * GLANCES.length)];glanceAt = now + (1400 + Math.random() * 3200) / rate;}- if (now > blinkAt) {+ const engaged = props.current.live || cue.current.hovered;+ if (!engaged) blinkAt = now + 300 + Math.random() * 400;+ else if (now > blinkAt) {cue.current.blinkAt = now;- blinkAt = now + 2600 + Math.random() * 4200;+ blinkAt = now + HOVER_BLINK_MS[0] + Math.random() * (HOVER_BLINK_MS[1] - HOVER_BLINK_MS[0]);}const pointer = cue.current.pointer;const outside = props.current.gaze;+ const roam = engaged && rate > 0;const want: CarvedPose = {- gx: pointer?.x ?? (mood.gx ?? (rate > 0 ? target[0] : 0)) + (outside?.x ?? 0),- gy: pointer?.y ?? (mood.gy ?? (rate > 0 ? target[1] : 0)) + (outside?.y ?? 0),+ gx: pointer?.x ?? (mood.gx ?? (roam ? target[0] : 0)) + (outside?.x ?? 0),+ gy: pointer?.y ?? (mood.gy ?? (roam ? target[1] : 0)) + (outside?.y ?? 0),wide: now < cue.current.startleUntil ? 1 : mood.wide ?? 0,shut: mood.shut ?? 0,smile: mood.smile ?? 1,@@ -249,24 +257,45 @@ function CarvedAvatarComponent(p.gy += (Math.max(-1, Math.min(1, want.gy)) - p.gy) * k(9);p.wide += (want.wide - p.wide) * k(want.wide > p.wide ? 18 : 7);p.smile += (want.smile - p.smile) * k(8);- const since = cue.current.blinkAt < 0 ? 1 : (now - cue.current.blinkAt) / 200;- const blink = since >= 1 ? 0 : since < 0.45 ? since / 0.45 : 1 - (since - 0.45) / 0.55;- p.shut += (Math.max(want.shut, blink) - p.shut) * (blink > 0 ? 1 : k(10));+ const open = cue.current.blinkAt < 0 ? null : blinkOpenness(now - cue.current.blinkAt);+ const blink = open === null ? 0 : 1 - open;+ p.shut += (Math.max(want.shut, blink) - p.shut) * (open !== null ? 1 : k(10));paint(p);- return nextFrameAt(now, frameFloorMs(size));+ const settled = open === null && (Object.keys(want) as Array<keyof CarvedPose>).every((key) => Math.abs(want[key] - p[key]) < 0.003);+ if (!engaged && settled) return now < cue.current.startleUntil ? cue.current.startleUntil : Infinity;+ return nextFrameAt(now, frameFloorMs(size, cue.current.hovered));+ };+ const added = mascotClock().add(step, group.current?.ownerSVGElement);+ ticket.current = added;+ return () => {+ added.remove();+ ticket.current = null;};- const ticket = mascotClock().add(step, group.current?.ownerSVGElement);- return () => ticket.remove();- }, [body, live, size]);+ }, [body, reduced, size]);++ useEffect(() => {+ ticket.current?.wake();+ }, [state, live, gaze?.x, gaze?.y]);const onPointerMove = (event: ReactPointerEvent<HTMLSpanElement>) => {+ if (!cue.current.hovered) return;+ ticket.current?.wake();const rect = event.currentTarget.getBoundingClientRect();cue.current.pointer = {x: Math.max(-1, Math.min(1, ((event.clientX - rect.left) / rect.width) * 2 - 1)),y: Math.max(-1, Math.min(1, ((event.clientY - rect.top) / rect.height) * 2 - 1)),};};- const onPointerLeave = () => { cue.current.pointer = null; };+ const onPointerEnter = (event: ReactPointerEvent<HTMLSpanElement>) => {+ if (event.pointerType === "touch") return;+ cue.current.hovered = true;+ ticket.current?.wake();+ };+ const onPointerLeave = () => {+ cue.current.pointer = null;+ cue.current.hovered = false;+ ticket.current?.wake();+ };const fills = carvedFills(body, color);const resolve = (fill: string) => (fill === "body" ? fills.body : fill === "accent" ? fills.accent : fill);@@ -290,8 +319,9 @@ function CarvedAvatarComponent(<span{...avatarMarks(kind, "mascot")}className="inline-flex shrink-0"- onPointerMove={trackPointer && live ? onPointerMove : undefined}- onPointerLeave={trackPointer && live ? onPointerLeave : undefined}+ onPointerEnter={trackPointer && !reduced ? onPointerEnter : undefined}+ onPointerMove={trackPointer && !reduced ? onPointerMove : undefined}+ onPointerLeave={trackPointer && !reduced ? onPointerLeave : undefined}><svgviewBox="-14 -14 268 268"diff --git a/src/components/CursorAvatar.clock.test.ts b/src/components/CursorAvatar.clock.test.tsindex a8571c1257..acdb504c94 100644--- a/src/components/CursorAvatar.clock.test.ts+++ b/src/components/CursorAvatar.clock.test.ts@@ -77,13 +77,13 @@ describe("CursorAvatar on the shared clock", () => {expect(mascotClock().pending()).toBe(12);});- it("draws a sidebar full of working mascots 20 times a second", () => {+ it("draws a sidebar full of working mascots 30 times a second", () => {render(Array.from({ length: 12 }, (_, i) => ({ state: "working" as const, size: [24, 28, 42, 56][i % 4] })));run(100);frameRequests = 0;run(1000);- expect(frameRequests).toBeGreaterThanOrEqual(18);- expect(frameRequests).toBeLessThanOrEqual(21);+ expect(frameRequests).toBeGreaterThanOrEqual(28);+ expect(frameRequests).toBeLessThanOrEqual(33);});it("paints a still mascot with its state's face and then asks for nothing", () => {@@ -137,7 +137,7 @@ describe("CursorAvatar on the shared clock", () => {});it("leaves an alert glyph's layer alone between its appearances", () => {- render([{ state: "confused", size: 64 }]);+ render([{ state: "confused", size: 64, animated: true }]);const { period } = EFFECTS.confused!.glyph!;run(period - (performance.now() % period) + 100);const glyphLayer = [...host.querySelectorAll("svg g")].find((g) => (g as SVGGElement).style.opacity === "0")!;@@ -159,7 +159,7 @@ describe("CursorAvatar on the shared clock", () => {run(2000);expect(frameRequests).toBeGreaterThan(20);run(UNREAD_NOTICE_MS);- run(100);+ run(1000);frameRequests = 0;run(30_000);expect(frameRequests).toBe(0);diff --git a/src/components/CursorAvatar.motion.test.ts b/src/components/CursorAvatar.motion.test.tsnew file mode 100644index 0000000000..cd7c8f08cf--- /dev/null+++ b/src/components/CursorAvatar.motion.test.ts@@ -0,0 +1,346 @@+// @vitest-environment happy-dom+import { act, createElement, createRef } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";++import { MausAvatar, type MausAvatarHandle, type MausAvatarProps } from "./Avatar";+import { mascotClock } from "./mascot-clock";+import { BLINK_MS, MOTION, PoseBlend, REST_POSE, blinkOpenness, bodyPose, criticalSpring, loopSeed } from "./mascot-motion";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++class FakeIntersectionObserver {+ observe() {}+ unobserve() {}+ disconnect() {}+}+vi.stubGlobal("IntersectionObserver", FakeIntersectionObserver);++let reducedMotion = false;+vi.stubGlobal("matchMedia", (query: string) => ({+ get matches() { return query.includes("reduce") && reducedMotion; },+ addEventListener: () => {},+ removeEventListener: () => {},+}));++let host: HTMLDivElement;+let root: Root;++beforeAll(() => {+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "requestAnimationFrame", "cancelAnimationFrame", "performance"] });+});++afterAll(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++beforeEach(() => {+ reducedMotion = false;+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+});++afterEach(() => {+ act(() => root.unmount());+ host.remove();+ vi.restoreAllMocks();+});++const render = (avatars: Array<Partial<MausAvatarProps> & { ref?: React.Ref<MausAvatarHandle> }>) =>+ act(() => root.render(avatars.map((props, key) => createElement(MausAvatar, { key, color: "green", ...props }))));+const run = (ms: number) => act(() => { vi.advanceTimersByTime(ms); });+const svgs = () => [...host.querySelectorAll("svg")];+const bodyOf = (svg: SVGSVGElement) => svg.querySelector(":scope > g > g:nth-child(2)")!;+const eyeOf = (svg: SVGSVGElement) => svg.querySelector("g[clip-path] path")!;++function watch() {+ const records: MutationRecord[] = [];+ const observer = new MutationObserver((batch) => records.push(...batch));+ observer.observe(host, { attributes: true, childList: true, subtree: true, characterData: true });+ const all = () => {+ records.push(...observer.takeRecords());+ return records;+ };+ return {+ attributes: () => all().filter((r) => r.type === "attributes"),+ nodes: () => all().filter((r) => r.type === "childList"),+ stop: () => observer.disconnect(),+ };+}++function placeAt(svg: SVGSVGElement, size: number) {+ vi.spyOn(svg, "getBoundingClientRect").mockReturnValue({ left: 100, top: 100, width: size, height: size, right: 100 + size, bottom: 100 + size, x: 100, y: 100, toJSON: () => ({}) });+}+const pointer = (type: string, x: number, y: number) => {+ const event = new MouseEvent(type, { clientX: x, clientY: y, bubbles: type !== "pointerenter" && type !== "pointerleave" });+ Object.defineProperty(event, "pointerType", { value: "mouse" });+ return event;+};++describe("blink", () => {+ it("closes eased, holds shut, opens past wide and lands, all in 260 ms", () => {+ expect(BLINK_MS).toBe(260);+ expect(blinkOpenness(0)).toBe(1);+ expect(blinkOpenness(20)!).toBeGreaterThan(blinkOpenness(45)!);+ expect(1 - blinkOpenness(10)!).toBeLessThan(0.1);+ const shut = blinkOpenness(95)!;+ expect(shut).toBeLessThan(0.1);+ expect(blinkOpenness(110)).toBe(shut);+ const opening = Array.from({ length: 136 }, (_, i) => blinkOpenness(124 + i)!);+ expect(Math.max(...opening)).toBeGreaterThan(1.02);+ expect(opening.at(-1)!).toBeCloseTo(1, 2);+ expect(blinkOpenness(BLINK_MS)).toBeNull();+ });+});++describe("blends", () => {+ it("springs to its target without overshoot in about 300 ms", () => {+ const samples = Array.from({ length: 60 }, (_, i) => criticalSpring(1, 0, i / 120).x);+ expect(Math.min(...samples)).toBeGreaterThanOrEqual(0);+ expect(criticalSpring(1, 0, 0.3).x).toBeLessThan(0.1);+ expect(criticalSpring(1, 0, 0.6).x).toBeLessThan(0.005);+ });++ it("starts from the shown pose, reaches the target, and picks up mid-blend when interrupted", () => {+ const blend = new PoseBlend();+ const from = { ...REST_POSE, y: -10, rotate: 6 };+ blend.retarget(1000, from, REST_POSE);+ expect(blend.apply(1000, REST_POSE)).toEqual(from);+ const midway = blend.apply(1080, REST_POSE);+ expect(midway.y).toBeGreaterThan(-10);+ expect(midway.y).toBeLessThan(0);+ const next = { ...REST_POSE, x: 8 };+ blend.retarget(1080, midway, next);+ const resumed = blend.apply(1080, next);+ expect(resumed.y).toBeCloseTo(midway.y, 6);+ expect(resumed.x).toBeCloseTo(0, 6);+ expect(blend.apply(2500, next)).toEqual(next);+ expect(blend.blending).toBe(false);+ });+});++describe("loops", () => {+ it("are authored with holds rather than sines, and differ from bot to bot", () => {+ const seed = { phase: 0, variant: 0 };+ const [, period] = MOTION.working.bob;+ const y = (at: number) => bodyPose(MOTION.working, at * period, 1, { seed }).y;+ expect(y(0.25)).toBeCloseTo(y(0.33), 6);+ expect(y(0.25)).not.toBeCloseTo(y(0.1), 1);+ const a = loopSeed("first bot");+ const b = loopSeed("second bot");+ expect(a).not.toEqual(b);+ const sway = (s: typeof a) => bodyPose(MOTION.thinking, 777, 1, { seed: s }).rotate;+ expect(sway(a)).not.toBeCloseTo(sway(b), 2);+ });++ it("gives each mascot its own phase so a list never moves in step", () => {+ render([{ state: "working", size: 60 }, { state: "working", size: 60 }]);+ run(700);+ const [one, two] = svgs();+ expect(bodyOf(one!).getAttribute("transform")).not.toBe(bodyOf(two!).getAttribute("transform"));+ });+});++describe("CursorAvatar at rest and under the pointer", () => {+ it.each([24, 36, 60, 86])("writes nothing at rest at %i px", (size) => {+ render([{ state: "idle", size }, { state: "happy", size, animated: false }]);+ run(500);+ const changes = watch();+ run(20_000);+ expect(changes.attributes()).toEqual([]);+ changes.stop();+ expect(mascotClock().pending()).toBe(0);+ });++ it("follows the pointer within its neighbourhood, blinks, then settles and drops its listener", () => {+ vi.spyOn(Math, "random").mockReturnValue(0.5);+ const adds = vi.spyOn(document, "addEventListener");+ const removes = vi.spyOn(document, "removeEventListener");+ render([{ state: "idle", size: 36, animated: false }]);+ run(200);+ const svg = svgs()[0]!;+ placeAt(svg, 36);+ const moves = () => adds.mock.calls.filter(([type]) => type === "pointermove").length - removes.mock.calls.filter(([type]) => type === "pointermove").length;+ const eyeBefore = eyeOf(svg).getAttribute("transform");+ const changes = watch();+ act(() => { svg.dispatchEvent(pointer("pointerenter", 150, 118)); });+ expect(moves()).toBe(1);+ run(120);+ const shift = svg.querySelector("g[clip-path] > g > g")!;+ expect(shift.getAttribute("transform")).toMatch(/^translate\(\d/);+ run(900);+ expect(eyeOf(svg).getAttribute("transform")).toBe(eyeBefore);+ expect(changes.attributes().some((r) => r.target === eyeOf(svg) && r.attributeName === "transform")).toBe(true);+ act(() => { svg.dispatchEvent(pointer("pointerleave", 160, 118)); });+ act(() => { document.dispatchEvent(pointer("pointermove", 175, 118)); });+ expect(moves()).toBe(1);+ act(() => { document.dispatchEvent(pointer("pointermove", 400, 118)); });+ expect(moves()).toBe(0);+ run(1500);+ expect(shift.getAttribute("transform")).toBeNull();+ expect(mascotClock().pending()).toBe(0);+ expect(changes.nodes()).toEqual([]);+ changes.stop();+ });++ it("drops its pointer listener when unmounted mid-hover", () => {+ const adds = vi.spyOn(document, "addEventListener");+ const removes = vi.spyOn(document, "removeEventListener");+ render([{ state: "idle", size: 36 }]);+ run(100);+ const svg = svgs()[0]!;+ placeAt(svg, 36);+ act(() => { svg.dispatchEvent(pointer("pointerenter", 118, 118)); });+ act(() => root.unmount());+ const added = adds.mock.calls.filter(([type]) => type === "pointermove");+ const removed = removes.mock.calls.filter(([type]) => type === "pointermove");+ expect(added).toHaveLength(1);+ expect(removed.map(([, listener]) => listener)).toEqual(added.map(([, listener]) => listener));+ root = createRoot(host);+ });++ it("blends a change of state instead of cutting, then stops", () => {+ render([{ state: "working", size: 60, animated: true }]);+ run(450);+ const body = bodyOf(svgs()[0]!);+ const working = body.getAttribute("transform");+ expect(working).toBeTruthy();+ const changes = watch();+ render([{ state: "idle", size: 60, animated: false }]);+ run(40);+ expect(body.getAttribute("transform")).toBeTruthy();+ run(1500);+ expect(body.getAttribute("transform")).toBeNull();+ expect(mascotClock().pending()).toBe(0);+ expect(changes.nodes()).toEqual([]);+ changes.stop();+ });++ it("only blinks on its own while engaged", () => {+ render([{ state: "idle", size: 60, animated: false }, { state: "working", size: 60, animated: true }]);+ run(300);+ const [resting, working] = svgs();+ const changes = watch();+ run(15_000);+ const blinked = (svg: SVGSVGElement) => changes.attributes().some((r) => r.target === eyeOf(svg) && r.attributeName === "transform");+ expect(blinked(resting!)).toBe(false);+ expect(blinked(working!)).toBe(true);+ changes.stop();+ });++ it("rewrites only the eye heights through a blink", () => {+ const ref = createRef<MausAvatarHandle>();+ render([{ state: "idle", size: 60, animated: false, ref }]);+ run(300);+ const changes = watch();+ act(() => ref.current!.blink());+ run(BLINK_MS + 100);+ const touched = new Set(changes.attributes().map((r) => `${(r.target as Element).tagName}.${r.attributeName}`));+ expect([...touched]).toEqual(["path.transform"]);+ expect(changes.attributes().length).toBeLessThanOrEqual(2 * Math.ceil((BLINK_MS + 100) / (1000 / 30)));+ changes.stop();+ });++ it("holds still under reduced motion, pointer included", () => {+ reducedMotion = true;+ const adds = vi.spyOn(document, "addEventListener");+ render([{ state: "working", size: 60, animated: true }]);+ run(200);+ const svg = svgs()[0]!;+ placeAt(svg, 60);+ const changes = watch();+ act(() => { svg.dispatchEvent(pointer("pointerenter", 130, 130)); });+ run(3000);+ expect(adds.mock.calls.filter(([type]) => type === "pointermove")).toEqual([]);+ expect(changes.attributes()).toEqual([]);+ expect(mascotClock().pending()).toBe(0);+ changes.stop();+ });++ it("holds a festival body still at rest and wakes it under the pointer", () => {+ render([{ state: "idle", size: 44, bodyId: "pumpkin" }]);+ run(1000);+ const changes = watch();+ run(10_000);+ expect(changes.attributes()).toEqual([]);+ const span = host.querySelector("[data-carved-body]")!.parentElement!;+ const over = pointer("pointerover", 120, 120);+ Object.defineProperty(over, "relatedTarget", { value: null });+ act(() => { span.dispatchEvent(over); });+ run(500);+ expect(changes.attributes().length).toBeGreaterThan(50);+ const out = pointer("pointerout", 400, 400);+ Object.defineProperty(out, "relatedTarget", { value: document.body });+ act(() => { span.dispatchEvent(out); });+ run(3000);+ expect(mascotClock().pending()).toBe(0);+ expect(changes.nodes()).toEqual([]);+ changes.stop();+ });++ it("follows from anywhere in its row and lets go when the pointer leaves the row", () => {+ const adds = vi.spyOn(document, "addEventListener");+ const removes = vi.spyOn(document, "removeEventListener");+ act(() => root.render(createElement("button", { type: "button" }, createElement(MausAvatar, { color: "green", state: "idle", size: 36, animated: false }))));+ run(200);+ const svg = svgs()[0]!;+ placeAt(svg, 36);+ const row = host.querySelector("button")!;+ const listening = () => adds.mock.calls.filter(([type]) => type === "pointermove").length - removes.mock.calls.filter(([type]) => type === "pointermove").length;+ act(() => { row.dispatchEvent(pointer("pointerenter", 400, 118)); });+ expect(listening()).toBe(1);+ act(() => { document.dispatchEvent(pointer("pointermove", 420, 118)); });+ run(300);+ const shift = svg.querySelector("g[clip-path] > g > g")!;+ expect(shift.getAttribute("transform")).toMatch(/^translate\(\d/);+ act(() => { row.dispatchEvent(pointer("pointerleave", 500, 118)); });+ expect(listening()).toBe(0);+ run(1500);+ expect(shift.getAttribute("transform")).toBeNull();+ expect(mascotClock().pending()).toBe(0);+ });++ it.each(["excited", "alerting", "celebrate"] as const)("only glances and breathes when a resting %s mascot is hovered", (state) => {+ render([{ state, size: 56, animated: false }]);+ run(300);+ const svg = svgs()[0]!;+ placeAt(svg, 56);+ act(() => { svg.dispatchEvent(pointer("pointerenter", 128, 128)); });+ const glyph = bodyOf(svg).children[1] as SVGGElement;+ let lowest = 0;+ let glyphShown = false;+ for (let i = 0; i < 70; i++) {+ run(50);+ const lift = /translate\(([-\d.]+) ([-\d.]+)\)/.exec(bodyOf(svg).getAttribute("transform") ?? "");+ lowest = Math.min(lowest, Number(lift?.[2] ?? 0));+ glyphShown ||= glyph.childElementCount > 0 || glyph.style.opacity !== "0";+ }+ expect(lowest).toBeGreaterThan(-1);+ expect(glyphShown).toBe(false);+ expect(svg.querySelector(":scope > g > g:first-child")!.childElementCount).toBe(0);+ expect(svg.querySelector(":scope > g > g:last-child")!.childElementCount).toBe(0);+ });++ it("plays a festival body's beats and spins when nothing animates it, and never sticks wide-eyed", () => {+ const ref = createRef<MausAvatarHandle>();+ render([{ state: "idle", size: 44, bodyId: "pumpkin", ref }]);+ run(1000);+ const smile = host.querySelector("[data-carved-body] path[stroke]") as SVGPathElement;+ const changes = watch();+ render([{ state: "idle", size: 44, bodyId: "pumpkin", ref, motion: "surprise", motionKey: 1 }]);+ run(200);+ expect(Number(smile.style.opacity)).toBeLessThan(0.1);+ run(3000);+ expect(smile.style.opacity).toBe("1");+ expect(mascotClock().pending()).toBe(0);+ const before = changes.attributes().length;+ act(() => ref.current!.spin());+ run(300);+ expect(changes.attributes().length).toBeGreaterThan(before);+ run(3000);+ expect(mascotClock().pending()).toBe(0);+ changes.stop();+ });+});diff --git a/src/components/CursorAvatar.tsx b/src/components/CursorAvatar.tsxindex acf76e6fcc..df4a138c3e 100644--- a/src/components/CursorAvatar.tsx+++ b/src/components/CursorAvatar.tsx@@ -15,8 +15,11 @@ import {mouthFrame,type Ring,} from "./cursor-face-data"-import { GLYPH_EASE_MS, MOTION, VIEW_SPAN, bodyTransform, faceTravelUnits, frameFloorMs, morphUnitsPerMs, nextFrameAt, nextMascotFrame, type BodyMotion } from "./mascot-motion"-import { mascotClock, usePrefersReducedMotion, type MascotTicket } from "./mascot-clock"+import {+ BLEND_OMEGA, COMPACT_MASCOT_PX, FRAME_SLACK_MS, GLYPH_EASE_MS, HOVER_BLINK_MS, MOTION, PoseBlend, REST_POSE, VIEW_SPAN, blinkOpenness, bodyPose,+ bodyTransform, faceTravelUnits, frameFloorMs, loopSeed, morphUnitsPerMs, nextFrameAt, nextMascotFrame, poseTransform, restPose, type BodyMotion,+} from "./mascot-motion"+import { mascotClock, put, usePrefersReducedMotion, type MascotTicket } from "./mascot-clock"export { MOTION, bodyTransform, type BodyMotion }export {@@ -321,522 +324,136 @@ export type CursorState =| "powering-down"export const POOLS = {- sleeping: [- 22,- 13,- 4- ],- waking: [- 13- ],- idle: [- 6,- 0,- 8- ],- listening: [- 1,- 10,- 19- ],- thinking: [- 17,- 8,- 16,- 14,- 5- ],- searching: [- 20,- 15,- 9,- 3,- 12,- 18- ],- working: [- 10,- 7,- 16,- 11- ],- excited: [- 2,- 17,- 21,- 3,- 11- ],- surprised: [- 21,- 3- ],- suspicious: [- 5,- 14,- 23- ],- angry: [- 7,- 16- ],- drowsy: [- 22,- 4,- 13- ],- happy: [- 19,- 2,- 11,- 17- ],- curious: [- 21,- 3,- 0,- 15- ],- confused: [- 8,- 14,- 5- ],- bored: [- 0,- 4,- 22- ],- proud: [- 2,- 15,- 8- ],- shy: [- 24,- 0,- 13- ],- sad: [- 22,- 4,- 13- ],- laughing: [- 2,- 11,- 17- ],- scared: [- 21,- 3- ],- playful: [- 2,- 17,- 11,- 8- ],- celebrate: [- 2,- 8,- 17- ],- orbit: [- 6,- 0,- 8- ],- radar: [- 6,- 0,- 8- ],- progress: [- 6,- 0,- 8- ],- spawning: [- 3,- 0- ],- humming: [- 6,- 0,- 8- ],- loading: [- 6,- 0,- 8- ],- dictating: [- 1,- 10,- 19- ],- sending: [- 6,- 0,- 8- ],- receiving: [- 19,- 0,- 8- ],- uploading: [- 15,- 9,- 8- ],- writing: [- 15,- 9- ],- notifying: [- 21,- 3,- 0- ],- alerting: [- 21,- 3- ],- bouncing: [- 2,- 17- ],- dragging: [- 3,- 15,- 0- ],- "powering-down": [- 22,- 13- ]+ sleeping: [22, 13, 4],+ waking: [13],+ idle: [6, 0, 8],+ listening: [1, 10, 19],+ thinking: [17, 8, 16, 14, 5],+ searching: [20, 15, 9, 3, 12, 18],+ working: [10, 7, 16, 11],+ excited: [2, 17, 21, 3, 11],+ surprised: [21, 3],+ suspicious: [5, 14, 23],+ angry: [7, 16],+ drowsy: [22, 4, 13],+ happy: [19, 2, 11, 17],+ curious: [21, 3, 0, 15],+ confused: [8, 14, 5],+ bored: [0, 4, 22],+ proud: [2, 15, 8],+ shy: [24, 0, 13],+ sad: [22, 4, 13],+ laughing: [2, 11, 17],+ scared: [21, 3],+ playful: [2, 17, 11, 8],+ celebrate: [2, 8, 17],+ orbit: [6, 0, 8],+ radar: [6, 0, 8],+ progress: [6, 0, 8],+ spawning: [3, 0],+ humming: [6, 0, 8],+ loading: [6, 0, 8],+ dictating: [1, 10, 19],+ sending: [6, 0, 8],+ receiving: [19, 0, 8],+ uploading: [15, 9, 8],+ writing: [15, 9],+ notifying: [21, 3, 0],+ alerting: [21, 3],+ bouncing: [2, 17],+ dragging: [3, 15, 0],+ "powering-down": [22, 13],} satisfies Record<CursorState, number[]>const EXPR_CADENCE = {- sleeping: [- 6000,- 10000- ],- waking: [- 800,- 800- ],- idle: [- 9000,- 16000- ],- listening: [- 2800,- 5000- ],- thinking: [- 2000,- 3600- ],- searching: [- 1000,- 1800- ],- working: [- 1800,- 3200- ],- excited: [- 1100,- 2000- ],- surprised: [- 2500,- 4000- ],- suspicious: [- 2600,- 4500- ],- angry: [- 2200,- 3800- ],- drowsy: [- 4000,- 8000- ],- happy: [- 2500,- 4500- ],- curious: [- 1800,- 3200- ],- confused: [- 2200,- 3800- ],- bored: [- 3500,- 6000- ],- proud: [- 3500,- 6000- ],- shy: [- 3000,- 5500- ],- sad: [- 4000,- 7000- ],- laughing: [- 1200,- 2400- ],- scared: [- 900,- 1800- ],- playful: [- 1500,- 3000- ],- celebrate: [- 1400,- 2600- ],- orbit: [- 4000,- 8000- ],- radar: [- 4000,- 8000- ],- progress: [- 4000,- 8000- ],- spawning: [- 1200,- 1200- ],- humming: [- 5000,- 9000- ],- loading: [- 6000,- 10000- ],- dictating: [- 4000,- 8000- ],- sending: [- 4000,- 8000- ],- receiving: [- 4000,- 8000- ],- uploading: [- 4000,- 8000- ],- writing: [- 4000,- 8000- ],- notifying: [- 1500,- 2600- ],- alerting: [- 2000,- 3600- ],- bouncing: [- 3000,- 6000- ],- dragging: [- 1600,- 3000- ],- "powering-down": [- 6000,- 9000- ]+ sleeping: [6000, 10000],+ waking: [800, 800],+ idle: [9000, 16000],+ listening: [2800, 5000],+ thinking: [2000, 3600],+ searching: [1000, 1800],+ working: [1800, 3200],+ excited: [1100, 2000],+ surprised: [2500, 4000],+ suspicious: [2600, 4500],+ angry: [2200, 3800],+ drowsy: [4000, 8000],+ happy: [2500, 4500],+ curious: [1800, 3200],+ confused: [2200, 3800],+ bored: [3500, 6000],+ proud: [3500, 6000],+ shy: [3000, 5500],+ sad: [4000, 7000],+ laughing: [1200, 2400],+ scared: [900, 1800],+ playful: [1500, 3000],+ celebrate: [1400, 2600],+ orbit: [4000, 8000],+ radar: [4000, 8000],+ progress: [4000, 8000],+ spawning: [1200, 1200],+ humming: [5000, 9000],+ loading: [6000, 10000],+ dictating: [4000, 8000],+ sending: [4000, 8000],+ receiving: [4000, 8000],+ uploading: [4000, 8000],+ writing: [4000, 8000],+ notifying: [1500, 2600],+ alerting: [2000, 3600],+ bouncing: [3000, 6000],+ dragging: [1600, 3000],+ "powering-down": [6000, 9000],} satisfies Record<CursorState, [number, number]>const BLINK = {sleeping: null,waking: null,- idle: [- 6000,- 14000- ],- listening: [- 3000,- 7000- ],- thinking: [- 3500,- 7000- ],- searching: [- 1600,- 4000- ],- working: [- 2800,- 5500- ],- excited: [- 2000,- 4000- ],- surprised: [- 1800,- 3500- ],- suspicious: [- 4500,- 8000- ],- angry: [- 3500,- 7000- ],+ idle: [6000, 14000],+ listening: [3000, 7000],+ thinking: [3500, 7000],+ searching: [1600, 4000],+ working: [2800, 5500],+ excited: [2000, 4000],+ surprised: [1800, 3500],+ suspicious: [4500, 8000],+ angry: [3500, 7000],drowsy: null,- happy: [- 2500,- 5000- ],- curious: [- 2500,- 5500- ],- confused: [- 2800,- 5500- ],- bored: [- 4000,- 8000- ],- proud: [- 3500,- 7000- ],- shy: [- 3000,- 6000- ],- sad: [- 4000,- 8000- ],- laughing: [- 2500,- 5000- ],- scared: [- 1200,- 3000- ],- playful: [- 2000,- 4500- ],- celebrate: [- 2200,- 4500- ],+ happy: [2500, 5000],+ curious: [2500, 5500],+ confused: [2800, 5500],+ bored: [4000, 8000],+ proud: [3500, 7000],+ shy: [3000, 6000],+ sad: [4000, 8000],+ laughing: [2500, 5000],+ scared: [1200, 3000],+ playful: [2000, 4500],+ celebrate: [2200, 4500],orbit: null,radar: null,progress: null,spawning: null,- humming: [- 4000,- 8000- ],+ humming: [4000, 8000],loading: null,dictating: null,sending: null,receiving: null,uploading: null,writing: null,- notifying: [- 2000,- 4000- ],+ notifying: [2000, 4000],alerting: null,bouncing: null,- dragging: [- 2200,- 4500- ],- "powering-down": null+ dragging: [2200, 4500],+ "powering-down": null,} satisfies Record<CursorState, [number, number] | null>export const STATE_GROUPS = {- "Cycle de vie": [- "sleeping",- "waking",- "idle",- "listening",- "thinking",- "searching",- "working"- ],- "Réactions": [- "excited",- "surprised",- "suspicious",- "angry",- "drowsy",- "happy",- "curious",- "confused",- "bored",- "proud",- "shy",- "sad",- "laughing",- "scared",- "playful",- "celebrate"- ],- "Morphes agent": [- "orbit",- "radar",- "progress"- ],- "Cycle produit": [- "spawning",- "humming",- "loading",- "dictating",- "writing",- "sending",- "receiving",- "uploading",- "notifying",- "alerting",- "dragging",- "bouncing",- "powering-down"- ]+ "Cycle de vie": ["sleeping", "waking", "idle", "listening", "thinking", "searching", "working"],+ "Réactions": ["excited", "surprised", "suspicious", "angry", "drowsy", "happy", "curious", "confused", "bored", "proud", "shy", "sad", "laughing", "scared", "playful", "celebrate"],+ "Morphes agent": ["orbit", "radar", "progress"],+ "Cycle produit": ["spawning", "humming", "loading", "dictating", "writing", "sending", "receiving", "uploading", "notifying", "alerting", "dragging", "bouncing", "powering-down"],} satisfies Record<string, CursorState[]>const isCursorState = (state: string): state is CursorState => state in POOLS@@ -900,7 +517,10 @@ export interface CursorAvatarProps {glyphs?: booleanautoBlink?: booleanautoExpression?: boolean- paused?: boolean+ /** Holds still: no loops, blinks or expression drift, until the pointer comes over it. A change of face still blends in. */+ resting?: boolean+ /** How far the eyes follow a nearby pointer, 0 to ignore it. */+ pointerGaze?: numbersilhouette?: CursorSilhouettegradient?: [string, string, string]picture?: string | null@@ -916,6 +536,19 @@ export interface CursorAvatarHandle {setExpression: (index: number) => void}+const HOVER_SCOPE = 'a, button, [role="button"], [role="link"], [role="option"], [role="menuitem"]'+const POINTER_REACH = 2+const LOOK_SMOOTHING = 0.86+const LEAN_DEGREES = 3+const FIRST_HOVER_BLINK_MS: [number, number] = [250, 700]++const engagedMotion = ({ state, resting }: { state: CursorState; resting: boolean }): BodyMotion => {+ const own: BodyMotion = MOTION[state]+ return resting ? { ...MOTION.idle, tilt: own.tilt, settle: own.settle } : own+}++const between = ([lo, hi]: [number, number]) => lo + Math.random() * (hi - lo)+export const CursorAvatar = React.forwardRef<CursorAvatarHandle, CursorAvatarProps>(function CursorAvatar({@@ -926,7 +559,7 @@ export const CursorAvatar = React.forwardRef<CursorAvatarHandle, CursorAvatarProturn = 0,lookAround = 0.5,flip = false,- spring = 7,+ spring = BLEND_OMEGA,eyeScale = 1,showMouth = true,mouthStroke = MOUTH_STROKE,@@ -935,7 +568,8 @@ export const CursorAvatar = React.forwardRef<CursorAvatarHandle, CursorAvatarProglyphs = true,autoBlink = true,autoExpression = true,- paused = false,+ resting = false,+ pointerGaze = 0,silhouette = DEFAULT_SILHOUETTE,gradient = DEFAULT_GRADIENT, picture,eyeColor,@@ -951,32 +585,37 @@ export const CursorAvatar = React.forwardRef<CursorAvatarHandle, CursorAvatarProconst eye0 = useRef<SVGPathElement | null>(null)const eye1 = useRef<SVGPathElement | null>(null)const mouth = useRef<SVGPathElement | null>(null)+ const faceShift = useRef<SVGGElement | null>(null)const bodyGroup = useRef<SVGGElement | null>(null)const bodyContent = useRef<SVGGElement | null>(null)const trailLayer = useRef<SVGGElement | null>(null)const confettiLayer = useRef<SVGGElement | null>(null)const glyphLayer = useRef<SVGGElement | null>(null)const ticket = useRef<MascotTicket | null>(null)- const wake = () => ticket.current?.wake(nextFrameAt(performance.now(), frameFloorMs(engine.current.props.sizePx)))+ const wake = () => ticket.current?.wake(nextFrameAt(performance.now(), frameFloorMs(engine.current.props.sizePx, engine.current.hovered)))const reduced = usePrefersReducedMotion()const motionStrength = motion ?? (reduced ? 0 : 1)const paint = `url(#${uid}-grad)`+ const sizePx = typeof size === 'number' ? size : 160const props = {state,expression,gaze,turn,+ flip,spring,eyeScale,- paused,+ resting,reduced,lookAround,motionStrength,effects,glyphs,+ autoBlink,paint,- sizePx: typeof size === 'number' ? size : 160,+ sizePx,+ compact: sizePx <= COMPACT_MASCOT_PX,}const engine = useRef({@@ -990,13 +629,21 @@ export const CursorAvatar = React.forwardRef<CursorAvatarHandle, CursorAvatarPromorph: 1,velocity: 0,travel: 0,+ drawn: false,blinkStart: noTimestamp(),+ nextBlinkAt: noTimestamp(),spinStart: noTimestamp(),spinDuration: 900,last: 0,stateStart: 0,lastState: state,- lastBodyTransform: '',+ seed: loopSeed(uid),+ blend: new PoseBlend(),+ shown: REST_POSE,+ poseKey: '',+ hovered: false,+ look: [0, 0],+ lookTarget: [0, 0],faceStale: true,faceMoving: false,effectsStill: '',@@ -1017,7 +664,7 @@ export const CursorAvatar = React.forwardRef<CursorAvatarHandle, CursorAvatarProe.targetGaze = GAZE[i]e.travel = faceTravelUnits(from, { rings: e.target, mouth: e.targetMouth, gaze: e.targetGaze })e.expression = i- e.morph = 0+ e.morph = e.drawn ? 0 : 1e.velocity = 0e.last = performance.now()wake()@@ -1047,10 +694,9 @@ export const CursorAvatar = React.forwardRef<CursorAvatarHandle, CursorAvatarPro}, [state, expression])useEffect(() => {- if (!autoExpression || expression !== undefined || paused || reduced) return+ if (!autoExpression || expression !== undefined || resting || reduced) returnlet timer: ReturnType<typeof setTimeout>const tick = () => {- const [lo, hi] = EXPR_CADENCE[state]timer = setTimeout(() => {const pool = POOLS[state]const alternatives = pool.filter(x => x !== engine.current.expression)@@ -1060,31 +706,71 @@ export const CursorAvatar = React.forwardRef<CursorAvatarHandle, CursorAvatarPro: pool[0])tick()- }, lo + Math.random() * (hi - lo))+ }, between(EXPR_CADENCE[state]))}tick()return () => clearTimeout(timer)- }, [state, autoExpression, expression, paused, reduced])-- useEffect(() => {- const cadence = BLINK[state]- if (!autoBlink || !cadence || paused || reduced) return- let timer: ReturnType<typeof setTimeout>- const tick = () => {- timer = setTimeout(() => {- engine.current.blinkStart = performance.now()- wake()- tick()- }, cadence[0] + Math.random() * (cadence[1] - cadence[0]))- }- tick()- return () => clearTimeout(timer)- }, [state, autoBlink, paused, reduced])+ }, [state, autoExpression, expression, resting, reduced])useEffect(() => {engine.current.faceStale = truewake()- }, [state, expression, gaze?.x, gaze?.y, turn, eyeScale, lookAround, paused, reduced, motionStrength, effects, glyphs, paint, showMouth, size])+ }, [state, expression, gaze?.x, gaze?.y, turn, eyeScale, lookAround, resting, reduced, motionStrength, effects, glyphs, paint, showMouth, size, autoBlink])++ useEffect(() => {+ const el = svg.current+ if (!pointerGaze || reduced || !el) return+ const doc = el.ownerDocument+ const scope = el.parentElement?.closest(HOVER_SCOPE) ?? el+ let inside = false+ let following = false+ const stop = () => {+ if (!following) return+ following = false+ doc.removeEventListener('pointermove', follow)+ doc.documentElement.removeEventListener('pointerleave', stop)+ const e = engine.current+ e.hovered = false+ e.lookTarget = [0, 0]+ wake()+ }+ const follow = (event: PointerEvent) => {+ const box = el.getBoundingClientRect()+ const reach = Math.max(box.width, 1) * POINTER_REACH+ const dx = (event.clientX - box.left - box.width / 2) / reach+ const dy = (event.clientY - box.top - box.height / 2) / reach+ const distance = Math.hypot(dx, dy)+ if (!inside && distance > 1) return stop()+ const fit = (distance > 1 ? 1 / distance : 1) * pointerGaze+ const e = engine.current+ e.lookTarget = [dx * fit * (e.props.flip ? -1 : 1), dy * fit]+ wake()+ }+ const enter = (event: PointerEvent) => {+ if (event.pointerType === 'touch') return+ inside = true+ if (!following) {+ following = true+ doc.addEventListener('pointermove', follow, { passive: true })+ doc.documentElement.addEventListener('pointerleave', stop)+ const e = engine.current+ e.hovered = true+ e.nextBlinkAt = performance.now() + between(FIRST_HOVER_BLINK_MS)+ }+ follow(event)+ }+ const leave = (event: PointerEvent) => {+ inside = false+ if (following) follow(event)+ }+ scope.addEventListener('pointerenter', enter as EventListener)+ scope.addEventListener('pointerleave', leave as EventListener)+ return () => {+ scope.removeEventListener('pointerenter', enter as EventListener)+ scope.removeEventListener('pointerleave', leave as EventListener)+ stop()+ }+ }, [pointerGaze, reduced])useEffect(() => {const drawFace = (e: typeof engine.current, now: number, spinTurn: number) => {@@ -1110,8 +796,9 @@ export const CursorAvatar = React.forwardRef<CursorAvatarHandle, CursorAvatarProconst longitude = baseLongitude + radiansconst depth = Math.cos(longitude)const perspective = Math.max(depth, 0.02) / Math.max(Math.cos(baseLongitude), 0.02)- el.setAttribute('d', toPath(ring))- el.setAttribute(+ put(el, 'd', toPath(ring))+ put(+ el,'transform',`translate(${(SPHERE_C + SPHERE_R * Math.sin(longitude) + gx).toFixed(2)} ${(c[1] + gy@@ -1121,7 +808,7 @@ export const CursorAvatar = React.forwardRef<CursorAvatarHandle, CursorAvatarPro2.4).toFixed(4)}) translate(${(-c[0]).toFixed(2)} ${(-c[1]).toFixed(2)})`)- el.style.opacity = depth > 0.02 ? '1' : '0'+ put(el, 'opacity', depth > 0.02 ? '1' : '0')})const mouthEl = mouth.current@@ -1132,8 +819,9 @@ export const CursorAvatar = React.forwardRef<CursorAvatarHandle, CursorAvatarProconst longitude = baseLongitude + radiansconst depth = Math.cos(longitude)const perspective = Math.max(depth, 0.02) / Math.max(Math.cos(baseLongitude), 0.02)- mouthEl.setAttribute('d', mouthPath(frameGeom, spec))- mouthEl.setAttribute(+ put(mouthEl, 'd', mouthPath(frameGeom, spec))+ put(+ mouthEl,'transform',`translate(${(SPHERE_C + SPHERE_R * Math.sin(longitude) + gx).toFixed(2)} ${(frameGeom.y + gy@@ -1141,25 +829,40 @@ export const CursorAvatar = React.forwardRef<CursorAvatarHandle, CursorAvatarPro-frameGeom.x).toFixed(2)} ${(-frameGeom.y).toFixed(2)})`)- mouthEl.style.opacity = depth > 0.02 ? '1' : '0'+ put(mouthEl, 'opacity', depth > 0.02 ? '1' : '0')}}- const drawBody = (e: typeof engine.current, now: number, showEffects: boolean, showGlyphs: boolean) => {+ const drawPose = (e: typeof engine.current, now: number, engaged: boolean) => {const p = e.propsif (p.state !== e.lastState) {e.lastState = p.statee.stateStart = now}- const bodyEl = bodyGroup.current- if (bodyEl) {- const transform = bodyTransform(MOTION[p.state] ?? {}, now - e.stateStart, p.motionStrength ?? 1)- if (transform !== e.lastBodyTransform) {- e.lastBodyTransform = transform- if (transform) bodyEl.setAttribute('transform', transform)- else bodyEl.removeAttribute('transform')- }+ const motion = engagedMotion(p)+ const strength = p.motionStrength ?? 1+ const target = engaged+ ? bodyPose(motion, now - e.stateStart, strength, { seed: e.seed, compact: p.compact })+ : restPose(motion, strength)+ const key = `${p.state}|${engaged}`+ if (key !== e.poseKey) {+ if (e.poseKey && !motion.enter && !p.reduced) e.blend.retarget(now, e.shown, target)+ e.poseKey = key}+ const pose = e.blend.apply(now, target)+ pose.rotate += e.look[0] * LEAN_DEGREES+ e.shown = pose+ const pixel = p.compact ? VIEW_SPAN / p.sizePx / Math.max(globalThis.devicePixelRatio ?? 1, 1) : 0+ if (bodyGroup.current) put(bodyGroup.current, 'transform', poseTransform(pose, pixel) || null)+ if (faceShift.current) {+ const fx = pose.fx + e.look[0] * GAZE_TRAVEL.x+ const fy = e.look[1] * GAZE_TRAVEL.y+ put(faceShift.current, 'transform', Math.abs(fx) < 0.005 && Math.abs(fy) < 0.005 ? null : `translate(${fx.toFixed(2)} ${fy.toFixed(2)})`)+ }+ }++ const drawEffects = (e: typeof engine.current, now: number, showEffects: boolean, showGlyphs: boolean) => {+ const p = e.propsconst spec = EFFECTS[p.state]const glyph = spec?.glyph && showGlyphs ? glyphAmount(spec.glyph, now - e.stateStart) : 0const still = `${p.state}|${showEffects}|${showGlyphs}|${glyph}|${p.paint}`@@ -1179,15 +882,46 @@ export const CursorAvatar = React.forwardRef<CursorAvatarHandle, CursorAvatarPro})}+ const stepLook = (e: typeof engine.current, dt: number) => {+ const k = 1 - Math.pow(LOOK_SMOOTHING, dt * 60)+ let moving = false+ for (const axis of [0, 1]) {+ const gap = e.lookTarget[axis] - e.look[axis]+ if (Math.abs(gap) < 0.002) e.look[axis] = e.lookTarget[axis]+ else {+ e.look[axis] += gap * k+ moving = true+ }+ }+ return moving+ }++ const scheduleBlink = (e: typeof engine.current, now: number, engaged: boolean) => {+ const p = e.props+ const own = BLINK[p.state]+ const cadence = engaged && p.autoBlink && !p.reduced && own ? (p.resting ? HOVER_BLINK_MS : own) : null+ if (!cadence) {+ e.nextBlinkAt = null+ return+ }+ if (e.nextBlinkAt === null) e.nextBlinkAt = now + between(cadence)+ else if (now + FRAME_SLACK_MS >= e.nextBlinkAt) {+ e.blinkStart = now+ e.nextBlinkAt = now + between(cadence)+ }+ }+const frame = (now: number): number => {const e = engine.currentconst p = e.propsconst dt = Math.min(Math.max(now - e.last, 0) / 1000, 0.05)- const f = p.spring ?? 7+ const f = p.spring ?? BLEND_OMEGAe.last = now- if (p.paused || p.reduced) {+ if (p.reduced || !e.drawn) {e.morph = 1e.velocity = 0+ }+ if (p.reduced) {e.blinkStart = nulle.spinStart = null} else {@@ -1199,6 +933,11 @@ export const CursorAvatar = React.forwardRef<CursorAvatarHandle, CursorAvatarProe.velocity = 0}}+ e.drawn = true++ const engaged = !p.reduced && (!p.resting || e.hovered)+ scheduleBlink(e, now, engaged)+ const lookMoving = stepLook(e, dt)let spinTurn = 0if (e.spinStart !== null) {@@ -1211,21 +950,25 @@ export const CursorAvatar = React.forwardRef<CursorAvatarHandle, CursorAvatarProif (e.faceStale || e.faceMoving || faceMoving()) drawFace(e, now, spinTurn)e.faceStale = falsee.faceMoving = faceMoving()- const showEffects = p.effects !== false && !p.paused- const showGlyphs = p.glyphs !== false && !p.paused && !p.reduced- drawBody(e, now, showEffects, showGlyphs)- if (p.paused) return Infinity- return nextMascotFrame(now, {- motion: MOTION[p.state] ?? {},+ drawPose(e, now, engaged)+ const showEffects = p.effects !== false && engaged && !p.resting && !p.compact+ const showGlyphs = p.glyphs !== false && engaged && !p.resting+ drawEffects(e, now, showEffects, showGlyphs)+ const due = nextMascotFrame(now, {+ motion: engagedMotion(p),effects: EFFECTS[p.state],stateElapsedMs: now - e.stateStart,- strength: p.motionStrength ?? 1,+ strength: engaged ? p.motionStrength ?? 1 : 0,showEffects,showGlyphs,sizePx: p.sizePx,faceUnitsPerMs: morphUnitsPerMs(e.velocity, e.morph, f, e.travel),- blinkingOrSpinning: e.blinkStart !== null || e.spinStart !== null,+ blinkingOrSpinning: e.blinkStart !== null || e.spinStart !== null || lookMoving,+ hovered: e.hovered,+ blending: e.blend.blending,})+ const blinkDue = e.nextBlinkAt === null ? Infinity : nextFrameAt(e.nextBlinkAt - FRAME_SLACK_MS - 0.01, frameFloorMs(p.sizePx, e.hovered))+ return Math.min(due, blinkDue)}engine.current.last = performance.now()@@ -1244,10 +987,10 @@ export const CursorAvatar = React.forwardRef<CursorAvatarHandle, CursorAvatarProconst ink = cutFace ? 'black' : eyeColorconst face = (<g clipPath={`url(#${uid}-clip)`} visibility={picture ? 'hidden' : undefined}>- <g transform={anchorTransform(silhouette.anchor)}>+ <g transform={anchorTransform(silhouette.anchor)}><g ref={faceShift}><path ref={eye0} fill={ink} /><path ref={eye1} fill={ink} />{showMouth && <path ref={mouth} fill="none" stroke={ink} strokeWidth={mouthStroke} strokeLinecap="round" />}- </g>+ </g></g></g>)@@ -1313,12 +1056,9 @@ const displayedGaze = (e: { currentGaze: number[]; targetGaze: number[]; morph:function blinkScale(e: { blinkStart: number | null }, now: number) {if (e.blinkStart === null) return 1- const t = (now - e.blinkStart) / 320- if (t >= 1) {- e.blinkStart = null- return 1- }- return Math.max(t < 0.42 ? 1 - t / 0.42 : (t - 0.42) / 0.58, 0.04)+ const open = blinkOpenness(now - e.blinkStart)+ if (open === null) e.blinkStart = null+ return open ?? 1}export default CursorAvatardiff --git a/src/components/mascot-clock.ts b/src/components/mascot-clock.tsindex 863564bb65..8f1d125649 100644--- a/src/components/mascot-clock.ts+++ b/src/components/mascot-clock.ts@@ -171,3 +171,16 @@ const readReducedMotion = () => globalThis.window?.matchMedia?.(REDUCED_MOTION).export function usePrefersReducedMotion(): boolean {return useSyncExternalStore(subscribeReducedMotion, readReducedMotion, () => false);}++const written = new WeakMap<Element, Map<string, string>>();++/** Sets an attribute, or `opacity` as a style, only when it changes. */+export function put(el: Element, name: string, value: string | null): void {+ let seen = written.get(el);+ if (!seen) written.set(el, (seen = new Map()));+ if (seen.get(name) === (value ?? "")) return;+ seen.set(name, value ?? "");+ if (name === "opacity") (el as SVGElement).style.opacity = value ?? "";+ else if (value === null) el.removeAttribute(name);+ else el.setAttribute(name, value);+}diff --git a/src/components/mascot-motion.test.ts b/src/components/mascot-motion.test.tsindex 93e0721ba2..f851c822fd 100644--- a/src/components/mascot-motion.test.ts+++ b/src/components/mascot-motion.test.ts@@ -34,16 +34,16 @@ function delay(state: CursorState, sizePx: number, extra: Partial<CadenceInput>describe("mascot cadence", () => {it("picks the slowest frame tier that keeps each step smooth", () => {expect(frameIntervalFor(0)).toBe(Infinity);- expect(frameIntervalFor(SMOOTH_STEP_PX / 50)).toBe(50);- expect(frameIntervalFor(SMOOTH_STEP_PX / 40)).toBeCloseTo(1000 / 30);+ expect(frameIntervalFor(SMOOTH_STEP_PX / 50)).toBeCloseTo(1000 / 30);+ expect(frameIntervalFor(SMOOTH_STEP_PX / 34)).toBeCloseTo(1000 / 30);expect(frameIntervalFor(SMOOTH_STEP_PX / 20)).toBeCloseTo(FULL_FRAME_MS);expect(frameIntervalFor(1)).toBeCloseTo(FULL_FRAME_MS);});it("gives idle breathing no frames where it cannot be seen and a slow tier where it can", () => {- expect(delay("idle", 24)).toBe(Infinity);+ expect(delay("idle", 16)).toBe(Infinity);expect(delay("idle", 64)).toBeGreaterThan(30);- expect(delay("idle", 64)).toBeLessThanOrEqual(50);+ expect(delay("idle", 64)).toBeLessThanOrEqual(1000 / 30 + 1);expect(delay("sleeping", 112)).toBeGreaterThan(30);});@@ -55,13 +55,14 @@ describe("mascot cadence", () => {expect(delay("spawning", 96, { stateElapsedMs: 5_000 })).toBeGreaterThan(30);});- it("draws row, chip and header mascots at most 20 times a second", () => {+ it("draws row, chip and header mascots 30 times a second, and 60 under the pointer", () => {for (const size of [24, 36, 42, SMALL_MASCOT_PX]) {- expect(delay("working", size)).toBeGreaterThan(40);- expect(delay("working", size)).toBeLessThanOrEqual(50);- expect(delay("celebrate", size)).toBeLessThanOrEqual(50);- expect(delay("idle", size, { blinkingOrSpinning: true })).toBeLessThanOrEqual(50);- expect(delay("idle", size, { blinkingOrSpinning: true })).toBeGreaterThan(40);+ expect(delay("working", size)).toBeGreaterThan(30);+ expect(delay("working", size)).toBeLessThanOrEqual(1000 / 30 + 1);+ expect(delay("celebrate", size)).toBeLessThanOrEqual(1000 / 30 + 1);+ expect(delay("idle", size, { blinkingOrSpinning: true })).toBeGreaterThan(30);+ expect(delay("idle", size, { blending: true })).toBeGreaterThan(30);+ expect(delay("idle", size, { hovered: true, blinkingOrSpinning: true })).toBeCloseTo(FULL_FRAME_MS);}expect(delay("working", SMALL_MASCOT_PX + 1)).toBeCloseTo(FULL_FRAME_MS);});@@ -84,20 +85,20 @@ describe("mascot cadence", () => {it("draws an alert glyph's fades at full rate and rests between them", () => {const glyph = EFFECTS.confused!.glyph!;const shown = glyph.period - glyph.hold;- const at = (position: number) => delay("confused", 112, { stateElapsedMs: glyph.period * 3 + position });+ const at = (position: number) => delay("confused", 112, { stateElapsedMs: glyph.period * 3 + position, motion: {} });expect(at(shown - 400)).toBeGreaterThan(2 * FULL_FRAME_MS);expect(at(shown - 400)).toBeLessThanOrEqual(400);expect(at(shown + 10)).toBeCloseTo(FULL_FRAME_MS);expect(at(shown + GLYPH_EASE_MS + 100)).toBeGreaterThan(2 * FULL_FRAME_MS);expect(at(glyph.period - 10)).toBeCloseTo(FULL_FRAME_MS);- expect(delay("confused", 112, { stateElapsedMs: glyph.period * 3 + shown + 10, showGlyphs: false })).toBeGreaterThan(2 * FULL_FRAME_MS);+ expect(delay("confused", 112, { stateElapsedMs: glyph.period * 3 + shown + 10, showGlyphs: false, motion: {} })).toBeGreaterThan(2 * FULL_FRAME_MS);});it("follows an expression change until it settles", () => {expect(morphUnitsPerMs(0, 1, 7, 40)).toBe(0);const start = morphUnitsPerMs(0, 0, 7, 40);expect(start).toBeGreaterThan(0);- expect(delay("idle", 24, { faceUnitsPerMs: start })).toBeLessThan(Infinity);+ expect(delay("idle", 16, { faceUnitsPerMs: start })).toBeLessThan(Infinity);expect(morphUnitsPerMs(0, 0.99, 7, 40)).toBeLessThan(start / 50);});});diff --git a/src/components/mascot-motion.ts b/src/components/mascot-motion.tsindex 9f8ba6a796..533186da05 100644--- a/src/components/mascot-motion.ts+++ b/src/components/mascot-motion.ts@@ -2,10 +2,11 @@ import { FACE_BOX, type Ring } from "./cursor-face-data";import type { CursorState, StateEffects } from "./CursorAvatar";export const FULL_FRAME_MS = 1000 / 60;+export const LIST_FRAME_MS = 1000 / 30;export const FRAME_SLACK_MS = 4;-const FRAME_TIERS_MS = [1000 / 20, 1000 / 30, FULL_FRAME_MS];+const FRAME_TIERS_MS = [LIST_FRAME_MS, FULL_FRAME_MS];export const SMALL_MASCOT_PX = 64;-const SMALL_MASCOT_FRAME_MS = FRAME_TIERS_MS[0]!;+export const COMPACT_MASCOT_PX = 36;export const SMOOTH_STEP_PX = 0.5;export const VISIBLE_PX = 0.2;const SETTLE_MS = 1400;@@ -14,8 +15,8 @@ const CRITICAL_SPRING_PEAK = 1 / Math.E;export const VIEW_SPAN = FACE_BOX + 30;const BODY_RADIUS = FACE_BOX / 2;-const TAU = Math.PI * 2;const DEGREE = Math.PI / 180;+const GLANCE_UNITS_TO_VIEW = 0.8;export interface BodyMotion {bob?: [number, number];@@ -23,6 +24,7 @@ export interface BodyMotion {pulse?: [number, number];circle?: [number, number];jitter?: [number, number];+ glance?: [number, number];tilt?: number;squash?: number;enter?: [number, number];@@ -32,9 +34,9 @@ export interface BodyMotion {export const MOTION = {sleeping: { pulse: [0.028, 4600], tilt: 2 },waking: { enter: [0.92, 700], pulse: [0.03, 2200] },- idle: { pulse: [0.014, 3600] },+ idle: { pulse: [0.022, 3800], glance: [6, 4000] },listening: { bob: [2, 2600], pulse: [0.012, 2600] },- thinking: { sway: [1.6, 3000], pulse: [0.01, 3000] },+ thinking: { sway: [1.6, 3000], pulse: [0.01, 3000], glance: [4, 3000] },searching: { bob: [3, 1400], sway: [2.2, 1400] },working: { bob: [2.5, 900], squash: 0.22 },@@ -44,7 +46,7 @@ export const MOTION = {angry: { jitter: [1.3, 95], tilt: 2 },drowsy: { pulse: [0.026, 5000], tilt: 3 },happy: { bob: [5, 820], squash: 0.28 },- curious: { sway: [3.4, 1900], tilt: -4 },+ curious: { sway: [3.4, 1900], tilt: -4, glance: [5, 1900] },confused: { sway: [3, 2200] },bored: { pulse: [0.016, 5200], tilt: 2 },proud: { bob: [1.6, 2400], pulse: [0.02, 2400] },@@ -74,6 +76,110 @@ export const MOTION = {"powering-down": { settle: 0.05, tilt: 4 },} satisfies Record<CursorState, BodyMotion>;+/** States that show the bot doing something; every other state holds still unless a caller animates it or the pointer is over it. */+export const ACTIVE_STATES: ReadonlySet<CursorState> = new Set<CursorState>([+ "waking", "listening", "thinking", "searching", "working", "surprised", "celebrate", "orbit", "radar", "progress",+ "spawning", "loading", "dictating", "writing", "sending", "receiving", "uploading", "notifying", "alerting",+ "dragging", "bouncing", "powering-down",+]);++export function cubicBezier(x1: number, y1: number, x2: number, y2: number): (t: number) => number {+ const at = (a: number, b: number, s: number) => 3 * a * (1 - s) * (1 - s) * s + 3 * b * (1 - s) * s * s + s * s * s;+ return (t) => {+ if (t <= 0) return 0;+ if (t >= 1) return 1;+ let lo = 0;+ let hi = 1;+ for (let i = 0; i < 24; i++) {+ const mid = (lo + hi) / 2;+ if (at(x1, x2, mid) < t) lo = mid;+ else hi = mid;+ }+ return at(y1, y2, (lo + hi) / 2);+ };+}++const smoothstep = (t: number) => t * t * (3 - 2 * t);+const keyEase = cubicBezier(0.42, 0, 0.58, 1);+const KEY_EASE_PEAK_SLOPE = 1.73;+const blinkOpen = cubicBezier(0.4, 0.22, 0.28, 1.34);++export const BLINK_MS = 260;+const BLINK_CLOSE_MS = 90;+const BLINK_HOLD_MS = 33;+const BLINK_SHUT = 0.06;++/** Eye height through a blink, 1 open; null once the blink is over. */+export function blinkOpenness(elapsedMs: number): number | null {+ if (elapsedMs >= BLINK_MS) return null;+ if (elapsedMs <= 0) return 1;+ if (elapsedMs < BLINK_CLOSE_MS) return 1 - (1 - BLINK_SHUT) * smoothstep(elapsedMs / BLINK_CLOSE_MS);+ if (elapsedMs < BLINK_CLOSE_MS + BLINK_HOLD_MS) return BLINK_SHUT;+ const opening = (elapsedMs - BLINK_CLOSE_MS - BLINK_HOLD_MS) / (BLINK_MS - BLINK_CLOSE_MS - BLINK_HOLD_MS);+ return BLINK_SHUT + (1 - BLINK_SHUT) * blinkOpen(opening);+}++export const HOVER_BLINK_MS: [number, number] = [3000, 6000];++export const BLEND_OMEGA = 14;++/** A critically damped spring released from x0 with velocity v0 (per second), t seconds later. */+export function criticalSpring(x0: number, v0: number, t: number, omega = BLEND_OMEGA): { x: number; v: number } {+ const decay = Math.exp(-omega * t);+ const b = v0 + omega * x0;+ return { x: (x0 + b * t) * decay, v: (v0 - omega * b * t) * decay };+}++export interface Pose {+ x: number;+ y: number;+ rotate: number;+ scale: number;+ sx: number;+ sy: number;+ fx: number;+}++export const POSE_KEYS = ["x", "y", "rotate", "scale", "sx", "sy", "fx"] as const satisfies ReadonlyArray<keyof Pose>;+const SETTLED: Pose = { x: 0.05, y: 0.05, rotate: 0.02, scale: 3e-4, sx: 3e-4, sy: 3e-4, fx: 0.05 };+export const REST_POSE: Pose = { x: 0, y: 0, rotate: 0, scale: 1, sx: 1, sy: 1, fx: 0 };++type Track = ReadonlyArray<readonly [number, number]>;++const TRACKS: ReadonlyArray<Track> = [+ [[0, 0], [0.22, 1], [0.34, 1], [0.66, -1], [0.78, -1], [1, 0]],+ [[0, 0], [0.2, 0.8], [0.28, 0.8], [0.46, -0.4], [0.56, -0.4], [0.74, 0.6], [0.82, 0.6], [1, 0]],+ [[0, 0], [0.3, 1], [0.42, 1], [0.58, 0.2], [0.68, 0.2], [0.85, -1], [1, 0]],+];++const trackPeak = (track: Track) =>+ Math.max(...track.slice(1).map(([u, v], i) => Math.abs(v - track[i]![1]) / (u - track[i]![0]))) * KEY_EASE_PEAK_SLOPE;+const LOOP_PEAK_RATE = Math.max(...TRACKS.map(trackPeak));++function sampleTrack(track: Track, u: number): number {+ for (let i = 1; i < track.length; i++) {+ const [u1, v1] = track[i]!;+ if (u <= u1) {+ const [u0, v0] = track[i - 1]!;+ return v0 + (v1 - v0) * keyEase((u - u0) / (u1 - u0));+ }+ }+ return 0;+}++/** A per-bot offset into every loop, and which authored variant it plays, so a list of bots never moves in step. */+export interface LoopSeed {+ phase: number;+ variant: number;+}++export function loopSeed(key: string): LoopSeed {+ let hash = 2166136261;+ for (let i = 0; i < key.length; i++) hash = Math.imul(hash ^ key.charCodeAt(i), 16777619);+ const unsigned = hash >>> 0;+ return { phase: (unsigned % 10007) / 10007, variant: (unsigned >>> 16) % TRACKS.length };+}+const easeOutBack = (t: number) => {const c = 1.7;const u = t - 1;@@ -82,69 +188,131 @@ const easeOutBack = (t: number) => {const easeInOut = (t: number) => (t < 0.5 ? 2 * t * t : 1 - 2 * (1 - t) * (1 - t));-export function bodyTransform(motion: BodyMotion, elapsed: number, strength: number): string {- if (strength <= 0) return "";- const centre = FACE_BOX / 2;- const ground = FACE_BOX;- const wave = (period: number, phase = 0) => Math.sin((elapsed / period) * Math.PI * 2 + phase);+export interface PoseOptions {+ seed?: LoopSeed;+ compact?: boolean;+}- let dx = 0;- let dy = 0;- let rotation = motion.tilt ? motion.tilt * strength : 0;- let scale = 1;- let sx = 1;- let sy = 1;+export function bodyPose(motion: BodyMotion, elapsed: number, strength: number, options: PoseOptions = {}): Pose {+ const pose = { ...REST_POSE };+ if (strength <= 0) return pose;+ const seed = options.seed ?? { phase: 0, variant: 0 };+ const loop = (period: number, lane: number) => {+ const u = ((elapsed / period + seed.phase + lane * 0.37) % 1 + 1) % 1;+ return sampleTrack(TRACKS[(seed.variant + lane) % TRACKS.length]!, u);+ };+ const tremor = (period: number, phase = 0) => Math.sin((elapsed / period) * Math.PI * 2 + phase);+ pose.rotate = motion.tilt ? motion.tilt * strength : 0;if (motion.bob) {const [amplitude, period] = motion.bob;- const p = wave(period);- dy -= amplitude * strength * p;- if (motion.squash) {+ const p = loop(period, 0);+ pose.y -= amplitude * strength * p;+ if (motion.squash && !options.compact) {const amount = motion.squash * strength * Math.max(0, -p);- sy = 1 - amount * 0.5;- sx = 1 + amount * 0.5;+ pose.sy = 1 - amount * 0.5;+ pose.sx = 1 + amount * 0.5;}}if (motion.circle) {const [radius, period] = motion.circle;- dx += radius * strength * wave(period);- dy += radius * strength * wave(period, Math.PI / 2);- }- if (motion.sway) {- const [degrees, period] = motion.sway;- rotation += degrees * strength * wave(period);- }- if (motion.pulse) {- const [fraction, period] = motion.pulse;- scale *= 1 + fraction * strength * wave(period);+ pose.x += radius * strength * Math.sin((elapsed / period + seed.phase) * Math.PI * 2);+ pose.y += radius * strength * Math.cos((elapsed / period + seed.phase) * Math.PI * 2);}+ if (motion.sway) pose.rotate += motion.sway[0] * strength * loop(motion.sway[1], 1);+ if (motion.pulse) pose.scale *= 1 + motion.pulse[0] * strength * loop(motion.pulse[1], 2);+ if (motion.glance && !options.compact) pose.fx = motion.glance[0] * strength * loop(motion.glance[1], 1);if (motion.jitter) {const [amplitude, period] = motion.jitter;- dx += amplitude * strength * wave(period);- dy += amplitude * strength * wave(period * 0.63, 1.1);+ pose.x += amplitude * strength * tremor(period);+ pose.y += amplitude * strength * tremor(period * 0.63, 1.1);}if (motion.enter) {const [from, duration] = motion.enter;const t = elapsed / duration;- scale *= t >= 1 ? 1 : from + (1 - from) * easeOutBack(Math.max(t, 0));+ pose.scale *= t >= 1 ? 1 : from + (1 - from) * easeOutBack(Math.max(t, 0));}if (motion.settle !== undefined) {const t = Math.min(Math.max(elapsed / SETTLE_MS, 0), 1);- scale *= 1 + (motion.settle - 1) * easeInOut(t) * strength;+ pose.scale *= 1 + (motion.settle - 1) * easeInOut(t) * strength;}+ return pose;+}+export function restPose(motion: BodyMotion, strength: number): Pose {+ const pose = { ...REST_POSE };+ if (strength <= 0) return pose;+ pose.rotate = (motion.tilt ?? 0) * strength;+ if (motion.settle !== undefined) pose.scale = 1 + (motion.settle - 1) * strength;+ return pose;+}++/** `pixel` is one device pixel in viewBox units; the body's offset lands on it so a small mascot stays crisp. */+export function poseTransform(pose: Pose, pixel = 0): string {+ const centre = FACE_BOX / 2;+ const ground = FACE_BOX;+ const snap = (v: number) => (pixel > 0 ? Math.round(v / pixel) * pixel : v);+ const dx = snap(pose.x);+ const dy = snap(pose.y);const parts: string[] = [];- if (dx || dy) parts.push(`translate(${dx.toFixed(2)} ${dy.toFixed(2)})`);- if (rotation) parts.push(`rotate(${rotation.toFixed(2)} ${centre} ${centre})`);- if (scale !== 1) {- parts.push(`translate(${centre} ${centre}) scale(${scale.toFixed(4)}) translate(${-centre} ${-centre})`);+ if (Math.abs(dx) >= 0.005 || Math.abs(dy) >= 0.005) parts.push(`translate(${dx.toFixed(2)} ${dy.toFixed(2)})`);+ if (Math.abs(pose.rotate) >= 0.005) parts.push(`rotate(${pose.rotate.toFixed(2)} ${centre} ${centre})`);+ if (Math.abs(pose.scale - 1) >= 0.00005) {+ parts.push(`translate(${centre} ${centre}) scale(${pose.scale.toFixed(4)}) translate(${-centre} ${-centre})`);}- if (sx !== 1 || sy !== 1) {- parts.push(`translate(${centre} ${ground}) scale(${sx.toFixed(4)} ${sy.toFixed(4)}) translate(${-centre} ${-ground})`);+ if (Math.abs(pose.sx - 1) >= 0.00005 || Math.abs(pose.sy - 1) >= 0.00005) {+ parts.push(`translate(${centre} ${ground}) scale(${pose.sx.toFixed(4)} ${pose.sy.toFixed(4)}) translate(${-centre} ${-ground})`);}return parts.join(" ");}+export function bodyTransform(motion: BodyMotion, elapsed: number, strength: number, options?: PoseOptions): string {+ return poseTransform(bodyPose(motion, elapsed, strength, options));+}++const zeroPose = (): Pose => ({ x: 0, y: 0, rotate: 0, scale: 0, sx: 0, sy: 0, fx: 0 });++/** Blends a pose into whatever it is asked to show next; interrupting a blend starts the next one from where the body is and how fast it moves. */+export class PoseBlend {+ private offset = zeroPose();+ private velocity = zeroPose();+ private since = 0;+ blending = false;++ retarget(now: number, shown: Pose, next: Pose): void {+ const velocity = this.sample(now).velocity;+ for (const key of POSE_KEYS) this.offset[key] = shown[key] - next[key];+ this.velocity = velocity;+ this.since = now;+ this.blending = POSE_KEYS.some((key) => Math.abs(this.offset[key]) >= SETTLED[key] || Math.abs(velocity[key]) >= SETTLED[key] * BLEND_OMEGA);+ }++ apply(now: number, target: Pose): Pose {+ if (!this.blending) return target;+ const { offset } = this.sample(now);+ if (POSE_KEYS.every((key) => Math.abs(offset[key]) < SETTLED[key])) {+ this.blending = false;+ return target;+ }+ const pose = { ...target };+ for (const key of POSE_KEYS) pose[key] += offset[key];+ return pose;+ }++ private sample(now: number): { offset: Pose; velocity: Pose } {+ const offset = zeroPose();+ const velocity = zeroPose();+ if (!this.blending) return { offset, velocity };+ const t = Math.max(0, now - this.since) / 1000;+ for (const key of POSE_KEYS) {+ const spring = criticalSpring(this.offset[key], this.velocity[key], t);+ offset[key] = spring.x;+ velocity[key] = spring.v;+ }+ return { offset, velocity };+ }+}+export interface CadenceInput {motion: BodyMotion;effects: StateEffects | undefined;@@ -155,6 +323,8 @@ export interface CadenceInput {sizePx: number;faceUnitsPerMs: number;blinkingOrSpinning: boolean;+ hovered?: boolean;+ blending?: boolean;}export function frameIntervalFor(pxPerMs: number): number {@@ -163,21 +333,24 @@ export function frameIntervalFor(pxPerMs: number): number {return FULL_FRAME_MS;}-function loopSpeed(amplitude: number, period: number, px: number): number {- return amplitude * px >= VISIBLE_PX ? (TAU * amplitude * px) / period : 0;+const SINE_PEAK_RATE = Math.PI * 2;++function loopSpeed(amplitude: number, period: number, px: number, rate = LOOP_PEAK_RATE): number {+ return amplitude * px >= VISIBLE_PX ? (rate * amplitude * px) / period : 0;}-export function bodyPxPerMs(motion: BodyMotion, strength: number, px: number): number {+export function bodyPxPerMs(motion: BodyMotion, strength: number, px: number, compact = false): number {if (strength <= 0) return 0;let speed = 0;if (motion.bob) {speed += loopSpeed(motion.bob[0] * strength, motion.bob[1], px);- if (motion.squash) speed += loopSpeed(motion.squash * strength * 0.5 * FACE_BOX, motion.bob[1], px);+ if (motion.squash && !compact) speed += loopSpeed(motion.squash * strength * 0.5 * FACE_BOX, motion.bob[1], px);}if (motion.sway) speed += loopSpeed(motion.sway[0] * strength * DEGREE * BODY_RADIUS, motion.sway[1], px);if (motion.pulse) speed += loopSpeed(motion.pulse[0] * strength * BODY_RADIUS, motion.pulse[1], px);- if (motion.circle) speed += loopSpeed(motion.circle[0] * strength, motion.circle[1], px);- if (motion.jitter) speed += loopSpeed(motion.jitter[0] * strength, motion.jitter[1] * 0.63, px);+ if (motion.glance && !compact) speed += loopSpeed(motion.glance[0] * strength * GLANCE_UNITS_TO_VIEW, motion.glance[1], px);+ if (motion.circle) speed += loopSpeed(motion.circle[0] * strength, motion.circle[1], px, SINE_PEAK_RATE);+ if (motion.jitter) speed += loopSpeed(motion.jitter[0] * strength, motion.jitter[1] * 0.63, px, SINE_PEAK_RATE);return speed;}@@ -190,22 +363,22 @@ export function nextFrameAt(now: number, interval: number): number {return (Math.floor((now + FRAME_SLACK_MS) / interval) + 1) * interval;}-export function frameFloorMs(sizePx: number): number {- return sizePx <= SMALL_MASCOT_PX ? SMALL_MASCOT_FRAME_MS : FULL_FRAME_MS;+export function frameFloorMs(sizePx: number, hovered = false): number {+ return sizePx <= SMALL_MASCOT_PX && !hovered ? LIST_FRAME_MS : FULL_FRAME_MS;}export function nextMascotFrame(now: number, input: CadenceInput): number {- return Math.max(smoothFrameAt(now, input), nextFrameAt(now, frameFloorMs(input.sizePx)));+ return Math.max(smoothFrameAt(now, input), nextFrameAt(now, frameFloorMs(input.sizePx, input.hovered)));}function smoothFrameAt(now: number, input: CadenceInput): number {const { motion, effects, stateElapsedMs: elapsed, strength } = input;const full = nextFrameAt(now, FULL_FRAME_MS);- if (input.blinkingOrSpinning) return full;+ if (input.blinkingOrSpinning || input.blending) return full;if (strength > 0 && input.showEffects && (effects?.confetti || effects?.trails)) return full;if (strength > 0 && bodyTransient(motion, elapsed)) return full;const px = input.sizePx / VIEW_SPAN;- const due = nextFrameAt(now, frameIntervalFor(bodyPxPerMs(motion, strength, px) + input.faceUnitsPerMs * px));+ const due = nextFrameAt(now, frameIntervalFor(bodyPxPerMs(motion, strength, px, input.sizePx <= COMPACT_MASCOT_PX) + input.faceUnitsPerMs * px));const glyph = input.showGlyphs ? effects?.glyph : undefined;if (!glyph) return due;const position = elapsed % glyph.period;diff --git a/src/mascot-preview.tsx b/src/mascot-preview.tsxindex d20c945442..54411027f0 100644--- a/src/mascot-preview.tsx+++ b/src/mascot-preview.tsx@@ -67,7 +67,7 @@ type Tuning = {const DEFAULTS: Tuning = {eyeScale: EYE_SCALE,mouthStroke: MOUTH_WEIGHT,- spring: 7,+ spring: 14,turn: 0,gazeX: 0,gazeY: 0,