Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(cua-driver): add @trycua/cursor-motion, the web port of Cua Cursor Motion, with a playground (#4759)

Francesco Bonacci2ce4691fc053
diff --git a/.github/workflows/ci-ts-cursor-motion.yml b/.github/workflows/ci-ts-cursor-motion.yml
new file mode 100644
index 0000000000..a5937c8610
--- /dev/null
+++ b/.github/workflows/ci-ts-cursor-motion.yml
@@ -0,0 +1,48 @@
+name: "CI: @trycua/cursor-motion"
+
+on:
+ pull_request:
+ paths:
+ - "libs/typescript/cursor-motion/**"
+ - "libs/cua-driver/rust/crates/cua-cursor-motion/fixtures/**"
+ - ".github/workflows/ci-ts-cursor-motion.yml"
+ - ".github/workflows/ts-reusable-build.yml"
+
+env:
+ # Cua programs and packages run here never send usage telemetry.
+ CUA_TELEMETRY: "0"
+ DO_NOT_TRACK: "1"
+
+permissions:
+ contents: read
+
+jobs:
+ build:
+ uses: ./.github/workflows/ts-reusable-build.yml
+ with:
+ package_name: "cursor-motion"
+ package_dir: "libs/typescript/cursor-motion"
+ package_manager: "pnpm"
+
+ test:
+ # Golden trajectories shared with the Rust crate, plus the API tests.
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - name: Use Node.js 24.x
+ uses: actions/setup-node@v4
+ with:
+ node-version: "24.x"
+ - name: Setup pnpm
+ uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4
+ with:
+ package_json_file: libs/typescript/cursor-motion/package.json
+ - name: Install dependencies
+ working-directory: libs/typescript/cursor-motion
+ run: pnpm install --frozen-lockfile
+ - name: Typecheck
+ working-directory: libs/typescript/cursor-motion
+ run: pnpm typecheck
+ - name: Test
+ working-directory: libs/typescript/cursor-motion
+ run: pnpm test
diff --git a/docs/content/docs/cua-driver/guides/cursor-motion.mdx b/docs/content/docs/cua-driver/guides/cursor-motion.mdx
new file mode 100644
index 0000000000..c20ce438d0
--- /dev/null
+++ b/docs/content/docs/cua-driver/guides/cursor-motion.mdx
@@ -0,0 +1,141 @@
+---
+title: Design cursor motions
+description: Cua Cursor Motion, the open-source library behind Cua Driver's agent cursor. Plan the six motions, design your own, and play them on a web page.
+---
+
+Cua Driver moves its agent cursor with **Cua Cursor Motion**, an MIT-licensed
+library you can use on its own. It comes in two packages that give the same
+trajectories:
+
+- `cua-cursor-motion` (`libs/cua-driver/rust/crates/cua-cursor-motion`),
+ the Rust crate the driver plans every move with;
+- `@trycua/cursor-motion` (`libs/typescript/cursor-motion`), a TypeScript
+ port with a canvas player that draws the Cua cursor.
+
+Both are tested against the same golden trajectories, so a motion you tune on
+a web page plays the same way in the driver.
+
+## Use it from the repository
+
+Cua Cursor Motion is not published to crates.io or npm. Use it straight from
+[trycua/cua](https://github.com/trycua/cua).
+
+In Rust, add a git dependency. Cargo finds the crate inside the repository:
+
+```toml skip="no-runner"
+[dependencies]
+cua-cursor-motion = { git = "https://github.com/trycua/cua" }
+```
+
+On the web, build the single-file ES module once and copy it with its types
+into your project:
+
+```bash skip="host-install"
+git clone --depth 1 https://github.com/trycua/cua
+cd cua/libs/typescript
+pnpm install
+pnpm --filter @trycua/cursor-motion build
+cp cursor-motion/dist/index.js ../../../my-app/src/vendor/cua-cursor-motion.js
+cp cursor-motion/dist/index.d.ts ../../../my-app/src/vendor/cua-cursor-motion.d.ts
+```
+
+The file has no imports, so it also loads from a plain
+`<script type="module">`. In a TypeScript project with a bundler you can copy
+`libs/typescript/cursor-motion/src/` instead.
+
+## Plan a move
+
+A move is planned once, as samples at 120 Hz, then played back by time. It
+takes a style (`signature_arc`, `spring_settle`, `magnetic`, `comet_swoop`,
+`adaptive` or `classic`), a timing mode (`native`, `fitts` or `fixed`) and
+the shape knobs of `set_agent_cursor_motion`.
+
+```ts skip="no-runner"
+import { planMove } from './vendor/cua-cursor-motion.js';
+
+const trajectory = planMove(
+ { style: 'spring_settle', timing: 'fitts' },
+ { from: { x: 100, y: 100 }, to: { x: 700, y: 400 }, target: [660, 380, 80, 40] }
+);
+const { x, y, heading } = trajectory.sampleAt(0.3);
+```
+
+```rust skip="no-runner"
+use cua_cursor_motion::{plan_move, MotionParams, MotionStyle, MotionTiming, MoveRequest, Pt};
+
+let params = MotionParams { style: MotionStyle::SpringSettle, timing: MotionTiming::Fitts, ..Default::default() };
+let request = MoveRequest {
+ target: Some([660.0, 380.0, 80.0, 40.0]),
+ ..MoveRequest::new(Pt::new(100.0, 100.0), Pt::new(700.0, 400.0))
+};
+let sample = plan_move(&params, &request).sample_at(0.3);
+```
+
+`arrivalT` (`arrival_t` in Rust) is when the tip first reaches the target.
+Cua Driver clicks then and lets any follow-through or bounce finish during the
+click. The target rect sets the Fitts width: smaller targets take longer.
+
+## Play it on a web page
+
+`MotionPlayer` draws the Cua cursor, its glow, the comet trail and the click
+ripple inside a `<canvas>`. It never moves, hides or restyles the page's own
+mouse pointer.
+
+```ts skip="no-runner"
+import { MotionPlayer } from './vendor/cua-cursor-motion.js';
+
+const player = new MotionPlayer(document.querySelector('canvas')!);
+player.place({ x: 80, y: 300 });
+await player.moveTo(
+ { x: 640, y: 120 },
+ { params: { style: 'comet_swoop' }, target: [600, 104, 80, 32], click: true }
+);
+```
+
+## Design your own motion
+
+A custom motion is a `MotionSpec`: a path shape (`straight`, `arc`, `bow`), a
+speed curve (named easings or `cubic_bezier`), an overshoot or settle
+(`follow_through`, `spring`), a duration model (`fitts`, `fixed`, `distance`),
+a heading mode, effects and a trail. `signature_arc`, `spring_settle` and
+`comet_swoop` are specs themselves, so start from one:
+
+```ts skip="no-runner"
+import { planSpec, specForStyle } from './vendor/cua-cursor-motion.js';
+
+const spec = specForStyle('signature_arc')!;
+spec.ease = { type: 'cubic_bezier', x1: 0.3, y1: 0, x2: 0.1, y2: 1 };
+spec.settle = { type: 'follow_through', amount: 0.04, maxPt: 14, at: 0.75 };
+spec.effects.trail = true;
+
+const trajectory = planSpec(spec, { from: { x: 100, y: 500 }, to: { x: 900, y: 200 } });
+```
+
+Custom specs play in your own renderer. Cua Driver itself takes one of the six
+styles and its knobs.
+
+## The playground
+
+The playground lets you pick a style, drag the start and end points, tune the
+curve with a live speed plot, and copy the result as TypeScript or as Cua
+Driver config. Run it from a checkout:
+
+```bash skip="host-install"
+cd libs/typescript
+pnpm install
+pnpm --filter @trycua/cursor-motion playground
+```
+
+It opens at `http://127.0.0.1:4173/playground/`. For a built-in style, the
+exported Cua Driver config looks like this:
+
+```bash test="cli-shape" id="cua-driver-design-cursor-motion"
+cua-driver config set cursor.motion.style comet_swoop
+cua-driver config set cursor.motion.timing fitts
+cua-driver cursor motion --session demo --style comet_swoop --timing fitts --effects trail=on
+```
+
+The arc knobs (`arc_size`, `arc_flow`, `start_handle`, `end_handle`) and the
+classic glide's `spring` and `turn_radius` travel only through
+`set_agent_cursor_motion`. See [Choose your cursor](/cua-driver/guides/operate#choose-your-cursor)
+for how saved defaults, `start_session` and per-call settings combine.
diff --git a/docs/content/docs/cua-driver/guides/meta.json b/docs/content/docs/cua-driver/guides/meta.json
index 8ede9f9798..60715c5886 100644
--- a/docs/content/docs/cua-driver/guides/meta.json
+++ b/docs/content/docs/cua-driver/guides/meta.json
@@ -10,6 +10,7 @@
"vms-and-remote",
"test-in-a-sandbox",
"operate",
+ "cursor-motion",
"troubleshoot",
"recipes"
]
diff --git a/libs/typescript/cursor-motion/LICENSE b/libs/typescript/cursor-motion/LICENSE
new file mode 100644
index 0000000000..b8b198ce3e
--- /dev/null
+++ b/libs/typescript/cursor-motion/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2025 Cua AI, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/libs/typescript/cursor-motion/README.md b/libs/typescript/cursor-motion/README.md
new file mode 100644
index 0000000000..5ae7298a73
--- /dev/null
+++ b/libs/typescript/cursor-motion/README.md
@@ -0,0 +1,149 @@
+# @trycua/cursor-motion
+
+The agent cursor motions of [Cua Driver](https://cua.ai/docs/cua-driver) for
+the web: six motion styles, Fitts timing, the comet trail and the other
+effects, an API for designing your own motions, and a small canvas player
+that draws the real Cua cursor.
+
+It is a TypeScript port of the Rust crate
+[`cua-cursor-motion`](https://github.com/trycua/cua/tree/main/libs/cua-driver/rust/crates/cua-cursor-motion),
+which Cua Driver uses for every move. Both are tested against the same golden
+trajectories, so a motion you design here plays the same in the driver. No
+runtime dependencies; about 14 KB gzipped.
+
+## Use it
+
+Cua Cursor Motion is not published to npm. It lives in the
+[trycua/cua](https://github.com/trycua/cua) repository. Build it once from a
+checkout and copy the single-file ES module and its types into your project:
+
+```bash
+git clone --depth 1 https://github.com/trycua/cua
+cd cua/libs/typescript
+pnpm install
+pnpm --filter @trycua/cursor-motion build
+cp cursor-motion/dist/index.js ../../../my-app/src/vendor/cua-cursor-motion.js
+cp cursor-motion/dist/index.d.ts ../../../my-app/src/vendor/cua-cursor-motion.d.ts
+```
+
+```ts
+import { MotionPlayer, planMove } from './vendor/cua-cursor-motion.js';
+```
+
+The file has no imports, so it also works from a plain `<script type="module">`.
+In a TypeScript project with a bundler you can instead copy
+`libs/typescript/cursor-motion/src/` into your source tree and import the
+folder. `tests/vendoring.test.ts` checks both ways.
+
+## Play a motion
+
+```ts
+import { MotionPlayer } from './vendor/cua-cursor-motion.js';
+
+const player = new MotionPlayer(document.querySelector('canvas')!);
+player.place({ x: 80, y: 300 });
+await player.moveTo(
+ { x: 640, y: 120 },
+ { params: { style: 'comet_swoop' }, target: [600, 104, 80, 32], click: true }
+);
+```
+
+`moveTo` resolves when the tip reaches the target; any follow-through or
+settle keeps playing during the click, as in the driver. The cursor is drawn
+inside the canvas only. The player never moves, hides or restyles the page's
+real mouse pointer.
+
+## Plan a move yourself
+
+```ts
+import { planMove, effects, anchorForPointer } from './vendor/cua-cursor-motion.js';
+
+const trajectory = planMove(
+ { style: 'spring_settle', timing: 'fitts' },
+ { from: { x: 100, y: 100 }, to: { x: 700, y: 400 }, target: [660, 380, 80, 40] }
+);
+
+const t = 0.3; // seconds
+const s = trajectory.sampleAt(t); // hotspot x, y and the arrow's heading
+const frame = effects.motionFrame(trajectory, t, anchorForPointer(s.x, s.y, s.heading));
+// frame.trail, frame.glow, frame.magnet: geometry to paint your way
+```
+
+| Style | Feel |
+| --------------- | ----------------------------------------------------------- |
+| `signature_arc` | One confident arc with a small follow-through. The default. |
+| `spring_settle` | An arc that lands with one soft bounce. |
+| `magnetic` | Slows near the target, then is pulled in. |
+| `comet_swoop` | A wide arc with a short trail. |
+| `adaptive` | Careful for small targets, a swoop for long moves. |
+| `classic` | The original Dubins glide with an arrival spring. |
+
+Timing is `native`, `fitts` (`150 + 120 log2(D / W + 1)` ms, 300 to 1000 ms)
+or `fixed` (`glideDurationMs`, 1430 ms when 0). The other knobs (`arcSize`,
+`arcFlow`, `startHandle`, `endHandle`, `spring`, `turnRadius`) match Cua
+Driver's `set_agent_cursor_motion`.
+
+## Design your own motion
+
+A `MotionSpec` is a path shape, a speed curve, an overshoot or settle, a
+duration model, a heading mode, effects and a trail. The arc styles are
+specs, so start from one:
+
+```ts
+import { planSpec, specForStyle } from './vendor/cua-cursor-motion.js';
+
+const spec = specForStyle('spring_settle')!;
+spec.ease = { type: 'cubic_bezier', x1: 0.3, y1: 0, x2: 0.1, y2: 1 };
+spec.settle = {
+ type: 'spring',
+ amount: 0.06,
+ maxPt: 10,
+ cycles: 2,
+ decay: 3,
+ start: 0.5,
+ glideEnd: 0.6,
+};
+spec.effects.trail = true;
+spec.trail.secs = 0.25;
+
+const trajectory = planSpec(spec, { from: { x: 100, y: 500 }, to: { x: 900, y: 200 } });
+```
+
+| Part | Options |
+| ---------- | ------------------------------------------------------------------------------------------------ |
+| `path` | `straight`, `arc` (the Cua cubic bezier), `bow` |
+| `ease` | `linear`, `min_jerk`, `smootherstep`, `in_out_cubic`, `in_out_sine`, `out_cubic`, `cubic_bezier` |
+| `settle` | `none`, `follow_through`, `spring` |
+| `duration` | `fixed`, `fitts`, `distance` |
+| `heading` | `tangent` (the tip leads), `fixed` (rest pose) |
+
+Custom specs play in your renderer. Cua Driver takes one of the six styles;
+`driverSnippets(params)` returns the matching `cua-driver config set` and
+`cua-driver cursor motion` commands and the `set_agent_cursor_motion`
+arguments.
+
+## Playground
+
+Pick a style, drag the start and end points, tune the curve and copy the
+config:
+
+```bash
+cd libs/typescript
+pnpm install
+pnpm --filter @trycua/cursor-motion playground # http://127.0.0.1:4173/playground/
+```
+
+## Tests
+
+```bash
+pnpm --filter @trycua/cursor-motion test
+```
+
+`tests/golden.test.ts` replays every case in
+`libs/cua-driver/rust/crates/cua-cursor-motion/fixtures/golden.json` (all styles,
+timings and custom specs, with effect frames) and must match the Rust crate
+within 1e-6 pt. Today the worst deviation is 5e-10 pt.
+
+## License
+
+MIT
diff --git a/libs/typescript/cursor-motion/package.json b/libs/typescript/cursor-motion/package.json
new file mode 100644
index 0000000000..ad409e4336
--- /dev/null
+++ b/libs/typescript/cursor-motion/package.json
@@ -0,0 +1,56 @@
+{
+ "name": "@trycua/cursor-motion",
+ "version": "0.1.0",
+ "private": true,
+ "packageManager": "[email protected]",
+ "description": "Agent cursor motions from Cua Driver: paths, Fitts timing, trails, and a canvas player. Used from the trycua/cua repository; not published.",
+ "type": "module",
+ "license": "MIT",
+ "homepage": "https://github.com/trycua/cua/tree/main/libs/typescript/cursor-motion",
+ "bugs": {
+ "url": "https://github.com/trycua/cua/issues"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/trycua/cua.git",
+ "directory": "libs/typescript/cursor-motion"
+ },
+ "author": "cua",
+ "keywords": [
+ "cursor",
+ "animation",
+ "motion",
+ "fitts",
+ "agent",
+ "computer-use"
+ ],
+ "sideEffects": false,
+ "files": [
+ "dist"
+ ],
+ "main": "./dist/index.js",
+ "module": "./dist/index.js",
+ "types": "./dist/index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./dist/index.d.ts",
+ "import": "./dist/index.js"
+ },
+ "./package.json": "./package.json"
+ },
+ "scripts": {
+ "build": "tsdown",
+ "dev": "tsdown --watch",
+ "test": "vitest run",
+ "typecheck": "tsc --noEmit",
+ "lint": "prettier --check .",
+ "playground": "tsdown && node playground/serve.mjs"
+ },
+ "devDependencies": {
+ "@types/node": "^22.15.17",
+ "tsdown": "^0.11.9",
+ "typescript": "^5.8.3",
+ "vitest": "^4.1.0",
+ "vite": "^7.3.5"
+ }
+}
diff --git a/libs/typescript/cursor-motion/playground/index.html b/libs/typescript/cursor-motion/playground/index.html
new file mode 100644
index 0000000000..31f8d4fe06
--- /dev/null
+++ b/libs/typescript/cursor-motion/playground/index.html
@@ -0,0 +1,79 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>Cua Cursor Motion playground</title>
+ <link rel="icon" href="data:," />
+ <link rel="stylesheet" href="./playground.css" />
+ </head>
+ <body>
+ <header>
+ <h1>Cua Cursor Motion</h1>
+ <p>
+ The agent cursor motions of Cua Driver. Drag the start and end points, tune the curve, and
+ copy the config. Source and how to use it:
+ <a href="https://github.com/trycua/cua/tree/main/libs/typescript/cursor-motion"
+ >trycua/cua</a
+ >.
+ </p>
+ </header>
+ <main>
+ <section class="stage-wrap">
+ <canvas
+ id="stage"
+ aria-label="Motion stage: the Cua cursor moves between two points"
+ ></canvas>
+ <div class="stage-bar">
+ <button id="replay" type="button">Replay</button>
+ <label
+ >Speed
+ <select id="speed">
+ <option value="1">1x</option>
+ <option value="0.5">0.5x</option>
+ <option value="0.25">0.25x</option>
+ <option value="0.1">0.1x</option>
+ </select></label
+ >
+ <label><input id="loop" type="checkbox" checked /> Loop</label>
+ <label><input id="ghost" type="checkbox" checked /> Path</label>
+ <span id="stats"></span>
+ </div>
+ <canvas id="speedplot" aria-label="Speed over time"></canvas>
+ </section>
+ <aside id="controls">
+ <fieldset>
+ <legend>Motion</legend>
+ <label class="row"
+ >Style
+ <select id="style"></select
+ ></label>
+ <label class="row"
+ >Timing
+ <select id="timing">
+ <option value="native">native</option>
+ <option value="fitts">fitts</option>
+ <option value="fixed">fixed</option>
+ </select></label
+ >
+ <div id="glide-row"></div>
+ <div id="target-row"></div>
+ </fieldset>
+ <fieldset id="knobs"><legend>Shape</legend></fieldset>
+ <fieldset id="custom" hidden><legend>Custom motion</legend></fieldset>
+ <fieldset id="effects"><legend>Effects</legend></fieldset>
+ <button id="to-custom" type="button">Edit as a custom motion</button>
+ </aside>
+ </main>
+ <section id="export">
+ <h2>Config</h2>
+ <div class="tabs" role="tablist">
+ <button type="button" role="tab" data-tab="ts" aria-selected="true">TypeScript</button>
+ <button type="button" role="tab" data-tab="driver" aria-selected="false">cua-driver</button>
+ </div>
+ <pre id="snippet"></pre>
+ <button id="copy" type="button">Copy</button>
+ </section>
+ <script type="module" src="./playground.js"></script>
+ </body>
+</html>
diff --git a/libs/typescript/cursor-motion/playground/playground.css b/libs/typescript/cursor-motion/playground/playground.css
new file mode 100644
index 0000000000..f811e83384
--- /dev/null
+++ b/libs/typescript/cursor-motion/playground/playground.css
@@ -0,0 +1,215 @@
+:root {
+ color-scheme: dark;
+ --bg: #07080a;
+ --panel: #101216;
+ --line: rgba(255, 255, 255, 0.09);
+ --text: #ecf2fa;
+ --muted: rgba(236, 242, 250, 0.6);
+ --blue: #5ec0e8;
+ font:
+ 14px/1.45 system-ui,
+ -apple-system,
+ 'Segoe UI',
+ sans-serif;
+}
+
+* {
+ box-sizing: border-box;
+}
+
+body {
+ margin: 0;
+ background: var(--bg);
+ color: var(--text);
+ padding: 28px clamp(16px, 3vw, 40px) 48px;
+}
+
+header h1 {
+ margin: 0;
+ font-size: 30px;
+ font-weight: 650;
+ letter-spacing: -0.02em;
+}
+
+header p {
+ margin: 6px 0 22px;
+ color: var(--muted);
+ max-width: 60ch;
+}
+
+main {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) 320px;
+ gap: 20px;
+ align-items: start;
+}
+
+@media (max-width: 900px) {
+ main {
+ grid-template-columns: 1fr;
+ }
+}
+
+#stage {
+ display: block;
+ width: 100%;
+ height: min(62vh, 620px);
+ border-radius: 12px;
+ border: 1px solid var(--line);
+ touch-action: none;
+}
+
+#speedplot {
+ display: block;
+ width: 100%;
+ height: 110px;
+ margin-top: 10px;
+ border-radius: 10px;
+ background: var(--panel);
+ border: 1px solid var(--line);
+}
+
+.stage-bar {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 16px;
+ align-items: center;
+ margin-top: 10px;
+ color: var(--muted);
+}
+
+#stats {
+ margin-left: auto;
+ font-variant-numeric: tabular-nums;
+}
+
+aside {
+ background: var(--panel);
+ border: 1px solid var(--line);
+ border-radius: 12px;
+ padding: 6px 16px 16px;
+ max-height: calc(62vh + 170px);
+ overflow: auto;
+}
+
+fieldset {
+ min-width: 0;
+ border: 0;
+ border-bottom: 1px solid var(--line);
+ margin: 0;
+ padding: 12px 0;
+}
+
+legend {
+ padding: 0;
+ font-weight: 600;
+ margin-bottom: 8px;
+}
+
+h3 {
+ margin: 14px 0 6px;
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--muted);
+}
+
+.row,
+.check {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: 10px;
+ margin: 6px 0;
+}
+
+.check {
+ justify-content: flex-start;
+}
+
+.slider {
+ display: grid;
+ grid-template-columns: 96px 1fr 56px;
+ gap: 8px;
+ align-items: center;
+ margin: 6px 0;
+ color: var(--muted);
+}
+
+.slider output {
+ text-align: right;
+ color: var(--text);
+ font-variant-numeric: tabular-nums;
+}
+
+input[type='range'] {
+ width: 100%;
+ accent-color: var(--blue);
+}
+
+input[type='checkbox'] {
+ accent-color: var(--blue);
+}
+
+select,
+button {
+ font: inherit;
+ color: var(--text);
+ background: #181b21;
+ border: 1px solid var(--line);
+ border-radius: 7px;
+ padding: 5px 10px;
+}
+
+button:hover,
+select:hover {
+ border-color: rgba(255, 255, 255, 0.22);
+}
+
+#to-custom {
+ width: 100%;
+ margin-top: 14px;
+}
+
+.note {
+ color: var(--muted);
+ margin: 0;
+}
+
+#export {
+ margin-top: 28px;
+ max-width: 980px;
+}
+
+#export h2 {
+ font-size: 18px;
+ margin: 0 0 10px;
+}
+
+.tabs {
+ display: flex;
+ gap: 6px;
+ margin-bottom: 8px;
+}
+
+.tabs [aria-selected='true'] {
+ border-color: var(--blue);
+}
+
+pre {
+ margin: 0 0 10px;
+ padding: 14px 16px;
+ background: var(--panel);
+ border: 1px solid var(--line);
+ border-radius: 10px;
+ overflow: auto;
+ font:
+ 12.5px/1.5 ui-monospace,
+ 'SF Mono',
+ Menlo,
+ monospace;
+ white-space: pre;
+}
+
+header a {
+ color: var(--blue);
+}
diff --git a/libs/typescript/cursor-motion/playground/playground.js b/libs/typescript/cursor-motion/playground/playground.js
new file mode 100644
index 0000000000..526b48a5f0
--- /dev/null
+++ b/libs/typescript/cursor-motion/playground/playground.js
@@ -0,0 +1,583 @@
+// Cua Cursor Motion playground. Plain ES module over the built package (../dist).
+// The cursor is drawn inside the canvas; the page's own pointer is untouched.
+import * as M from '../dist/index.js';
+
+const $ = (id) => document.getElementById(id);
+const stage = $('stage');
+const plot = $('speedplot');
+
+const state = {
+ mode: 'style', // or 'custom'
+ params: M.motionParams(),
+ spec: M.defaultSpec(),
+ a: null,
+ b: null,
+ target: { w: 96, h: 36 },
+ ghost: null,
+};
+
+// ── Stage ────────────────────────────────────────────────────────────────
+
+const rectAround = (p) => [
+ p.x - state.target.w / 2,
+ p.y - state.target.h / 2,
+ state.target.w,
+ state.target.h,
+];
+
+function drawScene(g) {
+ const w = stage.clientWidth;
+ const h = stage.clientHeight;
+ g.fillStyle = '#0b0d10';
+ g.fillRect(0, 0, w, h);
+ g.fillStyle = 'rgba(255,255,255,0.05)';
+ for (let x = 32; x < w; x += 32) for (let y = 32; y < h; y += 32) g.fillRect(x - 1, y - 1, 2, 2);
+ for (const [p, label] of [
+ [state.a, 'start'],
+ [state.b, 'end'],
+ ]) {
+ const [x, y, rw, rh] = rectAround(p);
+ g.fillStyle = 'rgba(255,255,255,0.04)';
+ g.strokeStyle = 'rgba(255,255,255,0.18)';
+ g.lineWidth = 1;
+ g.beginPath();
+ g.roundRect(x, y, rw, rh, 7);
+ g.fill();
+ g.stroke();
+ g.fillStyle = 'rgba(236,242,250,0.55)';
+ g.font = '500 12px system-ui, -apple-system, sans-serif';
+ g.textAlign = 'center';
+ g.fillText(label, p.x, y + rh + 16);
+ }
+ if ($('ghost').checked && state.ghost) {
+ g.strokeStyle = 'rgba(159,215,255,0.28)';
+ g.lineWidth = 1.5;
+ g.setLineDash([4, 5]);
+ g.beginPath();
+ state.ghost.samples.forEach((s, i) => (i ? g.lineTo(s.x, s.y) : g.moveTo(s.x, s.y)));
+ g.stroke();
+ g.setLineDash([]);
+ }
+ for (const p of [state.a, state.b]) {
+ g.strokeStyle = 'rgba(236,242,250,0.85)';
+ g.lineWidth = 1.5;
+ g.beginPath();
+ g.arc(p.x, p.y, 6, 0, 2 * Math.PI);
+ g.stroke();
+ }
+}
+
+const player = new M.MotionPlayer(stage, { drawScene });
+
+function moveOptions(to) {
+ const common = { target: rectAround(to), click: true };
+ return state.mode === 'custom'
+ ? { ...common, spec: state.spec }
+ : { ...common, params: state.params };
+}
+
+function planGhost() {
+ const req = { from: state.a, to: state.b, target: rectAround(state.b), seed: 'ghost' };
+ state.ghost =
+ state.mode === 'custom' ? M.planSpec(state.spec, req) : M.planMove(state.params, req);
+ const t = state.ghost;
+ $('stats').textContent =
+ `${Math.round(t.arrivalT * 1000)} ms to arrive, ${Math.round(t.duration() * 1000)} ms with settle`;
+ drawPlot(t);
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms / player.timeScale));
+let run = 0;
+async function play() {
+ const id = ++run;
+ planGhost();
+ player.place(state.a);
+ await sleep(350);
+ while (id === run) {
+ await player.moveTo(state.b, moveOptions(state.b));
+ if (id !== run) return;
+ await sleep(900);
+ if (!$('loop').checked || id !== run) return;
+ await player.moveTo(state.a, moveOptions(state.a));
+ if (id !== run) return;
+ await sleep(900);
+ }
+}
+
+let pending = 0;
+function changed() {
+ clearTimeout(pending);
+ planGhost();
+ renderExport();
+ pending = setTimeout(play, 120);
+}
+
+// Drag the start and end points. Only the canvas drawing changes; the real
+// pointer keeps its normal look.
+let dragging = null;
+const local = (e) => {
+ const r = stage.getBoundingClientRect();
+ return { x: e.clientX - r.left, y: e.clientY - r.top };
+};
+stage.addEventListener('pointerdown', (e) => {
+ const p = local(e);
+ const near = (q) => Math.hypot(q.x - p.x, q.y - p.y) < 24;
+ dragging = near(state.b) ? 'b' : near(state.a) ? 'a' : null;
+ if (dragging) {
+ stage.setPointerCapture(e.pointerId);
+ run++;
+ }
+});
+stage.addEventListener('pointermove', (e) => {
+ if (!dragging) return;
+ const p = local(e);
+ state[dragging] = {
+ x: Math.min(Math.max(p.x, 12), stage.clientWidth - 12),
+ y: Math.min(Math.max(p.y, 12), stage.clientHeight - 12),
+ };
+ planGhost();
+ player.place(state.a);
+});
+stage.addEventListener('pointerup', () => {
+ if (!dragging) return;
+ dragging = null;
+ changed();
+});
+
+// ── Speed plot ───────────────────────────────────────────────────────────
+
+function drawPlot(traj) {
+ const dpr = window.devicePixelRatio || 1;
+ const w = plot.clientWidth;
+ const h = plot.clientHeight;
+ plot.width = Math.round(w * dpr);
+ plot.height = Math.round(h * dpr);
+ const g = plot.getContext('2d');
+ g.setTransform(dpr, 0, 0, dpr, 0, 0);
+ g.clearRect(0, 0, w, h);
+ const s = traj.samples;
+ const speeds = s.slice(1).map((q, i) => {
+ const p = s[i];
+ const dt = q.t - p.t;
+ return { t: q.t, v: dt > 0 ? Math.hypot(q.x - p.x, q.y - p.y) / dt : 0 };
+ });
+ const tMax = Math.max(traj.duration(), 0.001);
+ const vMax = Math.max(...speeds.map((p) => p.v), 1);
+ const pad = 22;
+ const X = (t) => pad + (t / tMax) * (w - 2 * pad);
+ const Y = (v) => h - 18 - (v / vMax) * (h - 30);
+ g.strokeStyle = 'rgba(255,255,255,0.12)';
+ g.beginPath();
+ g.moveTo(pad, h - 18);
+ g.lineTo(w - pad, h - 18);
+ g.stroke();
+ g.strokeStyle = '#5ec0e8';
+ g.lineWidth = 1.75;
+ g.beginPath();
+ speeds.forEach((p, i) => (i ? g.lineTo(X(p.t), Y(p.v)) : g.moveTo(X(p.t), Y(p.v))));
+ g.stroke();
+ g.strokeStyle = 'rgba(236,242,250,0.5)';
+ g.setLineDash([3, 4]);
+ g.beginPath();
+ g.moveTo(X(traj.arrivalT), 6);
+ g.lineTo(X(traj.arrivalT), h - 18);
+ g.stroke();
+ g.setLineDash([]);
+ g.fillStyle = 'rgba(236,242,250,0.6)';
+ g.font = '11px system-ui, -apple-system, sans-serif';
+ g.textAlign = 'left';
+ g.fillText(`speed, peak ${Math.round(vMax)} pt/s`, pad, 12);
+ g.textAlign = 'center';
+ g.fillText('arrival', X(traj.arrivalT), h - 4);
+}
+
+// ── Controls ─────────────────────────────────────────────────────────────
+
+function slider(parent, label, { min, max, step, get, set, fmt = (v) => v }) {
+ const row = document.createElement('label');
+ row.className = 'slider';
+ const name = document.createElement('span');
+ name.textContent = label;
+ const input = Object.assign(document.createElement('input'), { type: 'range', min, max, step });
+ input.value = get();
+ const out = document.createElement('output');
+ out.textContent = fmt(Number(input.value));
+ input.addEventListener('input', () => {
+ set(Number(input.value));
+ out.textContent = fmt(Number(input.value));
+ changed();
+ });
+ row.append(name, input, out);
+ parent.append(row);
+ return row;
+}
+
+function select(parent, label, options, get, set) {
+ const row = document.createElement('label');
+ row.className = 'row';
+ row.append(label + ' ');
+ const sel = document.createElement('select');
+ for (const [value, text] of options) sel.append(new Option(text, value));
+ sel.value = get();
+ sel.addEventListener('change', () => {
+ set(sel.value);
+ build();
+ changed();
+ });
+ row.append(sel);
+ parent.append(row);
+}
+
+const clearBox = (el) => el.querySelectorAll(':scope > :not(legend)').forEach((n) => n.remove());
+const f2 = (v) => v.toFixed(2);
+
+function buildStyle() {
+ const style = $('style');
+ style.replaceChildren(
+ ...M.MOTION_STYLES.map((s) => new Option(s, s)),
+ new Option('custom', 'custom')
+ );
+ style.value = state.mode === 'custom' ? 'custom' : state.params.style;
+ $('timing').value = state.params.timing;
+ $('timing').disabled = state.mode === 'custom';
+
+ clearBox($('glide-row'));
+ if (state.mode === 'style' && state.params.timing === 'fixed') {
+ slider($('glide-row'), 'Move time', {
+ min: 0,
+ max: 3000,
+ step: 10,
+ get: () => state.params.glideDurationMs,
+ set: (v) => (state.params.glideDurationMs = v),
+ fmt: (v) => (v ? `${v} ms` : '1430 ms'),
+ });
+ }
+ clearBox($('target-row'));
+ slider($('target-row'), 'Target width', {
+ min: 8,
+ max: 240,
+ step: 1,
+ get: () => state.target.w,
+ set: (v) => {
+ state.target.w = v;
+ state.target.h = Math.min(v, 36);
+ },
+ fmt: (v) => `${v} pt`,
+ });
+}
+
+function buildKnobs() {
+ const box = $('knobs');
+ clearBox(box);
+ box.hidden = state.mode === 'custom';
+ if (box.hidden) return;
+ const p = state.params;
+ const k = (label, key, min, max, step, note) =>
+ slider(box, note ? `${label} (${note})` : label, {
+ min,
+ max,
+ step,
+ get: () => p[key],
+ set: (v) => (p[key] = v),
+ fmt: f2,
+ });
+ const arc = !['magnetic', 'adaptive', 'classic'].includes(p.style);
+ if (arc) {
+ k('Arc size', 'arcSize', 0, 1, 0.01);
+ k('Arc flow', 'arcFlow', -1, 1, 0.01);
+ k('Start handle', 'startHandle', 0, 1, 0.01);
+ k('End handle', 'endHandle', 0, 1, 0.01);
+ } else if (p.style === 'classic') {
+ k('Spring', 'spring', 0.3, 1, 0.01);
+ k('Turn radius', 'turnRadius', 10, 300, 1);
+ } else {
+ const note = document.createElement('p');
+ note.className = 'note';
+ note.textContent =
+ p.style === 'magnetic'
+ ? 'Magnetic is a physics simulation: it slows to a 40 pt capture radius, then the target pulls it in.'
+ : 'Adaptive picks a precise approach for targets under 16 pt, a swoop beyond 900 pt, and a Fitts min-jerk glide otherwise. Try the target width.';
+ box.append(note);
+ }
+}
+
+function buildEffects() {
+ const box = $('effects');
+ clearBox(box);
+ for (const name of M.EFFECT_NAMES) {
+ if (state.mode === 'custom') {
+ const row = document.createElement('label');
+ row.className = 'check';
+ const input = Object.assign(document.createElement('input'), {
+ type: 'checkbox',
+ checked: state.spec.effects[name],
+ });
+ input.addEventListener('change', () => {
+ state.spec.effects[name] = input.checked;
+ changed();
+ });
+ row.append(input, ' ' + name);
+ box.append(row);
+ } else {
+ const base = M.defaultEffects(state.params.style)[name];
+ select(
+ box,
+ name,
+ [
+ ['default', `style default (${base ? 'on' : 'off'})`],
+ ['on', 'on'],
+ ['off', 'off'],
+ ],
+ () => {
+ const v = state.params.effects[name];
+ return v == null ? 'default' : v ? 'on' : 'off';
+ },
+ (v) => (state.params.effects[name] = v === 'default' ? null : v === 'on')
+ );
+ }
+ }
+}
+
+function buildCustom() {
+ const box = $('custom');
+ clearBox(box);
+ box.hidden = state.mode !== 'custom';
+ $('to-custom').hidden = state.mode === 'custom';
+ if (box.hidden) return;
+ const s = state.spec;
+ const sub = (title) => {
+ const h = document.createElement('h3');
+ h.textContent = title;
+ box.append(h);
+ };
+ const num = (obj, label, key, min, max, step, fmt = f2) =>
+ slider(box, label, { min, max, step, get: () => obj[key], set: (v) => (obj[key] = v), fmt });
+
+ sub('Path');
+ select(
+ box,
+ 'Shape',
+ [
+ ['arc', 'arc (Cua bezier)'],
+ ['bow', 'bow'],
+ ['straight', 'straight'],
+ ],
+ () => s.path.type,
+ (v) => {
+ s.path =
+ v === 'arc'
+ ? { type: 'arc', startHandle: 0.3, endHandle: 0.3, arcSize: 0.16, arcFlow: 0.15 }
+ : v === 'bow'
+ ? { type: 'bow', amount: 0.06 }
+ : { type: 'straight' };
+ }
+ );
+ if (s.path.type === 'arc') {
+ num(s.path, 'Arc size', 'arcSize', -0.6, 0.6, 0.01);
+ num(s.path, 'Arc flow', 'arcFlow', -1, 1, 0.01);
+ num(s.path, 'Start handle', 'startHandle', 0, 1, 0.01);
+ num(s.path, 'End handle', 'endHandle', 0, 1, 0.01);
+ } else if (s.path.type === 'bow') {
+ num(s.path, 'Bow', 'amount', -0.4, 0.4, 0.01);
+ }
+
+ sub('Speed curve');
+ const easeType = typeof s.ease === 'string' ? s.ease : s.ease.type;
+ select(
+ box,
+ 'Ease',
+ [...M.EASE_NAMES.map((n) => [n, n]), ['cubic_bezier', 'cubic-bezier()']],
+ () => easeType,
+ (v) => {
+ s.ease = v === 'cubic_bezier' ? { type: 'cubic_bezier', x1: 0.3, y1: 0, x2: 0.1, y2: 1 } : v;
+ }
+ );
+ if (easeType === 'cubic_bezier') {
+ num(s.ease, 'x1', 'x1', 0, 1, 0.01);
+ num(s.ease, 'y1', 'y1', -0.5, 1.5, 0.01);
+ num(s.ease, 'x2', 'x2', 0, 1, 0.01);
+ num(s.ease, 'y2', 'y2', -0.5, 1.5, 0.01);
+ }
+
+ sub('Overshoot and settle');
+ select(
+ box,
+ 'Settle',
+ [
+ ['none', 'none'],
+ ['follow_through', 'follow-through'],
+ ['spring', 'spring'],
+ ],
+ () => s.settle.type,
+ (v) => {
+ s.settle =
+ v === 'follow_through'
+ ? { type: 'follow_through', amount: 0.018, maxPt: 8, at: 0.82 }
+ : v === 'spring'
+ ? {
+ type: 'spring',
+ amount: 0.05,
+ maxPt: 6,
+ cycles: 1.3,
+ decay: 2.6,
+ start: 0.55,
+ glideEnd: 0.68,
+ }
+ : { type: 'none' };
+ }
+ );
+ if (s.settle.type === 'follow_through') {
+ num(s.settle, 'Amount', 'amount', 0, 0.15, 0.001, (v) => v.toFixed(3));
+ num(s.settle, 'Max', 'maxPt', 0, 40, 0.5, (v) => `${v} pt`);
+ num(s.settle, 'Peak at', 'at', 0.5, 0.98, 0.01);
+ } else if (s.settle.type === 'spring') {
+ num(s.settle, 'Amount', 'amount', 0, 0.2, 0.001, (v) => v.toFixed(3));
+ num(s.settle, 'Max', 'maxPt', 0, 40, 0.5, (v) => `${v} pt`);
+ num(s.settle, 'Cycles', 'cycles', 0.5, 4, 0.1);
+ num(s.settle, 'Decay', 'decay', 0.5, 8, 0.1);
+ num(s.settle, 'Starts at', 'start', 0.2, 0.9, 0.01);
+ num(s.settle, 'Glide ends', 'glideEnd', 0.3, 1, 0.01);
+ }
+
+ sub('Duration');
+ select(
+ box,
+ 'Model',
+ [
+ ['fitts', "Fitts' law"],
+ ['fixed', 'fixed'],
+ ['distance', 'distance'],
+ ],
+ () => s.duration.type,
+ (v) => {
+ s.duration =
+ v === 'fitts'
+ ? M.fittsDuration(1.1)
+ : v === 'fixed'
+ ? { type: 'fixed', ms: 600 }
+ : { type: 'distance', baseMs: 350, msPerPt: 0.35, minMs: 450, maxMs: 1100 };
+ }
+ );
+ if (s.duration.type === 'fitts') num(s.duration, 'Scale', 'scale', 0.3, 3, 0.05);
+ else if (s.duration.type === 'fixed')
+ num(s.duration, 'Time', 'ms', 80, 3000, 10, (v) => `${v} ms`);
+ else {
+ num(s.duration, 'Base', 'baseMs', 0, 1000, 10, (v) => `${v} ms`);
+ num(s.duration, 'Per point', 'msPerPt', 0, 2, 0.01, (v) => `${v} ms`);
+ }
+ select(
+ box,
+ 'Heading',
+ [
+ ['tangent', 'tip leads'],
+ ['fixed', 'rest pose'],
+ ],
+ () => s.heading,
+ (v) => (s.heading = v)
+ );
+
+ sub('Trail');
+ num(s.trail, 'Length', 'secs', 0.05, 0.6, 0.01, (v) => `${Math.round(v * 1000)} ms`);
+ num(s.trail, 'Width', 'headWidth', 2, 28, 0.5, (v) => `${v} pt`);
+ num(s.trail, 'Opacity', 'alpha', 0.05, 1, 0.01);
+}
+
+function build() {
+ buildStyle();
+ buildKnobs();
+ buildCustom();
+ buildEffects();
+}
+
+$('style').addEventListener('change', (e) => {
+ const v = e.target.value;
+ if (v === 'custom') {
+ toCustom();
+ return;
+ }
+ state.mode = 'style';
+ state.params.style = v;
+ build();
+ changed();
+});
+$('timing').addEventListener('change', (e) => {
+ state.params.timing = e.target.value;
+ build();
+ changed();
+});
+function toCustom() {
+ state.spec = M.specForStyle(state.params.style, state.params) ?? M.defaultSpec();
+ state.mode = 'custom';
+ build();
+ changed();
+}
+$('to-custom').addEventListener('click', toCustom);
+$('replay').addEventListener('click', play);
+$('speed').addEventListener('change', (e) => (player.timeScale = Number(e.target.value)));
+$('loop').addEventListener('change', () => $('loop').checked && play());
+$('ghost').addEventListener('change', () => {});
+
+// ── Export ───────────────────────────────────────────────────────────────
+
+let tab = 'ts';
+function renderExport() {
+ let text;
+ if (tab === 'ts') {
+ text = state.mode === 'custom' ? M.specSnippet(state.spec) : M.paramsSnippet(state.params);
+ } else if (state.mode === 'custom') {
+ text =
+ '# Custom motions play in your own renderer (Rust: cua-cursor-motion plan_spec,\n' +
+ '# TypeScript: planSpec). Cua Driver takes one of the six styles and its\n' +
+ '# knobs: pick a style to get its cua-driver config.';
+ } else {
+ const d = M.driverSnippets(state.params, 'demo');
+ text = [
+ '# Default for new sessions',
+ ...d.configSet,
+ '',
+ '# One running session',
+ d.cursorMotion,
+ '',
+ d.callOnly.length
+ ? `# set_agent_cursor_motion (${d.callOnly.join(', ')} only travel this way)`
+ : '# set_agent_cursor_motion',
+ `cua-driver set_agent_cursor_motion '${JSON.stringify(d.setAgentCursorMotion)}'`,
+ ].join('\n');
+ }
+ $('snippet').textContent = text;
+}
+document.querySelectorAll('[data-tab]').forEach((b) =>
+ b.addEventListener('click', () => {
+ tab = b.dataset.tab;
+ document
+ .querySelectorAll('[data-tab]')
+ .forEach((x) => x.setAttribute('aria-selected', String(x === b)));
+ renderExport();
+ })
+);
+$('copy').addEventListener('click', async () => {
+ await navigator.clipboard.writeText($('snippet').textContent);
+ $('copy').textContent = 'Copied';
+ setTimeout(() => ($('copy').textContent = 'Copy'), 1200);
+});
+
+// ── Start ────────────────────────────────────────────────────────────────
+
+function layout() {
+ const w = stage.clientWidth;
+ const h = stage.clientHeight;
+ state.a = { x: Math.round(w * 0.16), y: Math.round(h * 0.74) };
+ state.b = { x: Math.round(w * 0.8), y: Math.round(h * 0.3) };
+}
+layout();
+build();
+renderExport();
+play();
+let resized = 0;
+window.addEventListener('resize', () => {
+ clearTimeout(resized);
+ resized = setTimeout(() => {
+ layout();
+ changed();
+ }, 150);
+});
diff --git a/libs/typescript/cursor-motion/playground/serve.mjs b/libs/typescript/cursor-motion/playground/serve.mjs
new file mode 100644
index 0000000000..9d620aa996
--- /dev/null
+++ b/libs/typescript/cursor-motion/playground/serve.mjs
@@ -0,0 +1,38 @@
+// Serve the playground and the built package with no dependencies:
+// pnpm --filter @trycua/cursor-motion playground # http://127.0.0.1:4173/playground/
+// PORT=8080 HOST=0.0.0.0 node playground/serve.mjs
+import { createServer } from 'node:http';
+import { readFile } from 'node:fs/promises';
+import { extname, join, normalize, sep } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const root = fileURLToPath(new URL('..', import.meta.url));
+const port = Number(process.env.PORT ?? 4173);
+const host = process.env.HOST ?? '127.0.0.1';
+const types = {
+ '.html': 'text/html; charset=utf-8',
+ '.js': 'text/javascript; charset=utf-8',
+ '.css': 'text/css; charset=utf-8',
+ '.json': 'application/json',
+ '.svg': 'image/svg+xml',
+};
+
+createServer(async (req, res) => {
+ let path = decodeURIComponent(new URL(req.url ?? '/', 'http://x').pathname);
+ if (path === '/' || path === '/playground') path = '/playground/';
+ if (path.endsWith('/')) path += 'index.html';
+ const file = normalize(join(root, path));
+ if (!file.startsWith(root) || file.includes(`${sep}node_modules${sep}`)) {
+ res.writeHead(403).end();
+ return;
+ }
+ try {
+ const body = await readFile(file);
+ res.writeHead(200, { 'content-type': types[extname(file)] ?? 'application/octet-stream' });
+ res.end(body);
+ } catch {
+ res.writeHead(404).end('not found');
+ }
+}).listen(port, host, () =>
+ console.log(`Cua Cursor Motion playground: http://${host}:${port}/playground/`)
+);
diff --git a/libs/typescript/cursor-motion/src/driver.ts b/libs/typescript/cursor-motion/src/driver.ts
new file mode 100644
index 0000000000..edc94eb859
--- /dev/null
+++ b/libs/typescript/cursor-motion/src/driver.ts
@@ -0,0 +1,105 @@
+/**
+ * Config snippets: the same motion as TypeScript, and as Cua Driver settings
+ * where the driver supports it (the six styles and their knobs).
+ */
+import { DEFAULT_PARAMS, motionParams, type MotionParams } from './params';
+import type { MotionSpec } from './spec';
+import { EFFECT_NAMES } from './style';
+
+const round = (v: number) => Math.round(v * 1000) / 1000;
+
+/** Knobs that differ from the defaults, rounded for display. */
+function changedKnobs(p: MotionParams): Partial<MotionParams> {
+ const out: Record<string, unknown> = {};
+ for (const key of Object.keys(DEFAULT_PARAMS) as (keyof MotionParams)[]) {
+ if (key === 'effects') continue;
+ const v = p[key];
+ if (v !== DEFAULT_PARAMS[key]) out[key] = typeof v === 'number' ? round(v) : v;
+ }
+ const effects = Object.fromEntries(
+ EFFECT_NAMES.filter((n) => p.effects[n] != null).map((n) => [n, p.effects[n]])
+ );
+ if (Object.keys(effects).length) out.effects = effects;
+ return out as Partial<MotionParams>;
+}
+
+const SNAKE: Record<string, string> = {
+ startHandle: 'start_handle',
+ endHandle: 'end_handle',
+ arcSize: 'arc_size',
+ arcFlow: 'arc_flow',
+ spring: 'spring',
+ glideDurationMs: 'glide_duration_ms',
+ turnRadius: 'turn_radius',
+};
+
+export interface DriverSnippets {
+ /** Saved default for new sessions (style, timing, effects only). */
+ configSet: string[];
+ /** One session, from the shell. */
+ cursorMotion: string;
+ /** The `set_agent_cursor_motion` arguments, including the shape knobs. */
+ setAgentCursorMotion: Record<string, unknown>;
+ /** Knobs the saved default and the shell command cannot carry. */
+ callOnly: string[];
+}
+
+/** Cua Driver equivalents of built-in style params. */
+export function driverSnippets(params: Partial<MotionParams>, session = 'demo'): DriverSnippets {
+ const p = motionParams(params);
+ const configSet = [
+ `cua-driver config set cursor.motion.style ${p.style}`,
+ `cua-driver config set cursor.motion.timing ${p.timing}`,
+ ];
+ const effectArgs: string[] = [];
+ for (const n of EFFECT_NAMES) {
+ const v = p.effects[n];
+ if (v == null) continue;
+ configSet.push(`cua-driver config set cursor.motion.effects.${n} ${v}`);
+ effectArgs.push(`${n}=${v ? 'on' : 'off'}`);
+ }
+ let cursorMotion = `cua-driver cursor motion --session ${session} --style ${p.style} --timing ${p.timing}`;
+ if (effectArgs.length) cursorMotion += ` --effects ${effectArgs.join(',')}`;
+ if (p.glideDurationMs > 0) cursorMotion += ` --glide-ms ${round(p.glideDurationMs)}`;
+ const call: Record<string, unknown> = { session, style: p.style, timing: p.timing };
+ const callOnly: string[] = [];
+ for (const [camel, snake] of Object.entries(SNAKE)) {
+ const v = p[camel as keyof MotionParams] as number;
+ if (v !== DEFAULT_PARAMS[camel as keyof MotionParams]) {
+ call[snake] = round(v);
+ if (camel !== 'glideDurationMs') callOnly.push(snake);
+ }
+ }
+ if (effectArgs.length) {
+ call.effects = Object.fromEntries(
+ EFFECT_NAMES.filter((n) => p.effects[n] != null).map((n) => [n, p.effects[n]])
+ );
+ }
+ return { configSet, cursorMotion, setAgentCursorMotion: call, callOnly };
+}
+
+/** TypeScript for planning these params with `@trycua/cursor-motion`. */
+export function paramsSnippet(params: Partial<MotionParams>): string {
+ return [
+ "import { planMove } from './vendor/cua-cursor-motion.js';",
+ '',
+ `const params = ${JSON.stringify(changedKnobs(motionParams(params)), null, 2)};`,
+ 'const trajectory = planMove(params, { from, to, target });',
+ ].join('\n');
+}
+
+/** TypeScript for a custom spec. */
+export function specSnippet(spec: MotionSpec): string {
+ const r = (v: unknown): unknown =>
+ typeof v === 'number'
+ ? round(v)
+ : v && typeof v === 'object'
+ ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, r(x)]))
+ : v;
+ return [
+ "import { planSpec, type MotionSpec } from './vendor/cua-cursor-motion.js';",
+ '',
+ `const spec: MotionSpec = ${JSON.stringify(r(spec), null, 2)};`,
+ 'const trajectory = planSpec(spec, { from, to, target });',
+ ].join('\n');
+}
diff --git a/libs/typescript/cursor-motion/src/dubins.ts b/libs/typescript/cursor-motion/src/dubins.ts
new file mode 100644
index 0000000000..7d4a656933
--- /dev/null
+++ b/libs/typescript/cursor-motion/src/dubins.ts
@@ -0,0 +1,169 @@
+/** Dubins arc-straight-arc planner of the `classic` glide (port of `dubins.rs`). */
+
+type Seg = 'L' | 'R' | 'S';
+
+export interface PathState {
+ x: number;
+ y: number;
+ heading: number;
+}
+
+const TAU = 2 * Math.PI;
+
+function mod2pi(x: number): number {
+ const r = x - TAU * Math.floor(x / TAU);
+ return r < 0 ? r + TAU : r;
+}
+
+interface Sol {
+ t: number;
+ p: number;
+ q: number;
+ types: [Seg, Seg, Seg];
+}
+
+function lsl(d: number, a: number, b: number): Sol | null {
+ const tmp0 = d + Math.sin(a) - Math.sin(b);
+ const p2 = 2 + d * d - 2 * Math.cos(a - b) + 2 * d * (Math.sin(a) - Math.sin(b));
+ if (p2 < 0) return null;
+ const tmp1 = Math.atan2(Math.cos(b) - Math.cos(a), tmp0);
+ return { t: mod2pi(-a + tmp1), p: Math.sqrt(p2), q: mod2pi(b - tmp1), types: ['L', 'S', 'L'] };
+}
+
+function rsr(d: number, a: number, b: number): Sol | null {
+ const tmp0 = d - Math.sin(a) + Math.sin(b);
+ const p2 = 2 + d * d - 2 * Math.cos(a - b) + 2 * d * (Math.sin(b) - Math.sin(a));
+ if (p2 < 0) return null;
+ const tmp1 = Math.atan2(Math.cos(a) - Math.cos(b), tmp0);
+ return { t: mod2pi(a - tmp1), p: Math.sqrt(p2), q: mod2pi(-b + tmp1), types: ['R', 'S', 'R'] };
+}
+
+function lsr(d: number, a: number, b: number): Sol | null {
+ const p2 = -2 + d * d + 2 * Math.cos(a - b) + 2 * d * (Math.sin(a) + Math.sin(b));
+ if (p2 < 0) return null;
+ const p = Math.sqrt(p2);
+ const tmp1 =
+ Math.atan2(-(Math.cos(a) + Math.cos(b)), d + Math.sin(a) + Math.sin(b)) - Math.atan2(-2, p);
+ return { t: mod2pi(-a + tmp1), p, q: mod2pi(-mod2pi(b) + tmp1), types: ['L', 'S', 'R'] };
+}
+
+function rsl(d: number, a: number, b: number): Sol | null {
+ const p2 = d * d - 2 + 2 * Math.cos(a - b) - 2 * d * (Math.sin(a) + Math.sin(b));
+ if (p2 < 0) return null;
+ const p = Math.sqrt(p2);
+ const tmp1 =
+ Math.atan2(Math.cos(a) + Math.cos(b), d - Math.sin(a) - Math.sin(b)) - Math.atan2(2, p);
+ return { t: mod2pi(a - tmp1), p, q: mod2pi(b - tmp1), types: ['R', 'S', 'L'] };
+}
+
+function rlr(d: number, a: number, b: number): Sol | null {
+ const tmp = (6 - d * d + 2 * Math.cos(a - b) + 2 * d * (Math.sin(a) - Math.sin(b))) / 8;
+ if (Math.abs(tmp) > 1) return null;
+ const p = mod2pi(TAU - Math.acos(tmp));
+ const t = mod2pi(
+ a - Math.atan2(Math.cos(a) - Math.cos(b), d - Math.sin(a) + Math.sin(b)) + p / 2
+ );
+ return { t, p, q: mod2pi(a - b - t + p), types: ['R', 'L', 'R'] };
+}
+
+function lrl(d: number, a: number, b: number): Sol | null {
+ const tmp = (6 - d * d + 2 * Math.cos(a - b) + 2 * d * (Math.sin(b) - Math.sin(a))) / 8;
+ if (Math.abs(tmp) > 1) return null;
+ const p = mod2pi(TAU - Math.acos(tmp));
+ const t = mod2pi(
+ -a + Math.atan2(-Math.cos(a) + Math.cos(b), d + Math.sin(a) - Math.sin(b)) + p / 2
+ );
+ return { t, p, q: mod2pi(mod2pi(b) - a - t + p), types: ['L', 'R', 'L'] };
+}
+
+export interface PlannedPath {
+ length: number;
+ sample(distance: number): PathState;
+}
+
+/** Plan a Dubins path from `(x0, y0)` heading `th0` to `(x1, y1)` heading `th1`. */
+export function planDubins(
+ x0: number,
+ y0: number,
+ th0: number,
+ x1: number,
+ y1: number,
+ th1: number,
+ turnRadius: number
+): PlannedPath {
+ const r = Math.max(turnRadius, 1);
+ const dx = x1 - x0;
+ const dy = y1 - y0;
+ const dd = Math.hypot(dx, dy);
+ let best: Sol | null = null;
+ if (dd >= 0.5) {
+ const d = dd / r;
+ const theta = mod2pi(Math.atan2(dy, dx));
+ const a = mod2pi(th0 - theta);
+ const b = mod2pi(th1 - theta);
+ let bestLen = Infinity;
+ for (const solver of [lsl, rsr, lsr, rsl, rlr, lrl]) {
+ const sol = solver(d, a, b);
+ if (!sol) continue;
+ const len = sol.t + sol.p + sol.q;
+ if (Number.isFinite(len) && len >= 0 && len < bestLen) {
+ bestLen = len;
+ best = sol;
+ }
+ }
+ }
+ if (!best) {
+ const length = Math.max(dd, 1);
+ return {
+ length,
+ sample(s) {
+ const u = Math.min(Math.max(s / Math.max(length, 1), 0), 1);
+ let diff = th1 - th0;
+ while (diff > Math.PI) diff -= TAU;
+ while (diff < -Math.PI) diff += TAU;
+ return { x: x0 + (x1 - x0) * u, y: y0 + (y1 - y0) * u, heading: th0 + diff * u };
+ },
+ };
+ }
+ const sol = best;
+ const l1 = sol.t * r;
+ const l2 = sol.p * r;
+ const l3 = sol.q * r;
+ return {
+ length: (sol.t + sol.p + sol.q) * r,
+ sample(sIn) {
+ if (sIn <= 0) return { x: x0, y: y0, heading: th0 };
+ const s = Math.min(sIn, l1 + l2 + l3);
+ let x = x0;
+ let y = y0;
+ let th = th0;
+ const advance = (len: number, seg: Seg) => {
+ if (seg === 'S') {
+ x += Math.cos(th) * len;
+ y += Math.sin(th) * len;
+ } else {
+ const dth = (len / r) * (seg === 'L' ? 1 : -1);
+ const side = seg === 'L' ? Math.PI / 2 : -Math.PI / 2;
+ const cx = x + Math.cos(th + side) * r;
+ const cy = y + Math.sin(th + side) * r;
+ const ang = Math.atan2(y - cy, x - cx);
+ x = cx + Math.cos(ang + dth) * r;
+ y = cy + Math.sin(ang + dth) * r;
+ th += dth;
+ }
+ };
+ if (s <= l1) {
+ advance(s, sol.types[0]);
+ return { x, y, heading: th };
+ }
+ advance(l1, sol.types[0]);
+ if (s <= l1 + l2) {
+ advance(s - l1, sol.types[1]);
+ return { x, y, heading: th };
+ }
+ advance(l2, sol.types[1]);
+ advance(s - l1 - l2, sol.types[2]);
+ return { x, y, heading: th };
+ },
+ };
+}
diff --git a/libs/typescript/cursor-motion/src/ease.ts b/libs/typescript/cursor-motion/src/ease.ts
new file mode 100644
index 0000000000..917831f4f4
--- /dev/null
+++ b/libs/typescript/cursor-motion/src/ease.ts
@@ -0,0 +1,99 @@
+/** Speed curves: how far along the path the cursor is at each moment. */
+
+export type EaseName =
+ | 'linear'
+ | 'min_jerk'
+ | 'smootherstep'
+ | 'in_out_cubic'
+ | 'in_out_sine'
+ | 'out_cubic';
+
+export type Ease =
+ | EaseName
+ | { type: EaseName }
+ | { type: 'cubic_bezier'; x1: number; y1: number; x2: number; y2: number };
+
+export const EASE_NAMES: EaseName[] = [
+ 'linear',
+ 'min_jerk',
+ 'smootherstep',
+ 'in_out_cubic',
+ 'in_out_sine',
+ 'out_cubic',
+];
+
+export const linear = (t: number): number => t;
+/** Minimum-jerk: the profile of a relaxed human reach. */
+export const minJerk = (t: number): number => t * t * t * (10 - 15 * t + 6 * t * t);
+export const smootherstep = (t: number): number => t * t * t * (t * (6 * t - 15) + 10);
+export const inOutCubic = (t: number): number =>
+ t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2;
+export const inOutSine = (t: number): number => 0.5 - 0.5 * Math.cos(Math.PI * t);
+export const outCubic = (t: number): number => 1 - (1 - t) ** 3;
+
+/** CSS-style `cubic-bezier(x1, y1, x2, y2)`. */
+export function cubicBezier(x1: number, y1: number, x2: number, y2: number, t: number): number {
+ if (t <= 0) return 0;
+ if (t >= 1) return 1;
+ const cx1 = Math.min(Math.max(x1, 0), 1);
+ const cx2 = Math.min(Math.max(x2, 0), 1);
+ const coord = (a: number, b: number, u: number) => {
+ const v = 1 - u;
+ return 3 * v * v * u * a + 3 * v * u * u * b + u * u * u;
+ };
+ let lo = 0;
+ let hi = 1;
+ for (let i = 0; i < 52; i++) {
+ const mid = 0.5 * (lo + hi);
+ if (coord(cx1, cx2, mid) < t) lo = mid;
+ else hi = mid;
+ }
+ return coord(y1, y2, 0.5 * (lo + hi));
+}
+
+const NAMED: Record<EaseName, (t: number) => number> = {
+ linear,
+ min_jerk: minJerk,
+ smootherstep,
+ in_out_cubic: inOutCubic,
+ in_out_sine: inOutSine,
+ out_cubic: outCubic,
+};
+
+/** The function behind an `Ease` value. */
+export function easeFn(ease: Ease): (t: number) => number {
+ if (typeof ease === 'string') return NAMED[ease];
+ if (ease.type === 'cubic_bezier') {
+ const { x1, y1, x2, y2 } = ease as Extract<Ease, { type: 'cubic_bezier' }>;
+ return (t) => cubicBezier(x1, y1, x2, y2, t);
+ }
+ return NAMED[ease.type];
+}
+
+/** Base plus a smooth bump that pushes `over` past the end, peaking at `overAt`. */
+export function bumpProfile(base: (t: number) => number, over: number, overAt: number) {
+ const a = Math.max(overAt * 10, 1.5);
+ const b = Math.max((1 - overAt) * 10, 1.5);
+ const peak = (a / (a + b)) ** a * (b / (a + b)) ** b;
+ return (tau: number) => base(tau) + over * ((tau ** a * (1 - tau) ** b) / peak);
+}
+
+/** Damped wobble around the end from `start` on. */
+export function wobbleProfile(
+ base: (t: number) => number,
+ amp: number,
+ cycles: number,
+ decay: number,
+ start: number
+) {
+ return (tau: number) => {
+ if (tau <= start) return base(tau);
+ const u = (tau - start) / (1 - start);
+ const ramp = smootherstep(Math.min(u / 0.18, 1));
+ return (
+ base(tau) +
+ (amp * ramp * Math.exp(-decay * u) * Math.sin(2 * Math.PI * cycles * u) * (1 - u) ** 2) /
+ Math.max(Math.exp(-decay * 0.12) * 0.77, 1e-6)
+ );
+ };
+}
diff --git a/libs/typescript/cursor-motion/src/effects.ts b/libs/typescript/cursor-motion/src/effects.ts
new file mode 100644
index 0000000000..34e7fe0610
--- /dev/null
+++ b/libs/typescript/cursor-motion/src/effects.ts
@@ -0,0 +1,209 @@
+/**
+ * Geometry of the motion effects at a moment of a move: comet trail, speed
+ * glow, magnet glow, click ripple and click squish. The renderer paints it.
+ */
+import { POINTER_ANCHOR_OFFSET, type Rect } from './geom';
+import type { Trajectory } from './plan';
+import type { ResolvedEffects } from './style';
+
+export interface TrailSpec {
+ /** How far back in time the trail reaches, seconds. */
+ secs: number;
+ /** Path length (pt) at which the trail reaches full strength. */
+ fadeLen: number;
+ /** Segments. */
+ steps: number;
+ /** Stroke width at the tail and the head, pt. */
+ tailWidth: number;
+ headWidth: number;
+ /** Opacity at the head; falls off with the square of the position. */
+ alpha: number;
+ /** How far behind the tip, along the arrow's axis, the trail starts, pt. */
+ anchorOffset: number;
+}
+
+export const DEFAULT_TRAIL: Readonly<TrailSpec> = Object.freeze({
+ secs: 0.18,
+ fadeLen: 60,
+ steps: 26,
+ tailWidth: 2,
+ headWidth: 12,
+ alpha: 0.38,
+ anchorOffset: POINTER_ANCHOR_OFFSET,
+});
+
+export const MAGNET_SECS = 0.7;
+export const MAGNET_INFLATE = 6;
+export const RIPPLE_SECS = 0.52;
+export const CLICK_FX_SECS = 0.55;
+export const SQUISH = 0.12;
+
+export interface Glow {
+ x: number;
+ y: number;
+ r: number;
+ alpha: number;
+}
+export interface TrailSeg {
+ a: [number, number];
+ b: [number, number];
+ width: number;
+ alpha: number;
+}
+export interface Magnet {
+ rect: Rect;
+ glow: number;
+}
+export interface Ripple {
+ x: number;
+ y: number;
+ r: number;
+ width: number;
+ alpha: number;
+}
+export interface EffectFrame {
+ glow: Glow | null;
+ trail: TrailSeg[];
+ magnet: Magnet | null;
+ ripple: Ripple | null;
+ /** Scale-down of the cursor, 0 = none. */
+ squish: number;
+}
+
+export const emptyFrame = (): EffectFrame => ({
+ glow: null,
+ trail: [],
+ magnet: null,
+ ripple: null,
+ squish: 0,
+});
+
+/** Speed glow at `t` around `pos` (the cursor's anchor). */
+export function glow(traj: Trajectory, t: number, pos: [number, number]): Glow | null {
+ if (t >= traj.duration()) return null;
+ const [vx, vy] = traj.velocityAt(t);
+ const speed = Math.hypot(vx, vy);
+ const alpha = Math.min(speed * 0.00014, 0.42);
+ if (alpha <= 0.02) return null;
+ const off = Math.min(speed * 0.009, 18);
+ return {
+ x: pos[0] - (vx / speed) * off,
+ y: pos[1] - (vy / speed) * off,
+ r: 30 * (1 + Math.min(speed * 0.00024, 0.44)),
+ alpha,
+ };
+}
+
+/** Comet trail at `t`, tail first, following the arrow's body. */
+export function trail(traj: Trajectory, t: number): TrailSeg[] {
+ const spec = traj.trail;
+ const steps = Math.max(spec.steps, 1);
+ const pts: [number, number][] = [];
+ for (let i = 0; i <= steps; i++) {
+ const s = traj.sampleAt(t - spec.secs + spec.secs * (i / steps));
+ pts.push([
+ s.x + Math.cos(s.heading) * spec.anchorOffset,
+ s.y + Math.sin(s.heading) * spec.anchorOffset,
+ ]);
+ }
+ let length = 0;
+ for (let i = 1; i <= steps; i++) {
+ length += Math.hypot(pts[i]![0] - pts[i - 1]![0], pts[i]![1] - pts[i - 1]![1]);
+ }
+ const fade = Math.min(length / spec.fadeLen, 1);
+ const out: TrailSeg[] = [];
+ for (let i = 1; i <= steps; i++) {
+ const a = pts[i - 1]!;
+ const b = pts[i]!;
+ const k = i / steps;
+ if (Math.hypot(b[0] - a[0], b[1] - a[1]) > 0.3) {
+ out.push({
+ a,
+ b,
+ width: spec.tailWidth + (spec.headWidth - spec.tailWidth) * k,
+ alpha: spec.alpha * k * k * fade,
+ });
+ }
+ }
+ return out;
+}
+
+/** Magnet glow at `t`, after a lock-on. */
+export function magnet(traj: Trajectory, t: number): Magnet | null {
+ if (traj.snapT === null) return null;
+ const age = t - traj.snapT;
+ if (!(age >= 0 && age < MAGNET_SECS)) return null;
+ const end = traj.end();
+ return {
+ rect: traj.targetKnown ? traj.target : [end.x - 12, end.y - 12, 24, 24],
+ glow: 1 - age / MAGNET_SECS,
+ };
+}
+
+/** Click ripple `age` seconds after a click at `point`. */
+export function ripple(age: number, point: [number, number]): Ripple | null {
+ if (age >= RIPPLE_SECS) return null;
+ const k = age / RIPPLE_SECS;
+ const easeOut = 1 - (1 - k) ** 3;
+ return {
+ x: point[0],
+ y: point[1],
+ r: 8 + 44 * easeOut,
+ width: 4 * (1 - k) + 1,
+ alpha: 0.75 * (1 - k),
+ };
+}
+
+/** Click squish `age` seconds after a click. */
+export function squish(age: number): number {
+ const PRESS = 0.09;
+ if (age < PRESS) return SQUISH * Math.min(age / 0.05, 1);
+ const after = age - PRESS;
+ return (
+ SQUISH *
+ Math.max(Math.cos(Math.min(after / 0.22, 1) * Math.PI * 1.5), 0) *
+ Math.max(1 - after / 0.22, 0)
+ );
+}
+
+/** The move's effects at `t`. `pos` is the anchor; `blend` = can draw translucency. */
+export function motionFrame(
+ traj: Trajectory,
+ t: number,
+ pos: [number, number],
+ blend = true
+): EffectFrame {
+ const fx = traj.effects;
+ return {
+ glow: fx.glow && blend ? glow(traj, t, pos) : null,
+ trail: fx.trail && blend ? trail(traj, t) : [],
+ magnet: fx.magnet ? magnet(traj, t) : null,
+ ripple: null,
+ squish: 0,
+ };
+}
+
+/** Add the click effects `age` seconds after a click at `point`. */
+export function addClick(
+ frame: EffectFrame,
+ effects: ResolvedEffects,
+ age: number,
+ point: [number, number]
+): void {
+ if (effects.ripple) frame.ripple = ripple(age, point);
+ if (effects.squish) frame.squish = squish(age);
+}
+
+/** When a finished trajectory can be dropped (trail caught up, magnet faded). */
+export function linger(traj: Trajectory): number {
+ let end = traj.duration();
+ if (traj.effects.trail) end += traj.trail.secs;
+ if (traj.effects.magnet && traj.snapT !== null) end = Math.max(end, traj.snapT + MAGNET_SECS);
+ return end;
+}
+
+/** Effect colour: the cursor fill lifted toward white. */
+export function effectRgb(fill: [number, number, number]): [number, number, number] {
+ const lift = (c: number) => Math.round(c + (255 - c) * 0.45);
+ return [lift(fill[0]), lift(fill[1]), lift(fill[2])];
+}
diff --git a/libs/typescript/cursor-motion/src/geom.ts b/libs/typescript/cursor-motion/src/geom.ts
new file mode 100644
index 0000000000..e8a628850e
--- /dev/null
+++ b/libs/typescript/cursor-motion/src/geom.ts
@@ -0,0 +1,56 @@
+/** A point in screen space (points, y down). */
+export interface Pt {
+ x: number;
+ y: number;
+}
+
+/** Target rect `[x, y, width, height]`. */
+export type Rect = [number, number, number, number];
+
+export const pt = (x: number, y: number): Pt => ({ x, y });
+
+export const dist = (a: Pt, b: Pt): number => Math.hypot(b.x - a.x, b.y - a.y);
+export const lerp = (a: number, b: number, t: number): number => a + (b - a) * t;
+export const lerpPt = (a: Pt, b: Pt, t: number): Pt => pt(lerp(a.x, b.x, t), lerp(a.y, b.y, t));
+export const clamp = (v: number, lo: number, hi: number): number => Math.min(Math.max(v, lo), hi);
+
+export function unit(a: Pt, b: Pt): Pt {
+ let d = dist(a, b);
+ if (d === 0) d = 1;
+ return pt((b.x - a.x) / d, (b.y - a.y) / d);
+}
+
+/** 90 degrees counter-clockwise in screen space (y down). */
+export const perp = (u: Pt): Pt => pt(-u.y, u.x);
+
+const TAU = 2 * Math.PI;
+
+/** Wrap an angle into `(-PI, PI]`. */
+export function wrapAngle(a: number): number {
+ let r = a % TAU;
+ if (r > Math.PI) r -= TAU;
+ if (r < -Math.PI) r += TAU;
+ return r;
+}
+
+/**
+ * Distance from the cursor's hotspot (the tip) to its anchor (the body),
+ * along the heading, in points.
+ */
+export const POINTER_ANCHOR_OFFSET = 16;
+
+/** Anchor (body point) that places the hotspot on `(x, y)` at `heading`. */
+export function anchorForPointer(x: number, y: number, heading: number): [number, number] {
+ return [
+ x + Math.cos(heading) * POINTER_ANCHOR_OFFSET,
+ y + Math.sin(heading) * POINTER_ANCHOR_OFFSET,
+ ];
+}
+
+/** Hotspot for an anchor at `heading`. */
+export function pointerForAnchor(x: number, y: number, heading: number): [number, number] {
+ return [
+ x - Math.cos(heading) * POINTER_ANCHOR_OFFSET,
+ y - Math.sin(heading) * POINTER_ANCHOR_OFFSET,
+ ];
+}
diff --git a/libs/typescript/cursor-motion/src/index.ts b/libs/typescript/cursor-motion/src/index.ts
new file mode 100644
index 0000000000..befa51b028
--- /dev/null
+++ b/libs/typescript/cursor-motion/src/index.ts
@@ -0,0 +1,32 @@
+export * from './geom';
+export { Rng, hashString } from './rng';
+export * from './ease';
+export { Path, cuaPath, bowPath, straightPath, naturalSide, type ArcShape } from './path';
+export { planDubins, type PlannedPath, type PathState } from './dubins';
+export * from './style';
+export * from './params';
+export * from './spec';
+export {
+ planMove,
+ planSpec,
+ fittsTimingMs,
+ Trajectory,
+ DT_MS,
+ DEFAULT_TARGET_PT,
+ REST_HEADING,
+ type MoveRequest,
+ type Sample,
+} from './plan';
+import * as effects from './effects';
+export { effects };
+export {
+ DEFAULT_TRAIL,
+ type TrailSpec,
+ type EffectFrame,
+ type TrailSeg,
+ type Glow,
+ type Magnet,
+ type Ripple,
+} from './effects';
+export * from './render';
+export * from './driver';
diff --git a/libs/typescript/cursor-motion/src/params.ts b/libs/typescript/cursor-motion/src/params.ts
new file mode 100644
index 0000000000..16f64e9a55
--- /dev/null
+++ b/libs/typescript/cursor-motion/src/params.ts
@@ -0,0 +1,60 @@
+import {
+ defaultEffects,
+ resolveEffects,
+ type MotionEffects,
+ type MotionStyle,
+ type MotionTiming,
+ type ResolvedEffects,
+} from './style';
+
+/** Knobs of the built-in styles. Defaults match Cua Driver. */
+export interface MotionParams {
+ style: MotionStyle;
+ timing: MotionTiming;
+ effects: MotionEffects;
+ /** Control-point offset from the start, fraction of the distance. [0, 1] */
+ startHandle: number;
+ /** Control-point offset from the end. [0, 1] */
+ endHandle: number;
+ /** Arc scale: 0.25 keeps each style's own arc, 0 is straight. [0, 1] */
+ arcSize: number;
+ /** Shift of the arc's peak: positive = apex near the destination. [-1, 1] */
+ arcFlow: number;
+ /** `classic` arrival spring damping: 1 = critical, 0.3 = bouncy. */
+ spring: number;
+ /** Fixed move time in ms (0 = 1430 for `fixed` timing; > 0 with `native` also fixes it). */
+ glideDurationMs: number;
+ /** `classic` peak speed, pt/s. */
+ peakSpeed: number;
+ /** `classic` speed floor at the start, pt/s. */
+ minStartSpeed: number;
+ /** `classic` speed floor at the end, pt/s. */
+ minEndSpeed: number;
+ /** `classic` minimum turning radius, pt. */
+ turnRadius: number;
+}
+
+export const DEFAULT_PARAMS: Readonly<MotionParams> = Object.freeze({
+ style: 'signature_arc',
+ timing: 'native',
+ effects: {},
+ startHandle: 0.3,
+ endHandle: 0.3,
+ arcSize: 0.25,
+ arcFlow: 0,
+ spring: 0.72,
+ glideDurationMs: 0,
+ peakSpeed: 900,
+ minStartSpeed: 300,
+ minEndSpeed: 200,
+ turnRadius: 80,
+});
+
+export const motionParams = (p: Partial<MotionParams> = {}): MotionParams => ({
+ ...DEFAULT_PARAMS,
+ ...p,
+ effects: { ...(p.effects ?? {}) },
+});
+
+export const resolvedEffects = (p: MotionParams): ResolvedEffects =>
+ resolveEffects(p.effects, defaultEffects(p.style));
diff --git a/libs/typescript/cursor-motion/src/path.ts b/libs/typescript/cursor-motion/src/path.ts
new file mode 100644
index 0000000000..31aaa3ee86
--- /dev/null
+++ b/libs/typescript/cursor-motion/src/path.ts
@@ -0,0 +1,116 @@
+import { dist, lerp, lerpPt, perp, pt, unit, type Pt } from './geom';
+
+/** A parametric path with an arc-length table, so speed curves act on distance. */
+export class Path {
+ readonly length: number;
+ private readonly us: Float64Array;
+ private readonly ss: Float64Array;
+ private readonly p0: Pt;
+ private readonly p1: Pt;
+ private readonly t0: Pt;
+ private readonly t1: Pt;
+
+ constructor(
+ private readonly f: (u: number) => Pt,
+ n: number
+ ) {
+ this.us = new Float64Array(n + 1);
+ this.ss = new Float64Array(n + 1);
+ let prev = f(0);
+ let total = 0;
+ for (let i = 1; i <= n; i++) {
+ const u = i / n;
+ const p = f(u);
+ total += Math.hypot(p.x - prev.x, p.y - prev.y);
+ this.us[i] = u;
+ this.ss[i] = total;
+ prev = p;
+ }
+ this.length = total;
+ this.p0 = f(0);
+ this.p1 = f(1);
+ this.t0 = unit(f(1e-3), this.p0);
+ this.t1 = unit(f(1 - 1e-3), this.p1);
+ }
+
+ /** The point `frac` of the way along by distance; extrapolates past the ends. */
+ atFraction(frac: number): Pt {
+ const len = this.length;
+ if (len < 1e-9) return this.f(Math.min(Math.max(frac, 0), 1));
+ if (frac > 1) {
+ return pt(this.p1.x + this.t1.x * (frac - 1) * len, this.p1.y + this.t1.y * (frac - 1) * len);
+ }
+ if (frac < 0) {
+ return pt(this.p0.x + this.t0.x * -frac * len, this.p0.y + this.t0.y * -frac * len);
+ }
+ const target = frac * len;
+ let lo = 0;
+ let hi = this.ss.length - 1;
+ while (hi - lo > 1) {
+ const mid = (lo + hi) >> 1;
+ if (this.ss[mid]! < target) lo = mid;
+ else hi = mid;
+ }
+ let span = this.ss[hi]! - this.ss[lo]!;
+ if (span === 0) span = 1;
+ return this.f(lerp(this.us[lo]!, this.us[hi]!, (target - this.ss[lo]!) / span));
+ }
+}
+
+const cubic = (p0: Pt, p1: Pt, p2: Pt, p3: Pt) => (u: number) => {
+ const v = 1 - u;
+ const a = v * v * v;
+ const b = 3 * v * v * u;
+ const c = 3 * v * u * u;
+ const d = u * u * u;
+ return pt(a * p0.x + b * p1.x + c * p2.x + d * p3.x, a * p0.y + b * p1.y + c * p2.y + d * p3.y);
+};
+
+const quad = (p0: Pt, p1: Pt, p2: Pt) => (u: number) => {
+ const v = 1 - u;
+ return pt(
+ v * v * p0.x + 2 * v * u * p1.x + u * u * p2.x,
+ v * v * p0.y + 2 * v * u * p1.y + u * u * p2.y
+ );
+};
+
+/** Arc knobs of the Cua bezier. */
+export interface ArcShape {
+ /** First control point's distance from the start, fraction of the chord. [0, 1] */
+ startHandle: number;
+ /** Second control point's distance from the end. [0, 1] */
+ endHandle: number;
+ /** Sideways bend, fraction of the chord; the sign picks the side. */
+ arcSize: number;
+ /** Where the bend peaks: -1 near the start, +1 near the end. */
+ arcFlow: number;
+}
+
+/** The Cua bezier as a path. */
+export function cuaPath(a: Pt, b: Pt, shape: ArcShape): Path {
+ const dx = b.x - a.x;
+ const dy = b.y - a.y;
+ const len = Math.max(Math.hypot(dx, dy), 1);
+ const px = -dy / len;
+ const py = dx / len;
+ const deflection = len * shape.arcSize;
+ const flow = (shape.arcFlow + 1) / 2;
+ const c1d = deflection * (1 - 0.5 * flow);
+ const c2d = deflection * (1 - 0.5 * (1 - flow));
+ const c1 = pt(a.x + dx * shape.startHandle + px * c1d, a.y + dy * shape.startHandle + py * c1d);
+ const c2 = pt(b.x - dx * shape.endHandle + px * c2d, b.y - dy * shape.endHandle + py * c2d);
+ return new Path(cubic(a, c1, c2, b), 256);
+}
+
+/** Gentle single-sided quadratic curve. */
+export function bowPath(a: Pt, b: Pt, amount: number): Path {
+ const d = dist(a, b);
+ const n = perp(unit(a, b));
+ const m = lerpPt(a, b, 0.5);
+ return new Path(quad(a, pt(m.x + n.x * amount * d, m.y + n.y * amount * d), b), 256);
+}
+
+export const straightPath = (a: Pt, b: Pt): Path => new Path((u) => lerpPt(a, b, u), 8);
+
+/** Chord side that bends paths upward for horizontal moves. */
+export const naturalSide = (a: Pt, b: Pt): number => (unit(a, b).x >= 0 ? -1 : 1);
diff --git a/libs/typescript/cursor-motion/src/plan.ts b/libs/typescript/cursor-motion/src/plan.ts
new file mode 100644
index 0000000000..f59e18fb4f
--- /dev/null
+++ b/libs/typescript/cursor-motion/src/plan.ts
@@ -0,0 +1,556 @@
+import { planDubins } from './dubins';
+import { bumpProfile, easeFn, inOutSine, minJerk, wobbleProfile } from './ease';
+import { DEFAULT_TRAIL, type TrailSpec } from './effects';
+import {
+ anchorForPointer,
+ dist,
+ lerp,
+ pointerForAnchor,
+ pt,
+ wrapAngle,
+ type Pt,
+ type Rect,
+} from './geom';
+import { motionParams, resolvedEffects, type MotionParams } from './params';
+import { bowPath, cuaPath, naturalSide, straightPath, type Path } from './path';
+import { Rng } from './rng';
+import { durationMs, specForStyle, type Duration, type Heading, type MotionSpec } from './spec';
+import {
+ DEFAULT_FIXED_MS,
+ NO_EFFECTS,
+ type MotionStyle,
+ type MotionTiming,
+ type ResolvedEffects,
+} from './style';
+
+/** Sample period of every planned trajectory, ms (120 Hz). */
+export const DT_MS = 1000 / 120;
+/** Target box assumed when a move has no element rect. */
+export const DEFAULT_TARGET_PT = 24;
+/** The arrow's rest heading: pointing up and to the left. */
+export const REST_HEADING = Math.PI / 4;
+const ARRIVAL_TOLERANCE_PT = 1;
+const REDUCED_MOTION_MS = 120;
+
+interface Raw {
+ t: number;
+ x: number;
+ y: number;
+}
+
+/** One sample: seconds from the start, the hotspot, and the arrow's heading. */
+export interface Sample {
+ t: number;
+ x: number;
+ y: number;
+ heading: number;
+}
+
+export interface MoveRequest {
+ /** Current hotspot. */
+ from: Pt;
+ /** Requested hotspot. */
+ to: Pt;
+ /** Current heading; defaults to the rest heading. */
+ fromHeading?: number;
+ /** Rest heading on arrival; defaults to pi/4. */
+ endHeading?: number;
+ /** Target element rect, if known. It sets the Fitts width. */
+ target?: Rect | null;
+ /** Same seed, same motion (only `adaptive` draws from it). */
+ seed?: string;
+ /** A short straight glide without effects. */
+ reducedMotion?: boolean;
+}
+
+function sampleTimed(pos: (tau: number) => Pt, ms: number): Raw[] {
+ const c = Math.ceil(ms / DT_MS);
+ const n = Math.max(Number.isFinite(c) && c > 0 ? c : 0, 2);
+ const out: Raw[] = [];
+ for (let i = 0; i <= n; i++) {
+ const tau = i / n;
+ const p = pos(tau);
+ out.push({ t: tau * ms, x: p.x, y: p.y });
+ }
+ return out;
+}
+
+function pinEnds(samples: Raw[], from: Pt, aim: Pt): Raw[] {
+ if (samples.length) {
+ samples[0]!.x = from.x;
+ samples[0]!.y = from.y;
+ samples[samples.length - 1]!.x = aim.x;
+ samples[samples.length - 1]!.y = aim.y;
+ }
+ return samples;
+}
+
+const glide = (from: Pt, aim: Pt, path: Path, profile: (t: number) => number, ms: number) =>
+ pinEnds(
+ sampleTimed((tau) => path.atFraction(profile(tau)), ms),
+ from,
+ aim
+ );
+
+function speedShaped(from: Pt, aim: Pt, path: Path, shape: (s: number) => number, ms: number) {
+ const N = 600;
+ const ts = new Float64Array(N + 1);
+ for (let i = 1; i <= N; i++) ts[i] = ts[i - 1]! + 1 / Math.max(shape((i - 0.5) / N), 1e-3);
+ const total = ts[N]!;
+ return pinEnds(
+ sampleTimed((tau) => {
+ const target = tau * total;
+ let lo = 0;
+ let hi = N;
+ while (hi - lo > 1) {
+ const mid = (lo + hi) >> 1;
+ if (ts[mid]! < target) lo = mid;
+ else hi = mid;
+ }
+ const f = (target - ts[lo]!) / Math.max(ts[hi]! - ts[lo]!, 1e-9);
+ return path.atFraction((lo + f) / N);
+ }, ms),
+ from,
+ aim
+ );
+}
+
+interface Ctx {
+ from: Pt;
+ aim: Pt;
+ target: Rect;
+}
+
+const ctxD = (c: Ctx) => dist(c.from, c.aim);
+const targetWidth = (c: Ctx) => Math.max(Math.min(c.target[2], c.target[3]), 4);
+const side = (c: Ctx) => naturalSide(c.from, c.aim);
+
+/** Global Fitts timing: `150 + 120 log2(D / W + 1)` ms, 300..1000. */
+export function fittsTimingMs(d: number, w: number): number {
+ return Math.min(Math.max(150 + 120 * Math.log2(d / Math.max(w, 4) + 1), 300), 1000);
+}
+
+function generateSpec(spec: MotionSpec, c: Ctx): Raw[] {
+ const s = side(c);
+ const sp = spec.path;
+ const path =
+ sp.type === 'straight'
+ ? straightPath(c.from, c.aim)
+ : sp.type === 'arc'
+ ? cuaPath(c.from, c.aim, { ...sp, arcSize: sp.arcSize * s })
+ : bowPath(c.from, c.aim, sp.amount * s);
+ const ease = easeFn(spec.ease);
+ const ms = durationMs(spec.duration, ctxD(c), targetWidth(c));
+ const st = spec.settle;
+ switch (st.type) {
+ case 'none':
+ return glide(c.from, c.aim, path, ease, ms);
+ case 'follow_through': {
+ const over = Math.min(st.amount, st.maxPt / Math.max(ctxD(c), 1));
+ return glide(c.from, c.aim, path, bumpProfile(ease, over, st.at), ms);
+ }
+ case 'spring': {
+ const amp = Math.min(st.amount, st.maxPt / Math.max(ctxD(c), 1));
+ const glideEnd = st.glideEnd;
+ const profile = wobbleProfile(
+ (t) => ease(Math.min(t / glideEnd, 1)),
+ amp,
+ st.cycles,
+ st.decay,
+ st.start
+ );
+ return glide(c.from, c.aim, path, profile, ms);
+ }
+ }
+}
+
+function magnetic(c: Ctx): [Raw[], number] {
+ const path = bowPath(c.from, c.aim, 0.04 * side(c));
+ const len = path.length;
+ const radius = Math.min(40, len * 0.5);
+ const pull = 0.45;
+ const enterSpeed = 300;
+ const out: Raw[] = [{ t: 0, x: c.from.x, y: c.from.y }];
+ let s = 0;
+ let v = 0;
+ let t = 0;
+ let snap: number | null = null;
+ const dt = DT_MS / 1000;
+ while (s < len && t < 4) {
+ const rem = len - s;
+ if (rem > radius) {
+ v = Math.min(1500, v + 7000 * dt, enterSpeed + 5.5 * (rem - radius));
+ } else {
+ if (snap === null) snap = t * 1000;
+ v += 26000 * pull * (radius / Math.max(rem, 6)) * dt;
+ }
+ s = Math.min(len, s + v * dt);
+ t += dt;
+ const q = path.atFraction(s / len);
+ out.push({ t: t * 1000, x: q.x, y: q.y });
+ }
+ return [pinEnds(out, c.from, c.aim), snap ?? t * 1000];
+}
+
+const plain = (
+ path: MotionSpec['path'],
+ ease: MotionSpec['ease'],
+ duration: Duration
+): MotionSpec => ({
+ path,
+ ease,
+ settle: { type: 'none' },
+ duration,
+ heading: 'tangent',
+ effects: { ...NO_EFFECTS },
+ trail: { ...DEFAULT_TRAIL },
+});
+
+const FITTS_MS: Duration = { type: 'fitts', a: 50, b: 150, minMs: 180, maxMs: 1400, scale: 1 };
+
+const fittsMinjerk = (c: Ctx) =>
+ generateSpec(plain({ type: 'bow', amount: 0.02 }, 'min_jerk', FITTS_MS), c);
+
+function keynoteSwoop(c: Ctx, rng: Rng): Raw[] {
+ const arc = rng.range(0.25, 0.35);
+ return generateSpec(
+ plain(
+ { type: 'arc', startHandle: 0.3, endHandle: 0.3, arcSize: arc, arcFlow: 0.2 },
+ 'in_out_cubic',
+ { type: 'distance', baseMs: 350, msPerPt: 0.35, minMs: 450, maxMs: 1100 }
+ ),
+ c
+ );
+}
+
+function preciseClick(c: Ctx): Raw[] {
+ const fp = 0.15;
+ const fs = 0.35;
+ const shape = (s: number) =>
+ s < 0.4
+ ? 0.04 + Math.sin((Math.PI * s) / 0.8)
+ : s < 1 - fp
+ ? 1 - (1 - fs) * inOutSine((s - 0.4) / (0.6 - fp))
+ : 0.02 + fs * Math.sqrt(Math.max((1 - s) / fp, 0));
+ const path = bowPath(c.from, c.aim, 0.03 * side(c));
+ return speedShaped(
+ c.from,
+ c.aim,
+ path,
+ shape,
+ durationMs(FITTS_MS, ctxD(c), targetWidth(c)) * 1.2
+ );
+}
+
+/** Which generator `adaptive` picks for a move. */
+export function adaptivePick(c: Ctx): 'precise_click' | 'keynote_swoop' | 'fitts_minjerk' {
+ if (targetWidth(c) < 16) return 'precise_click';
+ if (ctxD(c) > 900) return 'keynote_swoop';
+ return 'fitts_minjerk';
+}
+
+function retime(samples: Raw[], targetMs: number) {
+ const total = samples.length ? samples[samples.length - 1]!.t : 0;
+ if (Number.isNaN(total) || total <= 0 || samples.length < 3) return;
+ const k = targetMs / total;
+ for (const s of samples) s.t *= k;
+}
+
+function applyTiming(
+ samples: Raw[],
+ events: number[],
+ c: Ctx,
+ timing: MotionTiming,
+ fixedMs: number
+) {
+ const total = samples.length ? samples[samples.length - 1]!.t : 0;
+ let want: number;
+ if (timing === 'native') return;
+ if (timing === 'fixed') want = fixedMs;
+ else {
+ const last = samples.length ? samples[samples.length - 1]! : c.aim;
+ want = fittsTimingMs(dist(c.from, pt(last.x, last.y)), Math.min(c.target[2], c.target[3]));
+ }
+ if (total > 0) {
+ retime(samples, want);
+ for (let i = 0; i < events.length; i++) events[i] = (events[i]! * want) / total;
+ }
+}
+
+/** A planned move, played back by time. */
+export class Trajectory {
+ constructor(
+ readonly samples: Sample[],
+ /** When the tip first reaches the target (within 1 pt), seconds. */
+ readonly arrivalT: number,
+ /** Magnetic lock-on time, seconds. */
+ readonly snapT: number | null,
+ readonly target: Rect,
+ readonly targetKnown: boolean,
+ readonly effects: ResolvedEffects,
+ readonly trail: TrailSpec,
+ /** The built-in style, or `null` for a custom spec. */
+ readonly style: MotionStyle | null
+ ) {}
+
+ duration(): number {
+ return this.samples.length ? this.samples[this.samples.length - 1]!.t : 0;
+ }
+
+ end(): Sample {
+ return this.samples[this.samples.length - 1]!;
+ }
+
+ /** Interpolated sample at `t` seconds, clamped to the ends. */
+ sampleAt(t: number): Sample {
+ const first = this.samples[0]!;
+ if (t <= first.t) return first;
+ const last = this.end();
+ if (t >= last.t) return last;
+ let lo = 0;
+ let hi = this.samples.length;
+ while (lo < hi) {
+ const mid = (lo + hi) >> 1;
+ if (this.samples[mid]!.t <= t) lo = mid + 1;
+ else hi = mid;
+ }
+ const a = this.samples[lo - 1]!;
+ const b = this.samples[lo]!;
+ const f = (t - a.t) / (b.t - a.t);
+ return {
+ t,
+ x: lerp(a.x, b.x, f),
+ y: lerp(a.y, b.y, f),
+ heading: a.heading + wrapAngle(b.heading - a.heading) * f,
+ };
+ }
+
+ /** Hotspot velocity at `t`, pt/s. */
+ velocityAt(t: number): [number, number] {
+ const h = 0.008;
+ if (t > this.duration() + h) return [0, 0];
+ const a = this.sampleAt(t - h);
+ const b = this.sampleAt(t + h);
+ return [(b.x - a.x) / (2 * h), (b.y - a.y) / (2 * h)];
+ }
+}
+
+const TIP_ANGLE = -0.75 * Math.PI;
+
+interface Resolved {
+ from: Pt;
+ to: Pt;
+ fromHeading: number;
+ endHeading: number;
+ target: Rect;
+ targetKnown: boolean;
+ seed: string;
+}
+
+function resolve(req: MoveRequest): Resolved {
+ const r = req.target;
+ const known = !!r && r.every((v) => Number.isFinite(v)) && r[2] > 0 && r[3] > 0;
+ const h = DEFAULT_TARGET_PT / 2;
+ return {
+ from: req.from,
+ to: req.to,
+ fromHeading: req.fromHeading ?? REST_HEADING,
+ endHeading: req.endHeading ?? REST_HEADING,
+ target: known
+ ? (r as Rect)
+ : [req.to.x - h, req.to.y - h, DEFAULT_TARGET_PT, DEFAULT_TARGET_PT],
+ targetKnown: known,
+ seed: req.seed ?? '',
+ };
+}
+
+function finish(
+ rawIn: Raw[],
+ snapMs: number | null,
+ q: Resolved,
+ effects: ResolvedEffects,
+ trail: TrailSpec,
+ style: MotionStyle | null,
+ mode: Heading
+): Trajectory {
+ const raw = rawIn.length ? rawIn : [{ t: 0, x: q.to.x, y: q.to.y }];
+ const n = raw.length;
+ let rot = wrapAngle(q.fromHeading - q.endHeading);
+ const samples: Sample[] = [];
+ for (let i = 0; i < n; i++) {
+ const a = raw[Math.max(i - 2, 0)]!;
+ const b = raw[Math.min(i + 2, n - 1)]!;
+ const dt = Math.max((b.t - a.t) / 1000, 1e-3);
+ const vx = (b.x - a.x) / dt;
+ const vy = (b.y - a.y) / dt;
+ const speed = Math.hypot(vx, vy);
+ let want = 0;
+ if (mode === 'tangent') {
+ const w = Math.min(Math.max((speed - 40) / 260, 0), 1);
+ want = wrapAngle(Math.atan2(vy, vx) - TIP_ANGLE) * w;
+ }
+ const step = i > 0 ? (raw[i]!.t - raw[i - 1]!.t) / 1000 : 0;
+ const k = 1 - Math.exp(-step * 22);
+ rot += wrapAngle(want - rot) * k;
+ samples.push({ t: raw[i]!.t / 1000, x: raw[i]!.x, y: raw[i]!.y, heading: q.endHeading + rot });
+ }
+ const end = samples[samples.length - 1]!;
+ let t = end.t;
+ const dt = DT_MS / 1000;
+ for (let i = 0; i < 36; i++) {
+ if (Math.abs(rot) < 0.002) break;
+ t += dt;
+ rot -= rot * (1 - Math.exp(-dt * 22));
+ samples.push({ ...end, t, heading: q.endHeading + rot });
+ }
+ samples[samples.length - 1] = { ...samples[samples.length - 1]!, heading: q.endHeading };
+ const hit = samples.find((s) => Math.hypot(s.x - q.to.x, s.y - q.to.y) <= ARRIVAL_TOLERANCE_PT);
+ const arrival = hit ? hit.t : samples[samples.length - 1]!.t;
+ return new Trajectory(
+ samples,
+ arrival,
+ snapMs === null ? null : snapMs / 1000,
+ q.target,
+ q.targetKnown,
+ effects,
+ trail,
+ style
+ );
+}
+
+function reduced(q: Resolved, style: MotionStyle | null): Trajectory {
+ const raw = glide(q.from, q.to, straightPath(q.from, q.to), minJerk, REDUCED_MOTION_MS);
+ return finish(raw, null, q, { ...NO_EFFECTS }, { ...DEFAULT_TRAIL }, style, 'fixed');
+}
+
+/** Plan one move for a built-in style. Unset params take Cua Driver's defaults. */
+export function planMove(params: Partial<MotionParams>, req: MoveRequest): Trajectory {
+ const p = motionParams(params);
+ const q = resolve(req);
+ const c: Ctx = { from: q.from, aim: q.to, target: q.target };
+ const fixedMs = p.glideDurationMs > 0 ? p.glideDurationMs : DEFAULT_FIXED_MS;
+ const timing: MotionTiming = p.timing === 'native' && p.glideDurationMs > 0 ? 'fixed' : p.timing;
+ if (req.reducedMotion) return reduced(q, p.style);
+ if (p.style === 'classic') return planClassic(p, q, timing, fixedMs);
+ const spec = specForStyle(p.style, p);
+ let raw: Raw[];
+ let snap: number | null = null;
+ if (spec) raw = generateSpec(spec, c);
+ else if (p.style === 'magnetic') [raw, snap] = magnetic(c);
+ else {
+ const rng = new Rng(q.seed);
+ const pick = adaptivePick(c);
+ raw =
+ pick === 'precise_click'
+ ? preciseClick(c)
+ : pick === 'keynote_swoop'
+ ? keynoteSwoop(c, rng)
+ : fittsMinjerk(c);
+ }
+ const events = snap === null ? [] : [snap];
+ applyTiming(raw, events, c, timing, fixedMs);
+ return finish(
+ raw,
+ events.length ? events[0]! : null,
+ q,
+ resolvedEffects(p),
+ { ...DEFAULT_TRAIL },
+ p.style,
+ p.style === 'magnetic' ? 'fixed' : 'tangent'
+ );
+}
+
+/** Plan one move for a custom spec. */
+export function planSpec(spec: MotionSpec, req: MoveRequest): Trajectory {
+ const q = resolve(req);
+ if (req.reducedMotion) return reduced(q, null);
+ const raw = generateSpec(spec, { from: q.from, aim: q.to, target: q.target });
+ return finish(raw, null, q, { ...spec.effects }, { ...spec.trail }, null, spec.heading);
+}
+
+function planClassic(
+ p: MotionParams,
+ q: Resolved,
+ timing: MotionTiming,
+ fixedMs: number
+): Trajectory {
+ const K = 400;
+ const OVERSHOOT = 0.8;
+ const springC = (17 * p.spring) / 0.72;
+ const dt = DT_MS / 1000;
+ const [ax, ay] = anchorForPointer(q.from.x, q.from.y, q.fromHeading);
+ const [tx, ty] = anchorForPointer(q.to.x, q.to.y, q.endHeading);
+ const path = planDubins(
+ ax,
+ ay,
+ q.fromHeading + Math.PI,
+ tx,
+ ty,
+ q.endHeading + Math.PI,
+ p.turnRadius
+ );
+ const pathLen = Math.max(path.length, 1);
+ const fixed = timing === 'fixed';
+ const out: Sample[] = [];
+ const push = (t: number, x: number, y: number, heading: number) => {
+ const [px, py] = pointerForAnchor(x, y, heading);
+ out.push({ t, x: px, y: py, heading });
+ };
+ push(0, ax, ay, q.fromHeading);
+ let d = 0;
+ let t = 0;
+ let speed = 0;
+ let guard = 0;
+ while (d < pathLen && guard < 20000) {
+ guard++;
+ const u = Math.min(d / pathLen, 1);
+ const profile = (30 * u * u * (1 - u) * (1 - u)) / 1.875;
+ const floor = u < 0.5 ? p.minStartSpeed : p.minEndSpeed;
+ speed = fixed ? pathLen / (fixedMs / 1000) : floor + (p.peakSpeed - floor) * profile;
+ d += speed * dt;
+ t += dt;
+ if (d >= pathLen) break;
+ const s = path.sample(d);
+ push(t, s.x, s.y, s.heading + Math.PI);
+ }
+ const end = path.sample(pathLen);
+ push(t, tx, ty, q.endHeading);
+ let arrival = t;
+ const impulse = fixed ? p.minEndSpeed : speed;
+ let ox = 0;
+ let oy = 0;
+ let vx = impulse * OVERSHOOT * Math.cos(end.heading);
+ let vy = impulse * OVERSHOOT * Math.sin(end.heading);
+ for (let i = 0; i < 600; i++) {
+ const sdt = dt / 4;
+ for (let j = 0; j < 4; j++) {
+ vx += (-K * ox - springC * vx) * sdt;
+ vy += (-K * oy - springC * vy) * sdt;
+ ox += vx * sdt;
+ oy += vy * sdt;
+ }
+ t += dt;
+ if (Math.hypot(ox, oy) < 0.3 && Math.hypot(vx, vy) < 2) break;
+ push(t, tx + ox, ty + oy, q.endHeading);
+ }
+ push(t + dt, tx, ty, q.endHeading);
+ if (timing === 'fitts') {
+ const total = out[out.length - 1]!.t;
+ if (total > 0) {
+ const want = fittsTimingMs(dist(q.from, q.to), Math.min(q.target[2], q.target[3])) / 1000;
+ const k = want / total;
+ for (const s of out) s.t *= k;
+ arrival *= k;
+ }
+ }
+ return new Trajectory(
+ out,
+ arrival,
+ null,
+ q.target,
+ q.targetKnown,
+ resolvedEffects(p),
+ { ...DEFAULT_TRAIL },
+ 'classic'
+ );
+}
diff --git a/libs/typescript/cursor-motion/src/render.ts b/libs/typescript/cursor-motion/src/render.ts
new file mode 100644
index 0000000000..5f47c67fbd
--- /dev/null
+++ b/libs/typescript/cursor-motion/src/render.ts
@@ -0,0 +1,347 @@
+/**
+ * A small canvas renderer that plays motions with the Cua Driver cursor.
+ *
+ * It draws inside a `<canvas>` only. It never moves, hides or restyles the
+ * page's real mouse pointer.
+ */
+import {
+ addClick,
+ CLICK_FX_SECS,
+ effectRgb,
+ emptyFrame,
+ linger,
+ MAGNET_INFLATE,
+ motionFrame,
+ type EffectFrame,
+} from './effects';
+import { anchorForPointer, type Pt, type Rect } from './geom';
+import type { MotionParams } from './params';
+import { planMove, planSpec, REST_HEADING, type Trajectory } from './plan';
+import type { MotionSpec } from './spec';
+import { NO_EFFECTS, type ResolvedEffects } from './style';
+
+/**
+ * The Cua Driver cursor body (`cursor-overlay/assets/build_default_theme.py`
+ * `CURSOR_PATH`) on its 128-unit canvas, hotspot at (55, 30).
+ */
+export const CURSOR_PATH =
+ 'M55 30 C48 28 42 33 43 41 C43 41 64 98 64 98 C67 106 73 106 77 99 C77 99 86 79 86 79 C88 75 91 72 95 70 C95 70 108 63 108 63 C115 59 114 53 107 50 C107 50 55 30 55 30 Z';
+export const CURSOR_HOTSPOT: Pt = { x: 55, y: 30 };
+const CANVAS_SIZE = 128;
+/** On-screen size of the 128-unit cursor canvas, pt (Cua Driver's `DISPLAY_SIZE`). */
+export const CURSOR_DISPLAY_SIZE = 42;
+/** Cua blue, the default cursor fill. */
+export const CUA_BLUE = '#5ec0e8';
+/** The glow strokes under the body: width (canvas units) and opacity. */
+const GLOW_LAYERS: [number, number][] = [
+ [44, 0.02],
+ [36, 0.024],
+ [29, 0.03],
+ [23, 0.038],
+ [18, 0.048],
+ [14, 0.06],
+ [10, 0.075],
+ [7, 0.095],
+];
+const FLOAT_SECS = 4;
+
+let cursorPath: Path2D | null = null;
+
+function hexRgb(hex: string): [number, number, number] {
+ const h = hex.replace('#', '');
+ const n = parseInt(h.length === 3 ? h.replace(/./g, (c) => c + c) : h, 16);
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
+}
+
+export interface CursorStyle {
+ /** Body fill. Default Cua blue. */
+ fill?: string;
+ /** Scale on top of the 42 pt display size. */
+ scale?: number;
+ /** Click squish, 0..1 of the size. */
+ squish?: number;
+ alpha?: number;
+ /** Seconds into the driver's gentle float (it restarts with each move), or null for none. */
+ floatT?: number | null;
+}
+
+/** Draw the Cua cursor with its tip on `(x, y)`, rotated to `heading` (rest = pi/4). */
+export function drawCursor(
+ g: CanvasRenderingContext2D,
+ x: number,
+ y: number,
+ heading: number,
+ style: CursorStyle = {}
+): void {
+ const fill = style.fill ?? CUA_BLUE;
+ const s = (CURSOR_DISPLAY_SIZE / CANVAS_SIZE) * (style.scale ?? 1) * (1 - (style.squish ?? 0));
+ let fx = 0;
+ let fy = 0;
+ let fr = 0;
+ if (style.floatT != null) {
+ const a = ((style.floatT % FLOAT_SECS) / FLOAT_SECS) * 2 * Math.PI;
+ fx = Math.sin(a) * 5;
+ fy = 6 * Math.cos(a) - 5;
+ fr = ((2.5 * Math.PI) / 180) * Math.cos(a);
+ }
+ cursorPath ??= new Path2D(CURSOR_PATH);
+ g.save();
+ g.globalAlpha = style.alpha ?? 1;
+ g.translate(x + fx * s, y + fy * s);
+ g.rotate(heading - Math.PI / 4 + fr);
+ g.scale(s, s);
+ g.translate(-CURSOR_HOTSPOT.x, -CURSOR_HOTSPOT.y);
+ g.lineCap = 'round';
+ g.lineJoin = 'round';
+ for (const [width, opacity] of GLOW_LAYERS) {
+ g.globalAlpha = (style.alpha ?? 1) * opacity;
+ g.strokeStyle = fill;
+ g.lineWidth = width;
+ g.stroke(cursorPath);
+ }
+ g.globalAlpha = style.alpha ?? 1;
+ g.fillStyle = fill;
+ g.fill(cursorPath);
+ g.strokeStyle = '#ffffff';
+ g.lineWidth = 5;
+ g.stroke(cursorPath);
+ g.restore();
+}
+
+const rgba = (c: [number, number, number], a: number) =>
+ `rgba(${c[0]},${c[1]},${c[2]},${Math.min(Math.max(a, 0), 1)})`;
+
+/** Paint the effects that sit under the cursor: glow, trail, magnet. */
+export function drawEffectsUnder(
+ g: CanvasRenderingContext2D,
+ f: EffectFrame,
+ fill = CUA_BLUE
+): void {
+ const c = effectRgb(hexRgb(fill));
+ if (f.glow) {
+ const grad = g.createRadialGradient(f.glow.x, f.glow.y, 0, f.glow.x, f.glow.y, f.glow.r);
+ grad.addColorStop(0, rgba(c, f.glow.alpha));
+ grad.addColorStop(1, rgba(c, 0));
+ g.fillStyle = grad;
+ g.beginPath();
+ g.arc(f.glow.x, f.glow.y, f.glow.r, 0, 2 * Math.PI);
+ g.fill();
+ }
+ g.lineCap = 'round';
+ for (const seg of f.trail) {
+ g.strokeStyle = rgba(c, seg.alpha);
+ g.lineWidth = seg.width;
+ g.beginPath();
+ g.moveTo(seg.a[0], seg.a[1]);
+ g.lineTo(seg.b[0], seg.b[1]);
+ g.stroke();
+ }
+ if (f.magnet) {
+ const [x, y, w, h] = f.magnet.rect;
+ const i = MAGNET_INFLATE;
+ for (const [width, a] of [
+ [14, 0.1],
+ [8, 0.22],
+ [3, 0.9],
+ ] as const) {
+ g.strokeStyle = rgba(c, a * f.magnet.glow);
+ g.lineWidth = width;
+ g.beginPath();
+ g.roundRect(
+ x - i,
+ y - i,
+ w + 2 * i,
+ h + 2 * i,
+ Math.min(8, (w + 2 * i) / 2, (h + 2 * i) / 2)
+ );
+ g.stroke();
+ }
+ }
+}
+
+/** Paint the click ripple, which sits over the cursor. */
+export function drawEffectsOver(
+ g: CanvasRenderingContext2D,
+ f: EffectFrame,
+ fill = CUA_BLUE
+): void {
+ if (!f.ripple) return;
+ g.strokeStyle = rgba(effectRgb(hexRgb(fill)), f.ripple.alpha);
+ g.lineWidth = f.ripple.width;
+ g.beginPath();
+ g.arc(f.ripple.x, f.ripple.y, f.ripple.r, 0, 2 * Math.PI);
+ g.stroke();
+}
+
+export interface MoveOptions {
+ /** A built-in style and its knobs. */
+ params?: Partial<MotionParams>;
+ /** Or a custom motion. */
+ spec?: MotionSpec;
+ /** Target rect, for Fitts timing and the magnet glow. */
+ target?: Rect | null;
+ /** Click on arrival (ripple and squish when the motion has them). */
+ click?: boolean;
+ reducedMotion?: boolean;
+}
+
+export interface PlayerOptions {
+ fill?: string;
+ /** Called before the cursor each frame, in canvas points; draw your scene here. */
+ drawScene?: (g: CanvasRenderingContext2D, player: MotionPlayer) => void;
+ /** The driver's gentle float. Default true. */
+ float?: boolean;
+}
+
+/**
+ * Plays motions on a canvas. Coordinates are CSS pixels of the canvas.
+ *
+ * ```ts
+ * const player = new MotionPlayer(canvas);
+ * player.place({ x: 80, y: 80 });
+ * await player.moveTo({ x: 600, y: 320 }, { params: { style: 'comet_swoop' }, click: true });
+ * ```
+ */
+export class MotionPlayer {
+ /** Hotspot. */
+ pos: Pt = { x: 0, y: 0 };
+ heading = REST_HEADING;
+ trajectory: Trajectory | null = null;
+ /** Playback speed; 0.25 plays at quarter speed. */
+ timeScale = 1;
+ private motionT = 0;
+ private arrival: (() => void) | null = null;
+ private clickAge: number | null = null;
+ private clickPoint: [number, number] = [0, 0];
+ private clickEffects: ResolvedEffects = { ...NO_EFFECTS };
+ private pendingClick = false;
+ private idleT = 0;
+ private last = 0;
+ private raf = 0;
+ private moves = 0;
+ private readonly g: CanvasRenderingContext2D;
+
+ constructor(
+ readonly canvas: HTMLCanvasElement,
+ readonly options: PlayerOptions = {}
+ ) {
+ const g = canvas.getContext('2d');
+ if (!g) throw new Error('canvas 2d context unavailable');
+ this.g = g;
+ this.raf = requestAnimationFrame(this.frame);
+ }
+
+ /** Put the cursor at rest on `p` without motion. */
+ place(p: Pt): void {
+ const pending = this.arrival;
+ this.arrival = null;
+ pending?.();
+ this.pos = { ...p };
+ this.heading = REST_HEADING;
+ this.trajectory = null;
+ }
+
+ /** Move to `to`; resolves when the tip arrives (any settle keeps playing). */
+ moveTo(to: Pt, opts: MoveOptions = {}): Promise<void> {
+ this.arrival?.();
+ const req = {
+ from: this.pos,
+ fromHeading: this.heading,
+ to,
+ target: opts.target ?? null,
+ seed: `player|${++this.moves}`,
+ reducedMotion: opts.reducedMotion ?? false,
+ };
+ this.trajectory = opts.spec ? planSpec(opts.spec, req) : planMove(opts.params ?? {}, req);
+ this.motionT = 0;
+ this.idleT = 0;
+ this.pendingClick = !!opts.click;
+ return new Promise((resolve) => (this.arrival = resolve));
+ }
+
+ /** Show a click at the current tip. */
+ click(
+ effects: ResolvedEffects = this.trajectory?.effects ?? {
+ ...NO_EFFECTS,
+ ripple: true,
+ squish: true,
+ }
+ ): void {
+ this.clickAge = 0;
+ this.clickPoint = [this.pos.x, this.pos.y];
+ this.clickEffects = effects;
+ }
+
+ destroy(): void {
+ cancelAnimationFrame(this.raf);
+ }
+
+ private frame = (now: number) => {
+ const dt = this.last ? Math.min((now - this.last) / 1000, 0.1) : 0;
+ this.last = now;
+ this.tick(dt * this.timeScale);
+ this.paint();
+ this.raf = requestAnimationFrame(this.frame);
+ };
+
+ private tick(dt: number) {
+ const traj = this.trajectory;
+ if (traj) {
+ this.motionT += dt;
+ const s = traj.sampleAt(this.motionT);
+ this.pos = { x: s.x, y: s.y };
+ this.heading = s.heading;
+ if (this.arrival && this.motionT >= traj.arrivalT) {
+ if (this.pendingClick) {
+ this.pendingClick = false;
+ this.click(traj.effects);
+ }
+ const done = this.arrival;
+ this.arrival = null;
+ done();
+ }
+ if (this.motionT >= linger(traj)) this.trajectory = null;
+ }
+ this.idleT += dt;
+ if (this.clickAge !== null) {
+ this.clickAge += dt;
+ if (this.clickAge >= CLICK_FX_SECS) this.clickAge = null;
+ }
+ }
+
+ /** Effects at the current moment. */
+ effectFrame(): EffectFrame {
+ const frame = this.trajectory
+ ? motionFrame(
+ this.trajectory,
+ this.motionT,
+ anchorForPointer(this.pos.x, this.pos.y, this.heading)
+ )
+ : emptyFrame();
+ if (this.clickAge !== null) addClick(frame, this.clickEffects, this.clickAge, this.clickPoint);
+ return frame;
+ }
+
+ private paint() {
+ const { canvas, g } = this;
+ const dpr = window.devicePixelRatio || 1;
+ const w = canvas.clientWidth;
+ const h = canvas.clientHeight;
+ if (canvas.width !== Math.round(w * dpr) || canvas.height !== Math.round(h * dpr)) {
+ canvas.width = Math.round(w * dpr);
+ canvas.height = Math.round(h * dpr);
+ }
+ g.setTransform(dpr, 0, 0, dpr, 0, 0);
+ g.clearRect(0, 0, w, h);
+ this.options.drawScene?.(g, this);
+ const fill = this.options.fill ?? CUA_BLUE;
+ const f = this.effectFrame();
+ drawEffectsUnder(g, f, fill);
+ drawCursor(g, this.pos.x, this.pos.y, this.heading, {
+ fill,
+ squish: f.squish,
+ floatT: this.options.float === false ? null : this.idleT,
+ });
+ drawEffectsOver(g, f, fill);
+ }
+}
diff --git a/libs/typescript/cursor-motion/src/rng.ts b/libs/typescript/cursor-motion/src/rng.ts
new file mode 100644
index 0000000000..f55ae4fdfa
--- /dev/null
+++ b/libs/typescript/cursor-motion/src/rng.ts
@@ -0,0 +1,29 @@
+/** FNV-1a over UTF-16 code units. */
+export function hashString(text: string): number {
+ let h = 0x811c9dc5;
+ for (let i = 0; i < text.length; i++) {
+ h ^= text.charCodeAt(i);
+ h = Math.imul(h, 0x01000193);
+ }
+ return h >>> 0;
+}
+
+/** mulberry32, bit-identical to the Rust crate and the motion lab. */
+export class Rng {
+ private state: number;
+
+ constructor(seed: string) {
+ this.state = hashString(seed) || 1;
+ }
+
+ next(): number {
+ let t = (this.state = (this.state + 0x6d2b79f5) >>> 0);
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ }
+
+ range(lo: number, hi: number): number {
+ return lo + (hi - lo) * this.next();
+ }
+}
diff --git a/libs/typescript/cursor-motion/src/spec.ts b/libs/typescript/cursor-motion/src/spec.ts
new file mode 100644
index 0000000000..e0983c7b53
--- /dev/null
+++ b/libs/typescript/cursor-motion/src/spec.ts
@@ -0,0 +1,139 @@
+import type { Ease } from './ease';
+import { DEFAULT_TRAIL, type TrailSpec } from './effects';
+import { DEFAULT_PARAMS, motionParams, resolvedEffects, type MotionParams } from './params';
+import type { ArcShape } from './path';
+import type { MotionStyle, ResolvedEffects } from './style';
+
+/** Path shape. A positive arc or bow bends to the natural side (up for horizontal moves). */
+export type PathShape =
+ | { type: 'straight' }
+ | ({ type: 'arc' } & ArcShape)
+ | { type: 'bow'; amount: number };
+
+/** What happens at the end of the glide. */
+export type Settle =
+ | { type: 'none' }
+ /** Push `amount` of the distance (at most `maxPt`) past the target, peaking at `at`, and return. */
+ | { type: 'follow_through'; amount: number; maxPt: number; at: number }
+ /** Reach the target by `glideEnd`, then a damped wobble from `start` on. */
+ | {
+ type: 'spring';
+ amount: number;
+ maxPt: number;
+ cycles: number;
+ decay: number;
+ start: number;
+ glideEnd: number;
+ };
+
+/** How long the move takes. */
+export type Duration =
+ | { type: 'fixed'; ms: number }
+ /** `(a + b log2(D / W + 1)).clamp(minMs, maxMs) * scale`; W = target's smaller side (>= 4). */
+ | { type: 'fitts'; a: number; b: number; minMs: number; maxMs: number; scale: number }
+ /** `(baseMs + msPerPt * D).clamp(minMs, maxMs)`. */
+ | { type: 'distance'; baseMs: number; msPerPt: number; minMs: number; maxMs: number };
+
+/** `tangent`: the tip leads the motion. `fixed`: the arrow keeps its rest pose. */
+export type Heading = 'tangent' | 'fixed';
+
+/** A complete custom motion. */
+export interface MotionSpec {
+ path: PathShape;
+ ease: Ease;
+ settle: Settle;
+ duration: Duration;
+ heading: Heading;
+ effects: ResolvedEffects;
+ trail: TrailSpec;
+}
+
+/** The Fitts model the director's-cut styles share. */
+export const fittsDuration = (scale: number): Duration => ({
+ type: 'fitts',
+ a: 150,
+ b: 120,
+ minMs: 300,
+ maxMs: 1000,
+ scale,
+});
+
+export function durationMs(d: Duration, distance: number, width: number): number {
+ const clamp = (v: number, lo: number, hi: number) => Math.min(Math.max(v, lo), hi);
+ switch (d.type) {
+ case 'fixed':
+ return d.ms;
+ case 'fitts':
+ return (
+ clamp(d.a + d.b * Math.log2(distance / Math.max(width, 4) + 1), d.minMs, d.maxMs) * d.scale
+ );
+ case 'distance':
+ return clamp(d.baseMs + d.msPerPt * distance, d.minMs, d.maxMs);
+ }
+}
+
+/** Scale a style's own arc by the `arcSize` knob and shift its flow by `arcFlow`. */
+export function knobShape(params: MotionParams, arcSize: number, arcFlow: number): ArcShape {
+ return {
+ startHandle: params.startHandle,
+ endHandle: params.endHandle,
+ arcSize: arcSize * (params.arcSize / DEFAULT_PARAMS.arcSize),
+ arcFlow: Math.min(Math.max(arcFlow + params.arcFlow, -1), 1),
+ };
+}
+
+/**
+ * The spec behind a built-in style. `magnetic`, `adaptive` and `classic` are
+ * simulations rather than specs and return `null`.
+ */
+export function specForStyle(
+ style: MotionStyle,
+ params: Partial<MotionParams> = {}
+): MotionSpec | null {
+ const p = motionParams({ ...params, style });
+ const base = (path: PathShape, ease: Ease, settle: Settle, duration: Duration): MotionSpec => ({
+ path,
+ ease,
+ settle,
+ duration,
+ heading: 'tangent',
+ effects: resolvedEffects(p),
+ trail: { ...DEFAULT_TRAIL },
+ });
+ switch (style) {
+ case 'signature_arc':
+ return base(
+ { type: 'arc', ...knobShape(p, 0.16, 0.15) },
+ 'min_jerk',
+ { type: 'follow_through', amount: 0.018, maxPt: 8, at: 0.82 },
+ fittsDuration(1.1)
+ );
+ case 'spring_settle':
+ return base(
+ { type: 'arc', ...knobShape(p, 0.12, 0) },
+ 'min_jerk',
+ {
+ type: 'spring',
+ amount: 0.05,
+ maxPt: 6,
+ cycles: 1.3,
+ decay: 2.6,
+ start: 0.55,
+ glideEnd: 0.68,
+ },
+ fittsDuration(1.35)
+ );
+ case 'comet_swoop':
+ return base(
+ { type: 'arc', ...knobShape(p, 0.24, 0.2) },
+ 'in_out_cubic',
+ { type: 'none' },
+ fittsDuration(1.15)
+ );
+ default:
+ return null;
+ }
+}
+
+/** `signature_arc` as a spec: a good starting point for your own. */
+export const defaultSpec = (): MotionSpec => specForStyle('signature_arc')!;
diff --git a/libs/typescript/cursor-motion/src/style.ts b/libs/typescript/cursor-motion/src/style.ts
new file mode 100644
index 0000000000..d9d64344ea
--- /dev/null
+++ b/libs/typescript/cursor-motion/src/style.ts
@@ -0,0 +1,72 @@
+/** The six built-in styles, as Cua Driver names them. */
+export type MotionStyle =
+ | 'signature_arc'
+ | 'spring_settle'
+ | 'magnetic'
+ | 'comet_swoop'
+ | 'adaptive'
+ | 'classic';
+
+export const MOTION_STYLES: MotionStyle[] = [
+ 'signature_arc',
+ 'spring_settle',
+ 'magnetic',
+ 'comet_swoop',
+ 'adaptive',
+ 'classic',
+];
+
+/** `native` (the style's own), `fitts` or `fixed`. */
+export type MotionTiming = 'native' | 'fitts' | 'fixed';
+export const MOTION_TIMINGS: MotionTiming[] = ['native', 'fitts', 'fixed'];
+
+export type EffectName = 'trail' | 'glow' | 'magnet' | 'ripple' | 'squish';
+export const EFFECT_NAMES: EffectName[] = ['trail', 'glow', 'magnet', 'ripple', 'squish'];
+
+/** Effects that are on or off. */
+export type ResolvedEffects = Record<EffectName, boolean>;
+/** Per-effect overrides; unset or `null` keeps the style's default. */
+export type MotionEffects = Partial<Record<EffectName, boolean | null>>;
+
+export const NO_EFFECTS: ResolvedEffects = {
+ trail: false,
+ glow: false,
+ magnet: false,
+ ripple: false,
+ squish: false,
+};
+
+/** Effects a style turns on when the caller leaves them unset. */
+export function defaultEffects(style: MotionStyle): ResolvedEffects {
+ const on = (...names: EffectName[]): ResolvedEffects => {
+ const out = { ...NO_EFFECTS };
+ for (const n of names) out[n] = true;
+ return out;
+ };
+ switch (style) {
+ case 'signature_arc':
+ return on('glow', 'ripple', 'squish');
+ case 'spring_settle':
+ return on('glow', 'squish');
+ case 'magnetic':
+ return on('magnet', 'ripple');
+ case 'comet_swoop':
+ return on('trail', 'ripple');
+ case 'adaptive':
+ return on('squish');
+ case 'classic':
+ return on();
+ }
+}
+
+export function resolveEffects(overrides: MotionEffects | undefined, base: ResolvedEffects) {
+ const out = { ...base };
+ for (const n of EFFECT_NAMES) {
+ const v = overrides?.[n];
+ if (v !== undefined && v !== null) out[n] = v;
+ }
+ return out;
+}
+
+/** Fixed-timing duration when `glideDurationMs` is 0. */
+export const DEFAULT_FIXED_MS = 1430;
diff --git a/libs/typescript/cursor-motion/tests/api.test.ts b/libs/typescript/cursor-motion/tests/api.test.ts
new file mode 100644
index 0000000000..bddb808b93
--- /dev/null
+++ b/libs/typescript/cursor-motion/tests/api.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from 'vitest';
+import { driverSnippets, planMove, planSpec, specForStyle, MOTION_STYLES } from '../src/index';
+
+describe('api', () => {
+ it('the arc styles are specs', () => {
+ const req = { from: { x: 80, y: 640 }, to: { x: 900, y: 120 } };
+ for (const style of ['signature_arc', 'spring_settle', 'comet_swoop'] as const) {
+ const spec = specForStyle(style, { arcSize: 0.4 })!;
+ expect(planSpec(spec, req).samples).toEqual(planMove({ style, arcSize: 0.4 }, req).samples);
+ }
+ expect(specForStyle('magnetic')).toBeNull();
+ });
+
+ it('every style lands on the target', () => {
+ for (const style of MOTION_STYLES) {
+ const traj = planMove({ style }, { from: { x: 0, y: 0 }, to: { x: 500, y: 300 } });
+ expect(traj.end()).toMatchObject({ x: 500, y: 300 });
+ expect(traj.arrivalT).toBeLessThanOrEqual(traj.duration());
+ }
+ });
+
+ it('exports the Cua Driver equivalent', () => {
+ const s = driverSnippets(
+ { style: 'comet_swoop', timing: 'fitts', arcSize: 0.4, effects: { glow: true } },
+ 'demo'
+ );
+ expect(s.configSet).toEqual([
+ 'cua-driver config set cursor.motion.style comet_swoop',
+ 'cua-driver config set cursor.motion.timing fitts',
+ 'cua-driver config set cursor.motion.effects.glow true',
+ ]);
+ expect(s.cursorMotion).toBe(
+ 'cua-driver cursor motion --session demo --style comet_swoop --timing fitts --effects glow=on'
+ );
+ expect(s.setAgentCursorMotion).toEqual({
+ session: 'demo',
+ style: 'comet_swoop',
+ timing: 'fitts',
+ arc_size: 0.4,
+ effects: { glow: true },
+ });
+ expect(s.callOnly).toEqual(['arc_size']);
+ });
+});
diff --git a/libs/typescript/cursor-motion/tests/golden.test.ts b/libs/typescript/cursor-motion/tests/golden.test.ts
new file mode 100644
index 0000000000..399e805f9b
--- /dev/null
+++ b/libs/typescript/cursor-motion/tests/golden.test.ts
@@ -0,0 +1,151 @@
+// The TypeScript port must reproduce the Rust crate's golden trajectories:
+// libs/cua-driver/rust/crates/cua-cursor-motion/fixtures/golden.json.
+import { readFileSync } from 'node:fs';
+import { describe, expect, it } from 'vitest';
+import {
+ easeFn,
+ effects,
+ hashString,
+ planMove,
+ planSpec,
+ Rng,
+ anchorForPointer,
+ type MotionParams,
+ type MotionSpec,
+ type MoveRequest,
+ type Trajectory,
+} from '../src/index';
+
+const golden = JSON.parse(
+ readFileSync(
+ new URL(
+ '../../../cua-driver/rust/crates/cua-cursor-motion/fixtures/golden.json',
+ import.meta.url
+ ),
+ 'utf8'
+ )
+);
+
+/** Positions and times agree to a micro-point; the fixture rounds to 1e-9. */
+const TOL = 1e-6;
+
+const camel = (k: string) => k.replace(/_([a-z])/g, (_, c: string) => c.toUpperCase());
+function camelKeys(v: unknown): any {
+ if (Array.isArray(v)) return v.map(camelKeys);
+ if (v && typeof v === 'object') {
+ return Object.fromEntries(Object.entries(v).map(([k, x]) => [camel(k), camelKeys(x)]));
+ }
+ return v;
+}
+
+function request(r: any): MoveRequest {
+ return {
+ from: { x: r.from[0], y: r.from[1] },
+ to: { x: r.to[0], y: r.to[1] },
+ fromHeading: r.from_heading,
+ endHeading: r.end_heading,
+ target: r.target,
+ seed: r.seed,
+ reducedMotion: r.reduced_motion,
+ };
+}
+
+let worst = 0;
+function near(path: string, got: number, want: number) {
+ const d = Math.abs(got - want);
+ worst = Math.max(worst, d);
+ if (!(d <= TOL)) throw new Error(`${path}: ${got} vs ${want} (off by ${d})`);
+}
+
+function checkFrame(path: string, got: effects.EffectFrame, want: any) {
+ const list = (v: any, keys: string[]) => (v ? keys.map((k) => v[k]) : null);
+ const pairs: [string, number[] | null, number[] | null][] = [
+ ['glow', list(got.glow, ['x', 'y', 'r', 'alpha']), want.glow],
+ ['magnet', got.magnet ? [...got.magnet.rect, got.magnet.glow] : null, want.magnet],
+ ['ripple', list(got.ripple, ['x', 'y', 'r', 'width', 'alpha']), want.ripple],
+ ];
+ for (const [name, g, w] of pairs) {
+ expect(g === null, `${path}.${name} presence`).toBe(w === null);
+ g?.forEach((v, i) => near(`${path}.${name}[${i}]`, v, w![i]!));
+ }
+ near(`${path}.squish`, got.squish, want.squish);
+ expect(got.trail.length, `${path}.trail length`).toBe(want.trail.length);
+ got.trail.forEach((s, i) =>
+ [s.a[0], s.a[1], s.b[0], s.b[1], s.width, s.alpha].forEach((v, j) =>
+ near(`${path}.trail[${i}][${j}]`, v, want.trail[i][j])
+ )
+ );
+}
+
+function check(name: string, traj: Trajectory, out: any) {
+ expect(traj.samples.length, `${name}: sample count`).toBe(out.samples);
+ near(`${name}.duration`, traj.duration(), out.duration);
+ near(`${name}.arrival`, traj.arrivalT, out.arrival_t);
+ expect(traj.snapT === null, `${name}: snap`).toBe(out.snap_t === null);
+ if (traj.snapT !== null) near(`${name}.snap`, traj.snapT, out.snap_t);
+ traj.target.forEach((v, i) => near(`${name}.target[${i}]`, v, out.target[i]));
+ expect(traj.targetKnown).toBe(out.target_known);
+ expect(traj.effects).toEqual(out.effects);
+ const d = traj.duration();
+ out.grid.forEach((w: number[], i: number) => {
+ const s = traj.sampleAt((d * i) / golden.grid);
+ near(`${name}.grid[${i}].t`, s.t, w[0]!);
+ near(`${name}.grid[${i}].x`, s.x, w[1]!);
+ near(`${name}.grid[${i}].y`, s.y, w[2]!);
+ near(`${name}.grid[${i}].heading`, s.heading, w[3]!);
+ });
+ if (out.frames) {
+ near(`${name}.linger`, effects.linger(traj), out.linger);
+ // Frames at the same fractions of the move as export_golden.rs.
+ out.frames.forEach((f: any, i: number) => {
+ const k = [0.2, 0.5, 0.8, 1.0][i]!;
+ const t = d * k;
+ near(`${name}.frame[${i}].t`, t, f.t);
+ const s = traj.sampleAt(t);
+ const pos = anchorForPointer(s.x, s.y, s.heading);
+ const frame = effects.motionFrame(traj, t, pos, true);
+ effects.addClick(
+ frame,
+ { trail: false, glow: false, magnet: false, ripple: true, squish: true },
+ 0.03 + 0.4 * k,
+ [s.x, s.y]
+ );
+ checkFrame(`${name}@${f.t}`, frame, f.frame);
+ });
+ }
+}
+
+describe('golden trajectories shared with the Rust crate', () => {
+ it('seeded randomness is bit-identical', () => {
+ for (const r of golden.rng) {
+ expect(hashString(r.seed)).toBe(r.hash);
+ const rng = new Rng(r.seed);
+ for (const v of r.values) expect(rng.next()).toBe(v);
+ }
+ });
+
+ it('speed curves match', () => {
+ for (const e of golden.eases) {
+ const ease = camelKeys(e.ease);
+ const f = easeFn(ease);
+ e.values.forEach((v: number, i: number) =>
+ near(`${JSON.stringify(ease)}[${i}]`, f(i / 10), v)
+ );
+ }
+ });
+
+ it(`built-in styles match (${golden.cases.length} cases)`, () => {
+ for (const c of golden.cases) {
+ const params = camelKeys(c.params) as MotionParams;
+ check(c.name, planMove(params, request(c.request)), c.out);
+ }
+ });
+
+ it(`custom specs match (${golden.spec_cases.length} cases)`, () => {
+ for (const c of golden.spec_cases) {
+ const spec = camelKeys(c.spec) as MotionSpec;
+ check(c.name, planSpec(spec, request(c.request)), c.out);
+ }
+ console.log(`worst deviation from Rust: ${worst.toExponential(2)}`);
+ });
+});
diff --git a/libs/typescript/cursor-motion/tests/vendoring.test.ts b/libs/typescript/cursor-motion/tests/vendoring.test.ts
new file mode 100644
index 0000000000..b9f8a16990
--- /dev/null
+++ b/libs/typescript/cursor-motion/tests/vendoring.test.ts
@@ -0,0 +1,52 @@
+// The package is used from the repository, not a registry. Check both
+// documented ways in: copying the built single-file ESM, and vendoring src/.
+import { execFileSync } from 'node:child_process';
+import { cpSync, mkdtempSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+import { expect, it } from 'vitest';
+
+const pkg = fileURLToPath(new URL('..', import.meta.url));
+const bin = (name: string) => join(pkg, 'node_modules/.bin', name);
+const tsc = (dir: string, extra: string[] = []) =>
+ execFileSync(
+ bin('tsc'),
+ [
+ '--noEmit',
+ '--strict',
+ '--target',
+ 'es2022',
+ '--lib',
+ 'es2022,dom',
+ ...extra,
+ join(dir, 'app.ts'),
+ ],
+ { cwd: dir, stdio: 'pipe' }
+ );
+
+const usage = (from: string) => `
+import { planMove, planSpec, specForStyle, MotionPlayer, type Trajectory } from '${from}';
+const t: Trajectory = planMove({ style: 'comet_swoop' }, { from: { x: 0, y: 0 }, to: { x: 600, y: 300 } });
+const s = planSpec(specForStyle('spring_settle')!, { from: { x: 0, y: 0 }, to: { x: 600, y: 300 } });
+export const ok: boolean = t.arrivalT > 0 && s.duration() > 0 && typeof MotionPlayer === 'function';
+`;
+
+it('the built single-file ESM can be copied into a project', async () => {
+ execFileSync(bin('tsdown'), { cwd: pkg, stdio: 'pipe' });
+ const dir = mkdtempSync(join(tmpdir(), 'cua-cursor-motion-'));
+ cpSync(join(pkg, 'dist/index.js'), join(dir, 'cua-cursor-motion.js'));
+ cpSync(join(pkg, 'dist/index.d.ts'), join(dir, 'cua-cursor-motion.d.ts'));
+ writeFileSync(join(dir, 'app.ts'), usage('./cua-cursor-motion.js'));
+ tsc(dir, ['--module', 'nodenext', '--moduleResolution', 'nodenext']);
+ const mod = await import(pathToFileURL(join(dir, 'cua-cursor-motion.js')).href);
+ const traj = mod.planMove({ style: 'magnetic' }, { from: { x: 0, y: 0 }, to: { x: 400, y: 0 } });
+ expect(traj.end()).toMatchObject({ x: 400, y: 0 });
+}, 60_000);
+
+it('src/ can be vendored into a bundler project', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'cua-cursor-motion-src-'));
+ cpSync(join(pkg, 'src'), join(dir, 'cua-cursor-motion'), { recursive: true });
+ writeFileSync(join(dir, 'app.ts'), usage('./cua-cursor-motion'));
+ tsc(dir, ['--module', 'esnext', '--moduleResolution', 'bundler']);
+}, 60_000);
diff --git a/libs/typescript/cursor-motion/tsconfig.json b/libs/typescript/cursor-motion/tsconfig.json
new file mode 100644
index 0000000000..01d4d5605a
--- /dev/null
+++ b/libs/typescript/cursor-motion/tsconfig.json
@@ -0,0 +1,20 @@
+{
+ "compilerOptions": {
+ "target": "es2022",
+ "lib": ["es2023", "dom"],
+ "moduleDetection": "force",
+ "module": "preserve",
+ "moduleResolution": "bundler",
+ "resolveJsonModule": true,
+ "types": ["node"],
+ "strict": true,
+ "noUncheckedIndexedAccess": true,
+ "noUnusedLocals": true,
+ "declaration": true,
+ "emitDeclarationOnly": true,
+ "isolatedModules": true,
+ "verbatimModuleSyntax": true,
+ "skipLibCheck": true
+ },
+ "include": ["src", "tests"]
+}
diff --git a/libs/typescript/cursor-motion/tsdown.config.ts b/libs/typescript/cursor-motion/tsdown.config.ts
new file mode 100644
index 0000000000..bdc240ae74
--- /dev/null
+++ b/libs/typescript/cursor-motion/tsdown.config.ts
@@ -0,0 +1,10 @@
+import { defineConfig } from 'tsdown';
+
+// One self-contained ESM file (dist/index.js) plus its types (dist/index.d.ts),
+// so the build can be copied into any project straight from the repository.
+// Types are emitted in a second pass: bundling them in the same pass splits a
+// shared runtime helper into its own chunk.
+export default defineConfig([
+ { entry: ['./src/index.ts'], platform: 'neutral', dts: false },
+ { entry: ['./src/index.ts'], platform: 'neutral', dts: { emitDtsOnly: true }, clean: false },
+]);
diff --git a/libs/typescript/cursor-motion/vitest.config.ts b/libs/typescript/cursor-motion/vitest.config.ts
new file mode 100644
index 0000000000..94ede10e22
--- /dev/null
+++ b/libs/typescript/cursor-motion/vitest.config.ts
@@ -0,0 +1,3 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({});
diff --git a/libs/typescript/pnpm-lock.yaml b/libs/typescript/pnpm-lock.yaml
index 967e8db4bc..ae0aa4da92 100644
--- a/libs/typescript/pnpm-lock.yaml
+++ b/libs/typescript/pnpm-lock.yaml
@@ -102,6 +102,24 @@ importers:
specifier: 4.1.0
+ cursor-motion:
+ devDependencies:
+ '@types/node':
+ specifier: ^22.15.17
+ version: 22.19.8
+ tsdown:
+ specifier: ^0.11.9
+ version: 0.11.13([email protected])
+ typescript:
+ specifier: ^5.8.3
+ version: 5.9.3
+ vite:
+ specifier: 7.3.5
+ vitest:
+ specifier: 4.1.0
+
fleet:
dependencies:
'@ubjs/core':
diff --git a/libs/typescript/pnpm-workspace.yaml b/libs/typescript/pnpm-workspace.yaml
index 0d1d961017..ca809f3727 100644
--- a/libs/typescript/pnpm-workspace.yaml
+++ b/libs/typescript/pnpm-workspace.yaml
@@ -3,5 +3,6 @@ packages:
- "agent"
- "fleet"
- "playground"
+ - "cursor-motion"
minimumReleaseAge: 46080