@n-uf/motion 26.12.4 → 26.12.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/dist/browser.d.ts +1 -1
- package/dist/browser.js +2 -2
- package/dist/browser.js.map +1 -1
- package/dist/{chunk-I4TKJWCD.js → chunk-ELRGR2MI.js} +3 -3
- package/dist/{chunk-I4TKJWCD.js.map → chunk-ELRGR2MI.js.map} +1 -1
- package/dist/{chunk-MTSGXDVI.js → chunk-GLPO4HGL.js} +19 -1
- package/dist/chunk-GLPO4HGL.js.map +1 -0
- package/dist/{chunk-OOKRBVMB.js → chunk-LSIMILAL.js} +1 -1
- package/dist/chunk-LSIMILAL.js.map +1 -0
- package/dist/{chunk-BCFPSDOQ.js → chunk-LUFRN56Q.js} +1 -1
- package/dist/chunk-LUFRN56Q.js.map +1 -0
- package/dist/{chunk-QZJLWSPO.js → chunk-PIQEUBJE.js} +34 -3
- package/dist/chunk-PIQEUBJE.js.map +1 -0
- package/dist/{chunk-XKCRMQZQ.js → chunk-QZG3DQZ7.js} +1 -1
- package/dist/{chunk-XKCRMQZQ.js.map → chunk-QZG3DQZ7.js.map} +1 -1
- package/dist/{chunk-GDV76P2H.js → chunk-R4AHR32W.js} +4 -2
- package/dist/chunk-R4AHR32W.js.map +1 -0
- package/dist/clock.js +1 -1
- package/dist/drag.js +1 -1
- package/dist/gestures.d.ts +2 -1
- package/dist/gestures.js +2 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.js +7 -7
- package/dist/layout.d.ts +2 -2
- package/dist/layout.js +2 -2
- package/dist/{motion--ql49201.d.ts → motion-CREdoi-4.d.ts} +48 -6
- package/dist/signals.js +1 -1
- package/dist/values.js +3 -3
- package/package.json +1 -1
- package/dist/chunk-BCFPSDOQ.js.map +0 -1
- package/dist/chunk-GDV76P2H.js.map +0 -1
- package/dist/chunk-MTSGXDVI.js.map +0 -1
- package/dist/chunk-OOKRBVMB.js.map +0 -1
- package/dist/chunk-QZJLWSPO.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/clock/fake-clock.ts","../src/clock/frame-loop.ts","../src/clock/coalescer.ts"],"sourcesContent":["import type { ClockPort } from \"./port\";\n\n/** Options of {@link createFakeClock}. */\nexport interface FakeClockOptions {\n /** Starting time in ms. Default 0. */\n readonly now?: number;\n /** How far {@link FakeClock.frame} moves time by default. Default 16 (round numbers in tests). */\n readonly frameInterval?: number;\n}\n\n/**\n * A clock that only moves when a test moves it. Timers fire in time order\n * (ties in the order they were set), each with `now()` at its due time.\n * Frame callbacks run on {@link FakeClock.frame}; a callback requested during\n * a frame waits for the next one, as with requestAnimationFrame.\n */\nexport interface FakeClock extends ClockPort {\n /** The default frame step in ms. */\n readonly frameInterval: number;\n /** Frame callbacks waiting for the next frame. */\n readonly pendingFrames: number;\n /** Timers not yet fired. */\n readonly pendingTimers: number;\n /** Move time forward by `ms`, firing the timers that come due on the way. */\n tick(ms: number): void;\n /** Move `now()` forward by `ms` without firing anything: work that takes time. */\n spend(ms: number): void;\n /**\n * Move time forward by `dt` (default {@link FakeClock.frameInterval}), fire due\n * timers, then run the frame callbacks requested before this call. Returns\n * how many callbacks ran.\n */\n frame(dt?: number): number;\n /** Run `count` frames; returns how many callbacks ran in all. */\n frames(count: number, dt?: number): number;\n /**\n * Run frames until none is requested; returns how many frames ran. Throws\n * after `maxFrames` (default 1000): something keeps asking for frames.\n */\n runUntilIdle(options?: { readonly maxFrames?: number; readonly dt?: number }): number;\n}\n\ninterface Timer {\n readonly at: number;\n readonly order: number;\n readonly callback: () => void;\n}\n\n/** A {@link FakeClock} for tests. */\nexport function createFakeClock(options: FakeClockOptions = {}): FakeClock {\n let now = options.now ?? 0;\n const frameInterval = options.frameInterval ?? 16;\n let nextHandle = 1;\n let order = 0;\n let frameCallbacks = new Map<number, () => void>();\n const timers = new Map<number, Timer>();\n\n const checkStep = (ms: number, what: string): void => {\n if (!Number.isFinite(ms) || ms < 0) throw new RangeError(`fake clock: ${what} needs a finite ms >= 0, got ${ms}`);\n };\n\n const fireDue = (until: number): void => {\n for (;;) {\n let dueHandle = -1;\n let due: Timer | null = null;\n for (const [handle, timer] of timers) {\n if (timer.at > until) continue;\n if (due === null || timer.at < due.at || (timer.at === due.at && timer.order < due.order)) {\n due = timer;\n dueHandle = handle;\n }\n }\n if (due === null) return;\n timers.delete(dueHandle);\n if (due.at > now) now = due.at;\n due.callback();\n }\n };\n\n const clock: FakeClock = {\n frameInterval,\n get pendingFrames() {\n return frameCallbacks.size;\n },\n get pendingTimers() {\n return timers.size;\n },\n now: () => now,\n requestFrame(callback) {\n const handle = nextHandle++;\n frameCallbacks.set(handle, callback);\n return handle;\n },\n cancelFrame(handle) {\n frameCallbacks.delete(handle);\n },\n setTimer(callback, ms) {\n const handle = nextHandle++;\n timers.set(handle, { at: now + Math.max(0, ms), order: order++, callback });\n return handle;\n },\n clearTimer(handle) {\n timers.delete(handle);\n },\n tick(ms) {\n checkStep(ms, \"tick\");\n const until = now + ms;\n fireDue(until);\n if (until > now) now = until;\n },\n spend(ms) {\n checkStep(ms, \"spend\");\n now += ms;\n },\n frame(dt = frameInterval) {\n clock.tick(dt);\n const due = frameCallbacks;\n frameCallbacks = new Map();\n for (const callback of due.values()) callback();\n return due.size;\n },\n frames(count, dt) {\n let ran = 0;\n for (let i = 0; i < count; i++) ran += clock.frame(dt);\n return ran;\n },\n runUntilIdle({ maxFrames = 1000, dt } = {}) {\n let frames = 0;\n while (frameCallbacks.size > 0) {\n if (frames >= maxFrames) {\n throw new Error(`fake clock: still requesting frames after ${maxFrames} frames`);\n }\n clock.frame(dt);\n frames++;\n }\n return frames;\n },\n };\n return clock;\n}\n","import type { ClockPort, FrameSource } from \"./port\";\n\n/**\n * The phases of a frame, in the order they run:\n * - `input`: coalesced pointer, wheel and key samples are delivered;\n * - `update`: state changes (a gesture machine's intent, an engine transaction);\n * - `layout`: derived geometry, then motion values step toward their targets;\n * - `write`: the host writes the results out (transforms, canvas, DOM).\n */\nexport type Phase = \"input\" | \"update\" | \"layout\" | \"write\";\n\n/** {@link Phase} in run order. */\nexport const PHASES: readonly Phase[] = [\"input\", \"update\", \"layout\", \"write\"];\n\nconst PHASE_INDEX: Readonly<Record<Phase, number>> = { input: 0, update: 1, layout: 2, write: 3 };\n\n/** What a task sees of the frame it runs in. */\nexport interface FrameInfo {\n /** `clock.now()` when the frame started. */\n readonly time: number;\n /**\n * Ms since the previous frame, clamped to `maxDelta`. The first frame\n * after the loop was idle gets `frameInterval`, not the idle gap.\n */\n readonly delta: number;\n /** Frame counter, from 0. */\n readonly index: number;\n /** The phase running now. */\n readonly phase: Phase;\n /** The loop's frame budget in ms. */\n readonly budget: number;\n /** Ms spent in this frame so far. */\n elapsed(): number;\n /** Ms of budget left in this frame (negative when over). */\n remaining(): number;\n}\n\n/** A one-shot task. */\nexport type FrameTask = (frame: FrameInfo) => void;\n\n/** A task that runs every frame; it stops when it returns `false`. */\nexport type RepeatingTask = (frame: FrameInfo) => boolean | void;\n\n/** Options of {@link FrameLoop.schedule}. */\nexport interface ScheduleOptions {\n /**\n * May wait for a later frame when this frame is over budget. Default\n * `false`: the task runs this frame whatever the cost. Repeating tasks\n * always run.\n */\n readonly deferrable?: boolean;\n}\n\n/** Counters of a frame loop since it was created or last reset. */\nexport interface FrameStats {\n /** Frames run. */\n readonly frames: number;\n /** Frames that took longer than the budget. */\n readonly overBudget: number;\n /** Deferrable tasks moved to a later frame because the budget was spent. */\n readonly deferred: number;\n /** Tasks that threw. */\n readonly errors: number;\n /** Duration of the last frame in ms. */\n readonly lastFrame: number;\n /** Longest frame in ms. */\n readonly longestFrame: number;\n /** Mean frame duration in ms. */\n readonly meanFrame: number;\n /** Duration of each phase in the last frame, in ms. */\n readonly perPhase: Readonly<Record<Phase, number>>;\n /** Repeating tasks currently registered. */\n readonly repeating: number;\n /** One-shot tasks waiting for a frame. */\n readonly queued: number;\n}\n\n/** Options of {@link createFrameLoop}. */\nexport interface FrameLoopOptions {\n /** The clock: frames, time and timers all come from it. */\n readonly clock: ClockPort;\n /** Frame budget in ms. Default 10. */\n readonly budget?: number;\n /** `delta` of the first frame after the loop was idle. Default 1000/60. */\n readonly frameInterval?: number;\n /** Largest `delta` handed to tasks (a long pause doesn't make motion jump). Default 64. */\n readonly maxDelta?: number;\n /**\n * How many times one phase drains tasks that were queued for that same\n * phase while it ran (an effect that triggers another effect). The rest\n * waits for the next frame. Default 8.\n */\n readonly maxRounds?: number;\n /**\n * Called when a task throws; the frame carries on. Without it, the first\n * error of a frame is rethrown once the frame is done (and the next frame\n * is already requested). A repeating task that throws is stopped.\n */\n readonly onError?: (error: unknown, phase: Phase) => void;\n /** Called after a frame that took longer than the budget. */\n readonly onOverBudget?: (stats: FrameStats) => void;\n}\n\n/**\n * One frame loop. It requests a frame only while it has work, runs the\n * phases in order, and goes idle (no frame requested) when nothing is left.\n */\nexport interface FrameLoop {\n /** The clock the loop runs on. */\n readonly clock: ClockPort;\n /** The frame budget in ms. */\n readonly budget: number;\n /** Whether a frame is requested or running. */\n readonly active: boolean;\n /** The phase running now, or `null` outside a frame. */\n readonly phase: Phase | null;\n /**\n * Frames this loop has finished since it was created: a frame counts once\n * all four phases have run. {@link FrameLoop.resetStats} leaves it, so two\n * readings tell whether a frame ended between them.\n */\n readonly framesEnded: number;\n /**\n * Run `task` once in `phase`: in this frame if that phase is still ahead,\n * otherwise in the next one. Scheduling the same function again before it\n * runs does nothing. Returns a cancel function.\n */\n schedule(phase: Phase, task: FrameTask, options?: ScheduleOptions): () => void;\n /** Run `task` in `phase` every frame until it returns `false` or the returned stop is called. */\n repeat(phase: Phase, task: RepeatingTask): () => void;\n /**\n * A scheduler for `effect(fn, { schedule })`: the effect runs in `phase`,\n * at most once per frame. The same function is returned for a phase each time.\n */\n scheduler(phase: Phase): (run: () => void) => void;\n /** A {@link FrameSource} whose frames are this loop's `phase`, for a coalescer. */\n frames(phase: Phase): FrameSource;\n /** Counters since creation or the last {@link FrameLoop.resetStats}. */\n stats(): FrameStats;\n /** Zero the counters. */\n resetStats(): void;\n /** Cancel the requested frame and drop every task. The loop does nothing after this. */\n dispose(): void;\n}\n\ninterface Job {\n readonly task: FrameTask;\n readonly deferrable: boolean;\n cancelled: boolean;\n}\n\ninterface Repeater {\n readonly task: RepeatingTask;\n alive: boolean;\n}\n\n/** Create a frame loop on `options.clock`. */\nexport function createFrameLoop(options: FrameLoopOptions): FrameLoop {\n const clock = options.clock;\n const budget = options.budget ?? 10;\n const frameInterval = options.frameInterval ?? 1000 / 60;\n const maxDelta = options.maxDelta ?? 64;\n const maxRounds = options.maxRounds ?? 8;\n const onError = options.onError;\n const onOverBudget = options.onOverBudget;\n\n const queues: Map<FrameTask, Job>[] = [new Map(), new Map(), new Map(), new Map()];\n const carried: Job[][] = [[], [], [], []];\n const repeaters: Repeater[][] = [[], [], [], []];\n const schedulers: ((run: () => void) => void)[] = [];\n let liveRepeaters = 0;\n let handle: number | null = null;\n let running = false;\n let current = -1;\n let lastTime: number | null = null;\n let index = 0;\n let frameStart = 0;\n let disposed = false;\n let frameError: { error: unknown } | null = null;\n let framesEnded = 0;\n\n let frameCount = 0;\n let overBudget = 0;\n let deferred = 0;\n let errors = 0;\n let lastFrame = 0;\n let longestFrame = 0;\n let totalTime = 0;\n const perPhase = [0, 0, 0, 0];\n\n const queuedCount = (): number => {\n let count = 0;\n for (let p = 0; p < 4; p++) count += queues[p]!.size + carried[p]!.length;\n return count;\n };\n\n const hasWork = (): boolean => liveRepeaters > 0 || queuedCount() > 0;\n\n const request = (): void => {\n if (handle !== null || running || disposed) return;\n handle = clock.requestFrame(runFrame);\n };\n\n /** Drop a requested frame that has nothing left to do. */\n const releaseIfIdle = (): void => {\n if (running || handle === null || hasWork()) return;\n clock.cancelFrame(handle);\n handle = null;\n lastTime = null;\n };\n\n const report = (error: unknown, phase: number): void => {\n errors++;\n if (onError !== undefined) {\n onError(error, PHASES[phase]!);\n } else if (frameError === null) {\n frameError = { error };\n }\n };\n\n const drain = (phase: number, info: FrameInfo): void => {\n const queue = queues[phase]!;\n for (let round = 0; queue.size > 0 && round < maxRounds; round++) {\n const jobs = Array.from(queue.values());\n queue.clear();\n for (let i = 0; i < jobs.length; i++) {\n const job = jobs[i]!;\n if (job.cancelled) continue;\n if (job.deferrable && clock.now() - frameStart >= budget) {\n carried[phase]!.push(job);\n deferred++;\n continue;\n }\n try {\n job.task(info);\n } catch (error) {\n report(error, phase);\n }\n }\n }\n };\n\n const runRepeaters = (phase: number, info: FrameInfo): void => {\n const list = repeaters[phase]!;\n // New repeaters pushed during the pass run in this pass too.\n for (let i = 0; i < list.length; i++) {\n const repeater = list[i]!;\n if (!repeater.alive) continue;\n let keep: boolean | void;\n try {\n keep = repeater.task(info);\n } catch (error) {\n report(error, phase);\n keep = false;\n }\n if (keep === false && repeater.alive) {\n repeater.alive = false;\n liveRepeaters--;\n }\n }\n let kept = 0;\n for (let i = 0; i < list.length; i++) {\n const repeater = list[i]!;\n if (repeater.alive) list[kept++] = repeater;\n }\n list.length = kept;\n };\n\n /** Put deferred jobs back at the front of their queues for the next frame. */\n const restoreCarried = (): void => {\n for (let p = 0; p < 4; p++) {\n const jobs = carried[p]!;\n if (jobs.length === 0) continue;\n const queue = queues[p]!;\n const later = Array.from(queue.values());\n queue.clear();\n for (const job of jobs) if (!job.cancelled) queue.set(job.task, job);\n for (const job of later) if (!queue.has(job.task)) queue.set(job.task, job);\n jobs.length = 0;\n }\n };\n\n function runFrame(): void {\n handle = null;\n if (disposed) return;\n const time = clock.now();\n const delta = lastTime === null ? frameInterval : Math.min(Math.max(time - lastTime, 0), maxDelta);\n lastTime = time;\n frameStart = time;\n const info = {\n time,\n delta,\n index: index++,\n phase: PHASES[0]!,\n budget,\n elapsed: (): number => clock.now() - frameStart,\n remaining: (): number => budget - (clock.now() - frameStart),\n };\n running = true;\n try {\n for (let p = 0; p < 4; p++) {\n current = p;\n info.phase = PHASES[p]!;\n const phaseStart = clock.now();\n drain(p, info);\n runRepeaters(p, info);\n drain(p, info);\n perPhase[p] = clock.now() - phaseStart;\n }\n } finally {\n running = false;\n current = -1;\n }\n restoreCarried();\n const took = clock.now() - frameStart;\n framesEnded++;\n frameCount++;\n lastFrame = took;\n totalTime += took;\n if (took > longestFrame) longestFrame = took;\n if (took > budget) {\n overBudget++;\n if (onOverBudget !== undefined) onOverBudget(stats());\n }\n if (hasWork()) request();\n else lastTime = null;\n if (frameError !== null) {\n const { error } = frameError;\n frameError = null;\n throw error;\n }\n }\n\n const stats = (): FrameStats => ({\n frames: frameCount,\n overBudget,\n deferred,\n errors,\n lastFrame,\n longestFrame,\n meanFrame: frameCount === 0 ? 0 : totalTime / frameCount,\n perPhase: { input: perPhase[0]!, update: perPhase[1]!, layout: perPhase[2]!, write: perPhase[3]! },\n repeating: liveRepeaters,\n queued: queuedCount(),\n });\n\n const schedule = (phase: Phase, task: FrameTask, scheduleOptions?: ScheduleOptions): (() => void) => {\n if (disposed) return () => {};\n const queue = queues[PHASE_INDEX[phase]]!;\n let job = queue.get(task);\n if (job === undefined) {\n job = { task, deferrable: scheduleOptions?.deferrable ?? false, cancelled: false };\n queue.set(task, job);\n request();\n }\n const scheduled = job;\n return () => {\n if (scheduled.cancelled) return;\n scheduled.cancelled = true;\n if (queue.get(task) === scheduled) queue.delete(task);\n releaseIfIdle();\n };\n };\n\n const loop: FrameLoop = {\n clock,\n budget,\n get active() {\n return running || handle !== null;\n },\n get phase() {\n return current < 0 ? null : PHASES[current]!;\n },\n get framesEnded() {\n return framesEnded;\n },\n schedule,\n repeat(phase, task) {\n if (disposed) return () => {};\n const repeater: Repeater = { task, alive: true };\n repeaters[PHASE_INDEX[phase]]!.push(repeater);\n liveRepeaters++;\n request();\n return () => {\n if (!repeater.alive) return;\n repeater.alive = false;\n liveRepeaters--;\n releaseIfIdle();\n };\n },\n scheduler(phase) {\n const p = PHASE_INDEX[phase];\n let made = schedulers[p];\n if (made === undefined) {\n made = (run) => {\n schedule(phase, run);\n };\n schedulers[p] = made;\n }\n return made;\n },\n frames(phase) {\n let next = 1;\n const pending = new Map<number, () => void>();\n return {\n requestFrame(callback) {\n const id = next++;\n const task = (): void => {\n pending.delete(id);\n callback();\n };\n pending.set(id, schedule(phase, task));\n return id;\n },\n cancelFrame(id) {\n const cancel = pending.get(id);\n if (cancel === undefined) return;\n pending.delete(id);\n cancel();\n },\n };\n },\n stats,\n resetStats() {\n frameCount = 0;\n overBudget = 0;\n deferred = 0;\n errors = 0;\n lastFrame = 0;\n longestFrame = 0;\n totalTime = 0;\n perPhase.fill(0);\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n if (handle !== null) clock.cancelFrame(handle);\n handle = null;\n for (let p = 0; p < 4; p++) {\n queues[p]!.clear();\n carried[p]!.length = 0;\n for (const repeater of repeaters[p]!) repeater.alive = false;\n repeaters[p]!.length = 0;\n }\n liveRepeaters = 0;\n },\n };\n return loop;\n}\n","import type { FrameSource } from \"./port\";\n\n/** Options of {@link createFrameCoalescer}. */\nexport interface CoalescerOptions<T> {\n /**\n * How a new sample folds into the pending one. Default: keep the latest\n * (pointer positions). Wheel deltas want a sum instead.\n */\n readonly merge?: (pending: T, next: T) => T;\n}\n\n/**\n * Collapses a burst of samples into at most one delivery per frame. Same\n * shape as hypr-tiling's `createFrameCoalescer` (`schedule`, `cancel`),\n * plus `flush` and `pending`.\n */\nexport interface FrameCoalescer<T> {\n /** Record a sample and make sure a frame is requested. */\n schedule(sample: T): void;\n /**\n * Deliver the pending sample now, if there is one (before a pointer-up, so\n * the last move is seen first). Returns whether it delivered.\n */\n flush(): boolean;\n /** Drop the pending sample and the requested frame. Nothing is delivered after this. */\n cancel(): void;\n /** Whether a sample is waiting for its frame. */\n readonly pending: boolean;\n}\n\n/**\n * Deliver samples to `onFrame` once per frame of `frames`: the browser clock,\n * the fake clock, or a frame loop phase (`loop.frames(\"input\")`). `onFrame`\n * also gets how many samples were folded into this one.\n */\nexport function createFrameCoalescer<T>(\n onFrame: (sample: T, count: number) => void,\n frames: FrameSource,\n options: CoalescerOptions<T> = {},\n): FrameCoalescer<T> {\n const merge = options.merge;\n let handle: number | null = null;\n let sample: T | undefined;\n let count = 0;\n\n const deliver = (): void => {\n const delivered = sample as T;\n const folded = count;\n sample = undefined;\n count = 0;\n onFrame(delivered, folded);\n };\n\n const onFrameDue = (): void => {\n handle = null;\n if (count > 0) deliver();\n };\n\n return {\n schedule(next) {\n sample = count > 0 && merge !== undefined ? merge(sample as T, next) : next;\n count++;\n if (handle === null) handle = frames.requestFrame(onFrameDue);\n },\n flush() {\n if (handle !== null) {\n frames.cancelFrame(handle);\n handle = null;\n }\n if (count === 0) return false;\n deliver();\n return true;\n },\n cancel() {\n if (handle !== null) {\n frames.cancelFrame(handle);\n handle = null;\n }\n sample = undefined;\n count = 0;\n },\n get pending() {\n return count > 0;\n },\n };\n}\n"],"mappings":";AAiDO,SAAS,gBAAgB,UAA4B,CAAC,GAAc;AACzE,MAAI,MAAM,QAAQ,OAAO;AACzB,QAAM,gBAAgB,QAAQ,iBAAiB;AAC/C,MAAI,aAAa;AACjB,MAAI,QAAQ;AACZ,MAAI,iBAAiB,oBAAI,IAAwB;AACjD,QAAM,SAAS,oBAAI,IAAmB;AAEtC,QAAM,YAAY,CAAC,IAAY,SAAuB;AACpD,QAAI,CAAC,OAAO,SAAS,EAAE,KAAK,KAAK,EAAG,OAAM,IAAI,WAAW,eAAe,IAAI,gCAAgC,EAAE,EAAE;AAAA,EAClH;AAEA,QAAM,UAAU,CAAC,UAAwB;AACvC,eAAS;AACP,UAAI,YAAY;AAChB,UAAI,MAAoB;AACxB,iBAAW,CAAC,QAAQ,KAAK,KAAK,QAAQ;AACpC,YAAI,MAAM,KAAK,MAAO;AACtB,YAAI,QAAQ,QAAQ,MAAM,KAAK,IAAI,MAAO,MAAM,OAAO,IAAI,MAAM,MAAM,QAAQ,IAAI,OAAQ;AACzF,gBAAM;AACN,sBAAY;AAAA,QACd;AAAA,MACF;AACA,UAAI,QAAQ,K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AI;AACvE;AACA,UAAI,WAAW,KAAM,UAAS,OAAO,aAAa,UAAU;AAAA,IAC9D;AAAA,IACA,QAAQ;AACN,UAAI,WAAW,MAAM;AACnB,eAAO,YAAY,MAAM;AACzB,iBAAS;AAAA,MACX;AACA,UAAI,UAAU,EAAG,QAAO;AACxB,cAAQ;AACR,aAAO;AAAA,IACT;AAAA,IACA,SAAS;AACP,UAAI,WAAW,MAAM;AACnB,eAAO,YAAY,MAAM;AACzB,iBAAS;AAAA,MACX;AACA,eAAS;AACT,cAAQ;AAAA,IACV;AAAA,IACA,IAAI,UAAU;AACZ,aAAO,QAAQ;AAAA,IACjB;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/gestures/types.ts","../src/gestures/modifiers.ts","../src/gestures/wheel.ts","../src/gestures/recognizer.ts","../src/gestures/machine.ts","../src/gestures/dwell.ts","../src/gestures/touch-press.ts","../src/gestures/release-velocity.ts","../src/gestures/paged-swipe.ts"],"sourcesContent":["/**\n * Input types: plain event objects in, one gesture stream out. Nothing here\n * touches the DOM; the host copies the fields it needs out of PointerEvent /\n * WheelEvent / Safari's GestureEvent.\n *\n * Hit testing and routing (what is under a point, who gets a gesture) stay\n * with the host.\n */\n\nimport type { Modifiers } from \"../keys\";\nimport type { Point } from \"../shapes\";\n\nexport type { ModifierKey, Modifiers } from \"../keys\";\n\nexport type PointerKind = \"mouse\" | \"pen\" | \"touch\";\n\n/** \"mac\": the drag modifier defaults to Cmd; \"other\": Alt (the OS keeps the Win/Super key) */\nexport type Platform = \"mac\" | \"other\";\n\nexport const NO_MODIFIERS: Readonly<Modifiers> = Object.freeze({ shift: false, alt: false, meta: false, ctrl: false });\n\n/**\n * A pointer as the gesture stream reports it (screen, canvas, kind, buttons,\n * modifiers) plus the fields a recognizer needs: which pointer, which button\n * changed, when.\n */\nexport interface GesturePointer {\n screen: Point; // CSS px relative to the host's view\n canvas: Point; // the host's world units, through its camera at the time of the event (RecognizerOptions.toCanvas; else `screen`)\n kind: PointerKind;\n buttons: number; // PointerEvent.buttons bit mask\n modifiers: Modifiers;\n pointerId: number;\n /** PointerEvent.button: 0 primary, 1 middle, 2 secondary (a pen's barrel button), 5 eraser; -1 none changed */\n button: number;\n time: number; // event timeStamp, ms\n pressure?: number;\n}\n\n// ----------------------------------------------------------------------------\n// Raw events (copied out of DOM events by the host)\n// ----------------------------------------------------------------------------\n\nexport type RawPointerType = \"pointerdown\" | \"pointermove\" | \"pointerup\" | \"pointercancel\" | \"lostpointercapture\";\n\nexport interface RawPointerEvent {\n type: RawPointerType;\n pointerId: number;\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents -- `PointerKind | string` documents the known kinds next to the open string; changing it would change the published types\n pointerType: PointerKind | string; // unknown types are treated as mouse\n isPrimary?: boolean;\n button: number;\n buttons: number;\n screen: Point; // clientX/Y minus the view's origin\n modifiers?: Partial<Modifiers>;\n time: number;\n pressure?: number;\n /**\n * lostpointercapture only: whose capture was lost. \"content\" (an element inside the view's content, e.g.\n * right after the host took the pointer for a modifier-drag) leaves the gesture alone; default \"view\".\n */\n lostBy?: \"view\" | \"content\";\n}\n\nexport interface RawWheelEvent {\n type: \"wheel\";\n deltaX: number;\n deltaY: number;\n /** 0 pixels, 1 lines, 2 pages */\n deltaMode: 0 | 1 | 2;\n screen: Point;\n modifiers?: Partial<Modifiers>;\n time: number;\n}\n\n/** Safari's trackpad pinch (GestureEvent): scale is relative to the gesture's start */\nexport interface RawSafariGestureEvent {\n type: \"gesturestart\" | \"gesturechange\" | \"gestureend\";\n scale: number;\n screen: Point;\n modifiers?: Partial<Modifiers>;\n time: number;\n}\n\nexport type RawInputEvent = RawPointerEvent | RawWheelEvent | RawSafariGestureEvent;\n\n// ----------------------------------------------------------------------------\n// The gesture stream\n// ----------------------------------------------------------------------------\n\nexport type CancelReason =\n | \"pointercancel\" // the browser or OS took the pointer (scroll, system gesture, palm rejection)\n | \"lostcapture\" // pointer capture lost before the pointer went up\n | \"multitouch\" // a second finger turned the press into a pinch\n | \"missed-up\" // its pointerup never came (the same pointer pressed again, or another went down long after)\n | \"escape\"\n | \"reset\" // the view lost focus, the tool changed, the host was disposed\n | (string & {});\n\ninterface PointerGestureBase {\n pointer: GesturePointer;\n /** The press that started this gesture */\n origin: GesturePointer;\n}\n\nexport type InputGesture =\n /** A pointer went down (one per gesture; a second touch becomes a pinch instead) */\n | { type: \"press\"; pointer: GesturePointer }\n /**\n * The pointer travelled past the click threshold. What a drag means (a modifier-drag that moves or resizes, say) is\n * the host's: it reads `origin.button` and the keys held (`isHeld(pointer.modifiers, key)`).\n */\n | (PointerGestureBase & { type: \"dragStart\" })\n /** A move after dragStart (moves inside the threshold are not reported) */\n | (PointerGestureBase & { type: \"move\" })\n /** Held still past the long-press delay (touch and pen by default); at most once per press */\n | (PointerGestureBase & { type: \"longPress\" })\n /**\n * The pointer went up. click: it never crossed the threshold and no long press fired;\n * clickCount counts quick clicks at the same spot (2 = double click).\n */\n | (PointerGestureBase & { type: \"release\"; click: boolean; clickCount: number; dragged: boolean })\n | (PointerGestureBase & { type: \"cancel\"; reason: CancelReason; dragged: boolean })\n /** A pointer moving with no press (mouse and pen hover): cursor and chrome hover */\n | { type: \"hover\"; pointer: GesturePointer }\n /**\n * Two fingers (touch) or a trackpad pinch. scale is the change since the last update (multiply it in);\n * pan is the center's screen-px change since the last update. kind is what was recognized first.\n */\n | {\n type: \"pinch\";\n phase: \"start\" | \"update\" | \"end\" | \"cancel\";\n source: \"touch\" | \"trackpad\";\n kind: \"pinch\" | \"pan\";\n center: { screen: Point; canvas: Point };\n scale: number;\n pan: Point;\n modifiers: Modifiers;\n time: number;\n }\n /** A wheel or trackpad scroll that is not a pinch: delta in screen px (lines and pages converted) */\n | { type: \"scroll\"; delta: Point; at: { screen: Point; canvas: Point }; modifiers: Modifiers; time: number }\n /**\n * Zoom by a factor around a point: Cmd/Ctrl+wheel, a trackpad pinch reported as ctrl+wheel\n * (Chrome, Firefox, Edge). Safari's trackpad pinch comes as \"pinch\" with source \"trackpad\".\n */\n | { type: \"zoom\"; factor: number; at: { screen: Point; canvas: Point }; modifiers: Modifiers; time: number };\n\nexport type InputGestureType = InputGesture[\"type\"];\n","/**\n * Modifier keys: event modifiers to one shape, and the drag modifier\n * resolved per platform (Cmd on macOS, Alt elsewhere; null turns it off).\n */\n\nimport { NO_MODIFIERS, type ModifierKey, type Modifiers, type Platform, type PointerKind } from \"./types\";\n\nexport function toModifiers(m: Partial<Modifiers> | undefined): Modifiers {\n if (!m) return { ...NO_MODIFIERS };\n return { shift: !!m.shift, alt: !!m.alt, meta: !!m.meta, ctrl: !!m.ctrl };\n}\n\n/** The default drag modifier: \"meta\" (Cmd) on macOS, \"alt\" elsewhere */\nexport function defaultDragModifier(platform: Platform): ModifierKey {\n return platform === \"mac\" ? \"meta\" : \"alt\";\n}\n\n/**\n * A configured drag modifier as used: undefined → the platform default, null → off.\n */\nexport function resolveDragModifier(config: ModifierKey | null | undefined, platform: Platform): ModifierKey | null {\n if (config === null) return null;\n return config ?? defaultDragModifier(platform);\n}\n\nexport { isHeld } from \"../keys\";\n\n/**\n * The button a press stands for on this platform. On macOS a Ctrl+click is the secondary click (the system's own\n * rule; the browser's contextmenu follows it), so a primary mouse press with Ctrl held is button 2 there, as a\n * right-click is. Not when Ctrl is the drag modifier (`\"ctrl\"`, or `\"mod\"`, which Ctrl holds: Ctrl+drag then moves).\n * A pen, a finger and the other platforms keep their button.\n */\nexport function platformButton(press: { kind: PointerKind; button: number; modifiers: Modifiers }, platform: Platform, dragModifier: ModifierKey | null): number {\n const ctrlDrags = dragModifier === \"ctrl\" || dragModifier === \"mod\";\n return platform === \"mac\" && press.kind === \"mouse\" && press.button === 0 && press.modifiers.ctrl && !ctrlDrags ? 2 : press.button;\n}\n\n/**\n * The platform's own Mod key: Cmd on macOS, Ctrl elsewhere (Mod+wheel zooms, Mod+click is content's multi-select).\n * Where the platform is unknown, `isHeld(modifiers, \"mod\")` counts either key.\n */\nexport function modHeld(modifiers: Modifiers, platform: Platform): boolean {\n return platform === \"mac\" ? modifiers.meta : modifiers.ctrl;\n}\n","/**\n * Wheel normalisation (Figma / tldraw style): lines and pages to pixels;\n * Cmd/Ctrl+wheel and the trackpad pinch (ctrl+wheel in Chrome, Firefox, Edge)\n * zoom by 2^(−dy / sensitivity); any other wheel scrolls, Shift turns\n * vertical into horizontal.\n */\n\nimport type { Point } from \"../shapes\";\nimport type { Modifiers } from \"./types\";\n\nexport interface WheelOptions {\n /** px per line (deltaMode 1); default 40 */\n lineHeight: number;\n /** px per page (deltaMode 2); default 800 */\n pageHeight: number;\n /** zoom factor = 2^(−deltaY / sensitivity); default 300 */\n zoomSensitivity: number;\n}\n\nexport const WHEEL_DEFAULTS: Readonly<WheelOptions> = Object.freeze({ lineHeight: 40, pageHeight: 800, zoomSensitivity: 300 });\n\n/** A wheel event's delta in px: pixels as given, lines and pages by `lineHeight` and `pageHeight`. */\nexport function wheelDelta(deltaX: number, deltaY: number, deltaMode: 0 | 1 | 2, opts: WheelOptions = WHEEL_DEFAULTS): Point {\n const k = deltaMode === 1 ? opts.lineHeight : deltaMode === 2 ? opts.pageHeight : 1;\n return { x: finite(deltaX) * k, y: finite(deltaY) * k };\n}\n\nexport type WheelIntent = { kind: \"zoom\"; factor: number } | { kind: \"scroll\"; delta: Point };\n\n/**\n * What a wheel event means. Ctrl or Meta held: zoom (a trackpad pinch arrives as ctrl+wheel).\n * Otherwise scroll; with Shift a vertical-only delta scrolls horizontally (mice without a\n * horizontal wheel).\n */\nexport function classifyWheel(delta: Point, modifiers: Modifiers, opts: WheelOptions = WHEEL_DEFAULTS): WheelIntent {\n if (modifiers.ctrl || modifiers.meta) {\n const factor = Math.pow(2, -delta.y / (opts.zoomSensitivity > 0 ? opts.zoomSensitivity : WHEEL_DEFAULTS.zoomSensitivity));\n return { kind: \"zoom\", factor: Number.isFinite(factor) && factor > 0 ? factor : 1 };\n }\n if (modifiers.shift && delta.x === 0) return { kind: \"scroll\", delta: { x: delta.y, y: 0 } };\n return { kind: \"scroll\", delta };\n}\n\n/** Wheel pan damping for a camera that pans on scroll */\nexport interface WheelPanOptions {\n /** Multiplier on the wheel's px; default 0.65 */\n speed: number;\n /** Linear up to this many px per event; default 30 */\n threshold: number;\n /** Hard cap per event, px; default 60 */\n max: number;\n}\n\nexport const WHEEL_PAN_DEFAULTS: Readonly<WheelPanOptions> = Object.freeze({ speed: 0.65, threshold: 30, max: 60 });\n\n/**\n * The camera pan for one wheel scroll, per axis: speed × delta, linear up to the threshold, then\n * square-root damped (threshold + √(4 × excess)) and capped, so a fast flick of a free-spinning wheel or an\n * accelerated trackpad doesn't throw the canvas away.\n */\nexport function dampWheelPan(delta: Point, opts: WheelPanOptions = WHEEL_PAN_DEFAULTS): Point {\n const one = (d: number) => {\n const v = finite(d) * opts.speed;\n const abs = Math.abs(v);\n if (abs <= opts.threshold) return v;\n return Math.sign(v) * Math.min(opts.threshold + Math.sqrt((abs - opts.threshold) * 4), opts.max);\n };\n return { x: one(delta.x), y: one(delta.y) };\n}\n\nfunction finite(v: number): number {\n return Number.isFinite(v) ? v : 0;\n}\n","/**\n * The gesture recognizer: raw pointer, wheel and Safari gesture events (plain\n * objects) in, one stream of InputGesture out. Mouse, pen and touch share one\n * path; two fingers become a pinch (5 % scale or 10 px pan decides which, read\n * once both fingers have moved, so a pan's leading finger is no pinch); a\n * press becomes a drag only past a per-kind threshold, so a modifier+click\n * (Cmd/Ctrl+click to multi-select) stays a click for the content.\n *\n * One press at a time: a second mouse or pen while one is down is ignored, and\n * a second finger cancels the one-finger press (\"multitouch\") and starts a\n * pinch. After a pinch, the fingers left on the glass start nothing until all\n * are lifted.\n *\n * No DOM, no clock: timestamps come with the events and the long-press timer\n * is injected as the timer half of a ClockPort (without timers there is no\n * long press). The stale-press drop works from event timestamps, so it needs\n * no timer.\n */\n\nimport type { ClockPort } from \"../clock/port\";\nimport { DOUBLE_CLICK } from \"../double-click\";\nimport type { Point } from \"../shapes\";\nimport { platformButton, toModifiers } from \"./modifiers\";\nimport type {\n CancelReason,\n InputGesture,\n ModifierKey,\n Platform,\n PointerKind,\n RawInputEvent,\n RawPointerEvent,\n RawSafariGestureEvent,\n RawWheelEvent,\n GesturePointer,\n} from \"./types\";\nimport { classifyWheel, WHEEL_DEFAULTS, wheelDelta, type WheelOptions } from \"./wheel\";\n\n/** The timer half of a ClockPort: any clock (createBrowserClock, createFakeClock) is one. */\nexport type RecognizerTimers = Pick<ClockPort, \"setTimer\" | \"clearTimer\">;\n\nexport interface RecognizerOptions {\n /** Screen px (relative to the view) to canvas units, through the current camera; default: the same point (no camera) */\n toCanvas?: (screen: Point) => Point;\n /** For the long press: a clock; without timers no long press fires */\n timers?: RecognizerTimers;\n /**\n * The host's drag modifier, resolved (see resolveDragModifier); null = off. The recognizer reads it only for the\n * platform's secondary click: on macOS a Ctrl+press stays the primary button when Ctrl is the drag modifier\n * (platformButton). What a drag with it held does is the host's.\n */\n dragModifier?: ModifierKey | null;\n /** \"mac\": a mouse Ctrl+press is the secondary button, as the system has it (platformButton); default \"other\" */\n platform?: Platform;\n /** Click vs drag: a press becomes a drag after travelling more than this many screen px */\n thresholds?: Partial<Record<PointerKind, number>>;\n longPress?: { ms?: number; kinds?: readonly PointerKind[] };\n /** Two clicks within ms and px of each other count as a double click (default `DOUBLE_CLICK`: 500 ms, 5 px) */\n multiClick?: { ms?: number; px?: number };\n pinch?: { scaleThreshold?: number; panThreshold?: number };\n wheel?: Partial<WheelOptions>;\n /** A mouse or pen press, or a resting finger outside any gesture, untouched this long when another pointer goes down, lost its pointerup; default 1000 ms */\n stale?: number;\n}\n\nexport const RECOGNIZER_DEFAULTS = Object.freeze({\n thresholds: Object.freeze({ mouse: 4, pen: 6, touch: 8 }) as Readonly<Record<PointerKind, number>>,\n longPress: Object.freeze({ ms: 500, kinds: Object.freeze([\"touch\", \"pen\"]) as readonly PointerKind[] }),\n // The package's one double click (`DOUBLE_CLICK`, shared with a grip's double-activate).\n multiClick: DOUBLE_CLICK,\n pinch: Object.freeze({ scaleThreshold: 0.05, panThreshold: 10 }),\n});\n\nexport interface Recognizer {\n feed(event: RawInputEvent): void;\n /** Cancel the press and the pinch in flight (Escape, a tool change, the view losing focus) */\n cancel(reason: CancelReason): void;\n /** cancel(\"reset\") and forget every pointer (e.g. after the window lost focus mid-touch) */\n reset(): void;\n /** The press in flight, if any */\n active(): { pointerId: number; kind: PointerKind; dragging: boolean } | null;\n pinching(): boolean;\n /** Change the drag modifier; applies from the next press */\n setDragModifier(key: ModifierKey | null): void;\n dispose(): void;\n}\n\ninterface Press {\n origin: GesturePointer;\n last: GesturePointer;\n dragging: boolean;\n longPressed: boolean;\n timer: number | undefined;\n}\n\ninterface Touch {\n screen: Point;\n time: number;\n}\n\ninterface Pinch {\n ids: [number, number];\n startDist: number;\n startCenter: Point;\n lastDist: number;\n lastCenter: Point;\n kind: \"pinch\" | \"pan\" | null;\n /** While undecided: each finger's moves (position changes) since the last look at the kind */\n reported: Map<number, number>;\n}\n\n/**\n * While two fingers are undecided, the kind is looked at once both have moved as often as each other since the last\n * look: one finger's events arrive before the other's (one or a burst), and a pan's leading finger alone changes the\n * distance like a pinch. A finger at rest sends no moves, so a finger this many moves ahead of the other is looked at\n * on its own (a pinch around an anchored thumb).\n */\nconst SOLO_MOVES = 3;\n\nfunction kindOf(pointerType: string): PointerKind {\n return pointerType === \"touch\" || pointerType === \"pen\" ? pointerType : \"mouse\";\n}\n\nfunction dist(a: Point, b: Point): number {\n return Math.hypot(a.x - b.x, a.y - b.y);\n}\n\nfunction mid(a: Point, b: Point): Point {\n return { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };\n}\n\nfunction finitePoint(p: Point): Point {\n return { x: Number.isFinite(p.x) ? p.x : 0, y: Number.isFinite(p.y) ? p.y : 0 };\n}\n\nexport function createRecognizer(options: RecognizerOptions, emit: (gesture: InputGesture) => void): Recognizer {\n const thresholds = { ...RECOGNIZER_DEFAULTS.thresholds, ...options.thresholds };\n const longPressMs = options.longPress?.ms ?? RECOGNIZER_DEFAULTS.longPress.ms;\n const longPressKinds = options.longPress?.kinds ?? RECOGNIZER_DEFAULTS.longPress.kinds;\n const multiClick = { ...RECOGNIZER_DEFAULTS.multiClick, ...options.multiClick };\n const pinchCfg = { ...RECOGNIZER_DEFAULTS.pinch, ...options.pinch };\n const wheelCfg: WheelOptions = { ...WHEEL_DEFAULTS, ...options.wheel };\n const timers = options.timers;\n const stale = options.stale ?? 1000;\n let dragModifier: ModifierKey | null = options.dragModifier ?? null;\n const platform: Platform = options.platform ?? \"other\";\n // A host with no camera: canvas units are screen px.\n const toCanvas = options.toCanvas ?? ((p: Point): Point => ({ x: p.x, y: p.y }));\n\n let press: Press | null = null;\n let pinch: Pinch | null = null;\n const touches = new Map<number, Touch>();\n /** After a pinch (or a reset mid-touch), fingers still down start nothing until all are up */\n let touchLocked = false;\n let lastClick: { time: number; screen: Point; button: number; count: number } | null = null;\n let safari: { last: number } | null = null;\n let lastTime = 0;\n let disposed = false;\n\n const pointerOf = (e: RawPointerEvent): GesturePointer => {\n const screen = finitePoint(e.screen);\n return {\n screen,\n canvas: toCanvas(screen),\n kind: kindOf(e.pointerType),\n buttons: e.buttons,\n modifiers: toModifiers(e.modifiers),\n pointerId: e.pointerId,\n button: e.button,\n time: e.time,\n ...(e.pressure !== undefined ? { pressure: e.pressure } : {}),\n };\n };\n\n const clearTimer = (p: Press) => {\n if (p.timer !== undefined && timers) timers.clearTimer(p.timer);\n p.timer = undefined;\n };\n\n const endPress = (): Press | null => {\n const p = press;\n if (p) clearTimer(p);\n press = null;\n return p;\n };\n\n const cancelPress = (reason: CancelReason, pointer?: GesturePointer) => {\n const p = endPress();\n if (!p) return;\n emit({ type: \"cancel\", pointer: pointer ?? p.last, origin: p.origin, reason, dragged: p.dragging });\n };\n\n const releasePress = (pointer: GesturePointer) => {\n const p = endPress();\n if (!p) return;\n const click = !p.dragging && !p.longPressed;\n let clickCount = 0;\n if (click) {\n const prev = lastClick;\n const repeat =\n !!prev &&\n prev.button === p.origin.button &&\n p.origin.time - prev.time <= multiClick.ms &&\n dist(prev.screen, p.origin.screen) <= multiClick.px;\n clickCount = repeat ? prev!.count + 1 : 1;\n lastClick = { time: pointer.time, screen: p.origin.screen, button: p.origin.button, count: clickCount };\n } else {\n lastClick = null;\n }\n emit({ type: \"release\", pointer, origin: p.origin, click, clickCount, dragged: p.dragging });\n };\n\n const pinchState = (): { center: Point; d: number } | null => {\n if (!pinch) return null;\n const a = touches.get(pinch.ids[0]);\n const b = touches.get(pinch.ids[1]);\n if (!a || !b) return null;\n return { center: mid(a.screen, b.screen), d: Math.max(1, dist(a.screen, b.screen)) };\n };\n\n const pinchEvent = (\n phase: \"start\" | \"update\" | \"end\" | \"cancel\",\n center: Point,\n scale: number,\n pan: Point,\n time: number,\n modifiers: GesturePointer[\"modifiers\"],\n source: \"touch\" | \"trackpad\",\n kind: \"pinch\" | \"pan\",\n ): InputGesture => ({\n type: \"pinch\",\n phase,\n source,\n kind,\n center: { screen: center, canvas: toCanvas(center) },\n scale,\n pan,\n modifiers,\n time,\n });\n\n const endPinch = (phase: \"end\" | \"cancel\", time: number, modifiers: GesturePointer[\"modifiers\"]) => {\n const p = pinch;\n pinch = null;\n touchLocked = touches.size > 0;\n if (p && p.kind) emit(pinchEvent(phase, p.lastCenter, 1, { x: 0, y: 0 }, time, modifiers, \"touch\", p.kind));\n };\n\n /**\n * A pinch finger moved (`id`), or lifts (`lifting`: the last look, whatever moved). The kind is decided on both\n * fingers' latest positions (see SOLO_MOVES); the thresholds keep their meaning.\n */\n const updatePinch = (id: number, time: number, modifiers: GesturePointer[\"modifiers\"], moved: boolean, lifting = false) => {\n const p = pinch;\n const now = pinchState();\n if (!p || !now) return;\n if (!p.kind) {\n if (!moved && !lifting) return; // a move that changed nothing (pressure only) is no move\n const moves = (p.reported.get(id) ?? 0) + (moved ? 1 : 0);\n p.reported.set(id, moves);\n const other = p.reported.get(p.ids[0] === id ? p.ids[1] : p.ids[0]) ?? 0;\n const even = moves > 0 && moves === other;\n if (!lifting && !even && Math.abs(moves - other) < SOLO_MOVES) return;\n p.reported.clear();\n const scaleChange = Math.abs(now.d / p.startDist - 1);\n const panDist = dist(now.center, p.startCenter);\n if (scaleChange > pinchCfg.scaleThreshold) p.kind = \"pinch\";\n else if (panDist > pinchCfg.panThreshold) p.kind = \"pan\";\n else return;\n // The first event carries everything since the second finger landed, so nothing is lost.\n const scale = p.kind === \"pinch\" ? now.d / p.startDist : 1;\n const pan = { x: now.center.x - p.startCenter.x, y: now.center.y - p.startCenter.y };\n p.lastDist = now.d;\n p.lastCenter = now.center;\n emit(pinchEvent(\"start\", now.center, scale, pan, time, modifiers, \"touch\", p.kind));\n return;\n }\n const scale = p.kind === \"pinch\" ? now.d / p.lastDist : 1;\n const pan = { x: now.center.x - p.lastCenter.x, y: now.center.y - p.lastCenter.y };\n p.lastDist = now.d;\n p.lastCenter = now.center;\n if (scale === 1 && pan.x === 0 && pan.y === 0) return;\n emit(pinchEvent(\"update\", now.center, scale, pan, time, modifiers, \"touch\", p.kind));\n };\n\n /**\n * A pointerup that never came (released outside the page, a pen lifted out of range, a lost event):\n * a press of the same pointer, or a mouse / pen press untouched for `stale` ms, is over. A finger that\n * lands again under its old id, or one resting untouched for `stale` ms outside any press or pinch, is gone.\n */\n const dropMissedUps = (e: RawPointerEvent, kind: PointerKind) => {\n const p = press;\n if (p) {\n const same = p.origin.pointerId === e.pointerId;\n const mixed = kind !== \"touch\" || p.origin.kind !== \"touch\"; // two fingers make a pinch, never a stale press\n if (same || (mixed && e.time - p.last.time > stale)) cancelPress(\"missed-up\");\n }\n if (kind !== \"touch\") return;\n if (touches.has(e.pointerId)) {\n if (pinch?.ids.includes(e.pointerId)) endPinch(\"cancel\", e.time, toModifiers(e.modifiers));\n touches.delete(e.pointerId);\n }\n for (const [id, t] of touches) {\n const busy = press?.origin.pointerId === id || !!pinch?.ids.includes(id);\n if (!busy && e.time - t.time > stale) touches.delete(id);\n }\n if (touches.size === 0) touchLocked = false;\n };\n\n const onDown = (e: RawPointerEvent) => {\n const down = pointerOf(e);\n // The press's button as the platform means it (macOS: Ctrl+click is a secondary click)\n const pointer: GesturePointer = { ...down, button: platformButton(down, platform, dragModifier) };\n dropMissedUps(e, pointer.kind);\n if (pointer.kind === \"touch\") {\n touches.set(e.pointerId, { screen: pointer.screen, time: pointer.time });\n if (touchLocked || pinch) return; // a third finger, or fingers after a pinch\n if (touches.size === 2) {\n const ids = [...touches.keys()] as [number, number];\n // The second finger: whatever the first one started is cancelled, a pinch may begin.\n if (press && press.origin.kind === \"touch\") cancelPress(\"multitouch\");\n else if (press) {\n touches.delete(e.pointerId); // a mouse or pen press owns the input; ignore the finger\n return;\n }\n const a = touches.get(ids[0])!;\n const b = touches.get(ids[1])!;\n const d = Math.max(1, dist(a.screen, b.screen));\n const c = mid(a.screen, b.screen);\n pinch = { ids, startDist: d, startCenter: c, lastDist: d, lastCenter: c, kind: null, reported: new Map() };\n return;\n }\n if (touches.size > 2) return;\n }\n if (press || pinch) return; // one press at a time\n const p: Press = {\n origin: pointer,\n last: pointer,\n dragging: false,\n longPressed: false,\n timer: undefined,\n };\n press = p;\n if (timers && longPressKinds.includes(pointer.kind)) {\n p.timer = timers.setTimer(() => {\n p.timer = undefined;\n if (press !== p || p.dragging || disposed) return;\n p.longPressed = true;\n emit({ type: \"longPress\", pointer: p.last, origin: p.origin });\n }, longPressMs);\n }\n emit({ type: \"press\", pointer });\n };\n\n const onMove = (e: RawPointerEvent) => {\n const kind = kindOf(e.pointerType);\n if (kind === \"touch\") {\n const t = touches.get(e.pointerId);\n const to = finitePoint(e.screen);\n const moved = !t || t.screen.x !== to.x || t.screen.y !== to.y;\n if (t) {\n t.screen = to;\n t.time = e.time;\n }\n if (pinch && pinch.ids.includes(e.pointerId)) {\n updatePinch(e.pointerId, e.time, toModifiers(e.modifiers), moved);\n return;\n }\n }\n if (press && press.origin.pointerId === e.pointerId) {\n const pointer = pointerOf(e);\n // A mouse or pen moving with no button down and no pointerup before it: the release was missed.\n if (pointer.kind !== \"touch\" && e.buttons === 0) {\n releasePress(pointer);\n return;\n }\n const p = press;\n p.last = pointer;\n if (!p.dragging) {\n if (dist(pointer.screen, p.origin.screen) <= thresholds[p.origin.kind]) return;\n p.dragging = true;\n clearTimer(p);\n emit({ type: \"dragStart\", pointer, origin: p.origin });\n return;\n }\n emit({ type: \"move\", pointer, origin: p.origin });\n return;\n }\n if (!press && kind !== \"touch\" && e.buttons === 0) emit({ type: \"hover\", pointer: pointerOf(e) });\n };\n\n const onUp = (e: RawPointerEvent) => {\n if (kindOf(e.pointerType) === \"touch\") {\n // A finger lifting from an undecided pinch: its last position is looked at once, so a quick pinch still counts\n const t = touches.get(e.pointerId);\n if (t && pinch && !pinch.kind && pinch.ids.includes(e.pointerId)) {\n const to = finitePoint(e.screen);\n const moved = t.screen.x !== to.x || t.screen.y !== to.y;\n t.screen = to;\n updatePinch(e.pointerId, e.time, toModifiers(e.modifiers), moved, true);\n }\n touches.delete(e.pointerId);\n if (pinch && pinch.ids.includes(e.pointerId)) {\n endPinch(\"end\", e.time, toModifiers(e.modifiers));\n return;\n }\n if (touches.size === 0) touchLocked = false;\n }\n if (press && press.origin.pointerId === e.pointerId) releasePress(pointerOf(e));\n };\n\n const onCancel = (e: RawPointerEvent, reason: CancelReason) => {\n if (kindOf(e.pointerType) === \"touch\") {\n const tracked = touches.delete(e.pointerId);\n if (pinch && pinch.ids.includes(e.pointerId)) {\n if (tracked) endPinch(\"cancel\", e.time, toModifiers(e.modifiers));\n return;\n }\n if (touches.size === 0) touchLocked = false;\n }\n if (press && press.origin.pointerId === e.pointerId) cancelPress(reason, pointerOf(e));\n };\n\n const onWheel = (e: RawWheelEvent) => {\n const modifiers = toModifiers(e.modifiers);\n const screen = finitePoint(e.screen);\n const at = { screen, canvas: toCanvas(screen) };\n const intent = classifyWheel(wheelDelta(e.deltaX, e.deltaY, e.deltaMode, wheelCfg), modifiers, wheelCfg);\n if (intent.kind === \"zoom\") {\n if (intent.factor !== 1) emit({ type: \"zoom\", factor: intent.factor, at, modifiers, time: e.time });\n return;\n }\n if (intent.delta.x === 0 && intent.delta.y === 0) return;\n emit({ type: \"scroll\", delta: intent.delta, at, modifiers, time: e.time });\n };\n\n const onSafari = (e: RawSafariGestureEvent) => {\n // iOS Safari fires gesture events for touch pinches too; the pointer path handles those.\n if (touches.size > 0 || pinch) return;\n const modifiers = toModifiers(e.modifiers);\n const screen = finitePoint(e.screen);\n const scaleNow = Number.isFinite(e.scale) && e.scale > 0 ? e.scale : 1;\n const none = { x: 0, y: 0 };\n if (e.type === \"gesturestart\") {\n safari = { last: scaleNow };\n emit(pinchEvent(\"start\", screen, 1, none, e.time, modifiers, \"trackpad\", \"pinch\"));\n return;\n }\n if (!safari) return;\n const scale = scaleNow / safari.last;\n safari.last = scaleNow;\n if (e.type === \"gesturechange\") {\n if (scale !== 1) emit(pinchEvent(\"update\", screen, scale, none, e.time, modifiers, \"trackpad\", \"pinch\"));\n return;\n }\n safari = null;\n emit(pinchEvent(\"end\", screen, scale, none, e.time, modifiers, \"trackpad\", \"pinch\"));\n };\n\n const cancelAll = (reason: CancelReason) => {\n cancelPress(reason);\n if (pinch) endPinch(\"cancel\", lastTime, toModifiers(undefined));\n if (safari) {\n safari = null;\n emit(pinchEvent(\"cancel\", { x: 0, y: 0 }, 1, { x: 0, y: 0 }, lastTime, toModifiers(undefined), \"trackpad\", \"pinch\"));\n }\n };\n\n return {\n feed(event) {\n if (disposed) return;\n if (Number.isFinite(event.time)) lastTime = event.time;\n switch (event.type) {\n case \"pointerdown\":\n return onDown(event);\n case \"pointermove\":\n return onMove(event);\n case \"pointerup\":\n return onUp(event);\n case \"pointercancel\":\n return onCancel(event, \"pointercancel\");\n case \"lostpointercapture\":\n // Also fires right after pointerup; by then the press is gone and this is a no-op. The content\n // losing its capture (the surface just took the pointer) is not the gesture's end.\n if (event.lostBy === \"content\") return;\n return onCancel(event, \"lostcapture\");\n case \"wheel\":\n return onWheel(event);\n case \"gesturestart\":\n case \"gesturechange\":\n case \"gestureend\":\n return onSafari(event);\n }\n },\n cancel: cancelAll,\n reset() {\n cancelAll(\"reset\");\n touches.clear();\n touchLocked = false;\n lastClick = null;\n },\n active() {\n return press ? { pointerId: press.origin.pointerId, kind: press.origin.kind, dragging: press.dragging } : null;\n },\n pinching() {\n return !!pinch?.kind || !!safari;\n },\n setDragModifier(key) {\n dragModifier = key;\n },\n dispose() {\n if (press) clearTimer(press);\n press = null;\n pinch = null;\n safari = null;\n touches.clear();\n disposed = true;\n },\n };\n}\n","import type { TimerSource } from \"../clock/port\";\nimport { signal } from \"../signals/signals\";\n\n/**\n * A timer event a state asks for: send `event(t)` when the clock reaches\n * `at`. Machines stay pure; this is how a long-press or a dwell turns into\n * an event without the reducer touching a timer.\n */\nexport interface Deadline<E> {\n /** Clock time in ms. */\n readonly at: number;\n /** The event to send, given the clock time it fired at. */\n readonly event: (t: number) => E;\n}\n\n/** Options of {@link createMachine}. */\nexport interface MachineOptions<S, E> {\n /** The pure transition function. Returning the same state means \"no change\". */\n readonly reducer: (state: S, event: E) => S;\n readonly initial: S;\n /** Timers come from here (and `now()` for their events). */\n readonly clock: TimerSource;\n /** The timer event the state needs, or `null`. Checked after every transition. */\n readonly deadline?: (state: S) => Deadline<E> | null;\n}\n\n/** A running machine: the state, a way to send events, and change listeners. */\nexport interface Machine<S, E> {\n /** The current state; reactive (read it in a computed or an effect). */\n readonly state: S;\n /** The current state, untracked. */\n peek(): S;\n /**\n * Run `event` through the reducer and return the new state. An event sent\n * from a listener waits until the current one has been handled.\n */\n send(event: E): S;\n /** Called after each change of state (not for events that changed nothing). */\n subscribe(listener: (next: S, previous: S, event: E) => void): () => void;\n /** Clear the timer and drop listeners. Events sent after this are ignored. */\n dispose(): void;\n}\n\n/** Run a pure machine on a clock: it arms and clears the deadline timer for you. */\nexport function createMachine<S, E>(options: MachineOptions<S, E>): Machine<S, E> {\n const { reducer, clock, deadline } = options;\n const state = signal(options.initial);\n const listeners = new Set<(next: S, previous: S, event: E) => void>();\n const inbox: E[] = [];\n let dispatching = false;\n let disposed = false;\n let timer: number | null = null;\n let timerAt: number | null = null;\n let timerEvent: ((t: number) => E) | null = null;\n\n const clearTimer = (): void => {\n if (timer !== null) clock.clearTimer(timer);\n timer = null;\n timerAt = null;\n timerEvent = null;\n };\n\n const arm = (): void => {\n const due = deadline === undefined ? null : deadline(state.peek());\n if (due === null) {\n clearTimer();\n return;\n }\n timerEvent = due.event;\n if (timer !== null && timerAt === due.at) return;\n if (timer !== null) clock.clearTimer(timer);\n timerAt = due.at;\n timer = clock.setTimer(() => {\n const make = timerEvent;\n timer = null;\n timerAt = null;\n timerEvent = null;\n if (make !== null) machine.send(make(clock.now()));\n }, Math.max(0, due.at - clock.now()));\n };\n\n const machine: Machine<S, E> = {\n get state() {\n return state.value;\n },\n peek: () => state.peek(),\n send(event) {\n if (disposed) return state.peek();\n inbox.push(event);\n if (dispatching) return state.peek();\n dispatching = true;\n try {\n let next: E | undefined;\n while ((next = inbox.shift()) !== undefined) {\n const previous = state.peek();\n const after = reducer(previous, next);\n if (after === previous) continue;\n state.value = after;\n arm();\n for (const listener of Array.from(listeners)) listener(after, previous, next);\n if (disposed) break;\n }\n } finally {\n dispatching = false;\n inbox.length = 0;\n }\n return state.peek();\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n clearTimer();\n listeners.clear();\n },\n };\n arm();\n return machine;\n}\n","import type { TimerSource } from \"../clock/port\";\nimport { createMachine, type Deadline, type Machine } from \"./machine\";\n\n/**\n * The dwell machine (spring-load): hold over the same target long enough and\n * it fires, once.\n *\n * ```text\n * idle ──hover(key)──► dwelling ──tick (t − since ≥ dwell)──► fired\n * ▲ │ hover(other key) restarts `since` │\n * │ │ hover(null) ─► idle │\n * └────────┴─────────────── reset ◄─────────────────────┘\n * ```\n *\n * `fired` holds until `reset`: neither a late tick nor a hover change can fire\n * it again or clear it while the host acts on it. Shapes come from\n * hypr-tiling's `springLoadReducer`, with its workspace tab generalised to\n * any `key` (the host passes `null` for anything that shouldn't dwell, such as\n * the active tab).\n */\n\n/** Tunables of the dwell machine. */\nexport interface DwellConfig {\n /** How long in ms the pointer must stay over the same key. Default 500. */\n readonly dwell: number;\n}\n\n/** Defaults of {@link DwellConfig}. */\nexport const DWELL_DEFAULTS: DwellConfig = { dwell: 500 };\n\n/** The dwell machine's state. `K` is the target key, `P` the payload carried into `fired`. */\nexport type DwellState<K = string, P = unknown> =\n | { readonly phase: \"idle\" }\n | { readonly phase: \"dwelling\"; readonly key: K; readonly since: number; readonly payload: P | undefined }\n | {\n readonly phase: \"fired\";\n readonly key: K;\n readonly since: number;\n readonly firedAt: number;\n readonly payload: P | undefined;\n };\n\n/** Events of the dwell machine. `t` is the clock time in ms. */\nexport type DwellInput<K = string, P = unknown> =\n | { readonly type: \"hover\"; readonly t: number; readonly key: K | null; readonly payload?: P }\n | { readonly type: \"tick\"; readonly t: number }\n | { readonly type: \"reset\" };\n\n/** The idle state (the same object every time). */\nexport const DWELL_IDLE: DwellState<never, never> = { phase: \"idle\" };\n\n/** The dwell machine's pure transition function. */\nexport function dwellReducer<K, P>(\n state: DwellState<K, P>,\n event: DwellInput<K, P>,\n config: DwellConfig = DWELL_DEFAULTS,\n): DwellState<K, P> {\n switch (event.type) {\n case \"reset\":\n return state.phase === \"idle\" ? state : DWELL_IDLE;\n case \"hover\":\n if (state.phase === \"fired\") return state;\n if (event.key === null) return state.phase === \"idle\" ? state : DWELL_IDLE;\n if (state.phase === \"dwelling\" && Object.is(state.key, event.key)) return state;\n return { phase: \"dwelling\", key: event.key, since: event.t, payload: event.payload };\n case \"tick\":\n if (state.phase !== \"dwelling\" || event.t - state.since < config.dwell) return state;\n return { phase: \"fired\", key: state.key, since: state.since, firedAt: event.t, payload: state.payload };\n default:\n return state;\n }\n}\n\n/** When a dwelling state fires, as a timer event; `null` outside `dwelling`. */\nexport function dwellDeadline<K, P>(\n state: DwellState<K, P>,\n config: DwellConfig = DWELL_DEFAULTS,\n): Deadline<DwellInput<K, P>> | null {\n if (state.phase !== \"dwelling\") return null;\n return { at: state.since + config.dwell, event: (t) => ({ type: \"tick\", t }) };\n}\n\n/** Options of {@link createDwellMachine}. */\nexport interface DwellMachineOptions {\n readonly clock: TimerSource;\n readonly config?: Partial<DwellConfig>;\n}\n\n/** A dwell machine on a clock: the dwell timer is armed for you. */\nexport function createDwellMachine<K = string, P = unknown>(\n options: DwellMachineOptions,\n): Machine<DwellState<K, P>, DwellInput<K, P>> {\n const config: DwellConfig = { ...DWELL_DEFAULTS, ...options.config };\n return createMachine<DwellState<K, P>, DwellInput<K, P>>({\n reducer: (state, event) => dwellReducer(state, event, config),\n initial: DWELL_IDLE,\n clock: options.clock,\n deadline: (state) => dwellDeadline(state, config),\n });\n}\n","import type { TimerSource } from \"../clock/port\";\nimport type { Point } from \"../shapes\";\nimport { createMachine, type Deadline, type Machine } from \"./machine\";\n\n/**\n * A touch press on something draggable that sits in a scrolling page: is it a drag, or a scroll?\n *\n * ```text\n * idle ──press──► pressed ──move: mostly along the scroll direction, ≥ scrollEscape──► scrolled (never lifts)\n * │ ──move: mostly across it, ≥ lift px────────────────────────────► lifted\n * │ ──tick: held still hold─────────────────────────────────────► lifted (where it was pressed)\n * └ ──move: along it short of the escape, or across it below lift px: stays pressed\n * any ──release──► idle\n * ```\n *\n * Before the hold has elapsed, a finger that travels mostly along the page's scroll direction is a scroll: the touch\n * goes back to the page and stays a scroll until it is released; short of the escape it waits, never lifting.\n * Travel past the lift distance mostly across the scroll direction is a deliberate drag. Once the hold has elapsed\n * the press lifts where it is. `scrolled` and `lifted`\n * hold until `release`.\n */\n\n/** Tunables of the touch press. */\nexport interface TouchPressConfig {\n /** px of travel that lifts a press that is not a scroll. Default 6. */\n readonly lift: number;\n /** px of travel along the scroll direction that makes the press a scroll. Default 10. */\n readonly scrollEscape: number;\n /** The page's scroll direction: `\"y\"` (a vertical page, the default) or `\"x\"`. */\n readonly scroll: \"x\" | \"y\";\n /** ms a still finger holds before the press lifts where it is. Default 220. */\n readonly hold: number;\n}\n\n/** Defaults of {@link TouchPressConfig}. */\nexport const TOUCH_PRESS_DEFAULTS: TouchPressConfig = { lift: 6, scrollEscape: 10, scroll: \"y\", hold: 220 };\n\n/** The touch press's state. `from` is where the finger went down, `at` where it lifted. */\nexport type TouchPressState =\n | { readonly phase: \"idle\" }\n | { readonly phase: \"pressed\"; readonly from: Point; readonly since: number }\n | { readonly phase: \"lifted\"; readonly from: Point; readonly at: Point }\n | { readonly phase: \"scrolled\"; readonly from: Point };\n\n/** Events of the touch press. `t` is the clock time in ms. */\nexport type TouchPressInput =\n | { readonly type: \"press\"; readonly t: number; readonly point: Point }\n | { readonly type: \"move\"; readonly point: Point }\n | { readonly type: \"tick\"; readonly t: number }\n | { readonly type: \"release\" };\n\n/** The idle state (the same object every time). */\nexport const TOUCH_PRESS_IDLE: TouchPressState = { phase: \"idle\" };\n\n/** The touch press's pure transition function. */\nexport function touchPressReducer(state: TouchPressState, event: TouchPressInput, config: TouchPressConfig = TOUCH_PRESS_DEFAULTS): TouchPressState {\n switch (event.type) {\n case \"release\":\n return state.phase === \"idle\" ? state : TOUCH_PRESS_IDLE;\n case \"press\":\n return state.phase === \"idle\" ? { phase: \"pressed\", from: { x: event.point.x, y: event.point.y }, since: event.t } : state;\n case \"tick\":\n if (state.phase !== \"pressed\" || event.t - state.since < config.hold) return state;\n return { phase: \"lifted\", from: state.from, at: state.from };\n case \"move\": {\n if (state.phase !== \"pressed\") return state;\n const dx = event.point.x - state.from.x;\n const dy = event.point.y - state.from.y;\n const along = Math.abs(config.scroll === \"y\" ? dy : dx);\n const across = Math.abs(config.scroll === \"y\" ? dx : dy);\n // Mostly along the scroll direction is never a lift: a scroll once it reaches the escape, until then waiting\n // (a finger scroll is reported a few px at a time, and would pass the lift distance first).\n if (along > across) return along >= config.scrollEscape ? { phase: \"scrolled\", from: state.from } : state;\n if (Math.hypot(dx, dy) >= config.lift) return { phase: \"lifted\", from: state.from, at: { x: event.point.x, y: event.point.y } };\n return state;\n }\n default:\n return state;\n }\n}\n\n/** When a pressed state lifts by holding, as a timer event; `null` outside `pressed`. */\nexport function touchPressDeadline(state: TouchPressState, config: TouchPressConfig = TOUCH_PRESS_DEFAULTS): Deadline<TouchPressInput> | null {\n if (state.phase !== \"pressed\") return null;\n return { at: state.since + config.hold, event: (t) => ({ type: \"tick\", t }) };\n}\n\n/** Options of {@link createTouchPress}. */\nexport interface TouchPressOptions {\n readonly clock: TimerSource;\n readonly config?: Partial<TouchPressConfig>;\n}\n\n/** A touch press on a clock: the hold timer is armed for you. */\nexport function createTouchPress(options: TouchPressOptions): Machine<TouchPressState, TouchPressInput> {\n const config: TouchPressConfig = { ...TOUCH_PRESS_DEFAULTS, ...options.config };\n return createMachine<TouchPressState, TouchPressInput>({\n reducer: (state, event) => touchPressReducer(state, event, config),\n initial: TOUCH_PRESS_IDLE,\n clock: options.clock,\n deadline: (state) => touchPressDeadline(state, config),\n });\n}\n","import { sampleOrder } from \"../samples\";\n\n/**\n * The release velocity: how fast, and which way, a pointer was moving along one axis when its gesture ended, read from\n * its last samples. A gesture that ends in a throw (a paged swipe, a drag let go) hands it to the value that carries\n * on. It is a velocity, signed, always a number; the landing model's hand speed (a speed along the path, unsigned, for\n * judging \"fast or slow\", and allowed to be unknown) is a different estimate. On straight, steady motion the two read\n * the same size. Both read sample times the same way (`../samples`).\n *\n * The rule, over the samples (oldest first):\n * - **Which samples count.** One whose time or travel is not a finite number is left out; so is one stamped earlier\n * than the newest kept, and one under 1 ms past it (the same sample: in a run of such stamps, the first 1 ms or more\n * past the newest kept counts). Of the rest, those no more than `lookback` ms older than the newest are read, at most\n * the newest 64.\n * - **The rest.** It is 0 when the gesture ended more than `rest` ms after the newest sample (the pointer stood still),\n * or before it (a clock that stepped back), or when fewer than two samples are read.\n * - **The velocity** is the travel from the oldest sample read to the newest over the time between them, read over\n * 16 ms at least (a window shorter than one 60 Hz frame says little about speed), in px per ms. A result that is not\n * a finite number is 0.\n *\n * Only the sample times decide which samples count, so a host that draws something other than the travel (a curve\n * of it) maps the travels of its samples and calls this on them: the velocity of what it draws, by the same rule.\n */\n\n/** One sample of a moving pointer: the clock time (ms) and the travel along one axis (px). */\nexport interface ReleaseSample {\n readonly t: number;\n readonly travel: number;\n}\n\n/** The two numbers the release velocity reads, both ms. */\nexport interface ReleaseRule {\n /** The samples of the last `lookback` ms count (the window). A value that is not a number above 0 means the default; above 1000 (Infinity too) it is 1000. */\n readonly lookback: number;\n /** A gesture that ended more than `rest` ms after its newest sample ends at 0. `Infinity`: never. NaN or a value below 0 means the default. */\n readonly rest: number;\n}\n\n/** Defaults of {@link ReleaseRule}: a 50 ms window, a 100 ms rest. */\nexport const RELEASE_RULE: ReleaseRule = { lookback: 50, rest: 100 };\n\n/** The shortest time the velocity is read over, ms. */\nconst MIN_SPAN = 16;\n/** The longest window, ms. */\nconst LOOKBACK_MAX = 1000;\n/** The most samples kept. */\nconst SAMPLES_MAX = 64;\n\n/** The window a rule asks for, as the rule reads it. */\nexport function releaseWindowOf(lookback: number | undefined): number {\n return lookback !== undefined && lookback > 0 ? Math.min(lookback, LOOKBACK_MAX) : RELEASE_RULE.lookback;\n}\n\nfunction restOf(rest: number | undefined): number {\n // Infinity is no rest at all, as `flickRest: Infinity` is for the paged swipe's commit.\n return rest !== undefined && rest >= 0 ? rest : RELEASE_RULE.rest;\n}\n\n/**\n * `samples` with `sample` added by the rule's first point: unchanged (the same array) when it doesn't count, else a new\n * array with the samples more than `lookback` ms older than it dropped, at most the newest 64. Internal: the paged\n * swipe records with it, and {@link releaseVelocity} reads with it.\n */\nexport function addReleaseSample(samples: ReadonlyArray<ReleaseSample>, sample: ReleaseSample, lookback: number): ReadonlyArray<ReleaseSample> {\n if (!Number.isFinite(sample.t) || !Number.isFinite(sample.travel)) return samples;\n const newest = samples[samples.length - 1];\n if (newest !== undefined && sampleOrder(newest.t, sample.t) !== \"next\") return samples;\n let start = Math.max(0, samples.length + 1 - SAMPLES_MAX);\n while (start < samples.length && sample.t - samples[start]!.t > lookback) start += 1;\n const kept = samples.slice(start);\n kept.push({ t: sample.t, travel: sample.travel });\n return kept;\n}\n\n/**\n * The release velocity of `samples` (oldest first) for a gesture that ended at `endedAt` (ms): px of travel per ms,\n * signed like the travel. See the rule above. A value's velocity is per second: pass `releaseVelocity(…) * 1000` to\n * `set(target, { velocity })`.\n */\nexport function releaseVelocity(samples: ReadonlyArray<ReleaseSample>, endedAt: number, rule: Partial<ReleaseRule> = {}): number {\n const lookback = releaseWindowOf(rule.lookback);\n let read: ReadonlyArray<ReleaseSample> = [];\n for (const sample of samples) read = addReleaseSample(read, sample, lookback);\n const newest = read[read.length - 1];\n const oldest = read[0];\n if (newest === undefined || oldest === undefined || read.length < 2) return 0;\n const since = endedAt - newest.t;\n if (!(since >= 0) || since > restOf(rule.rest)) return 0;\n const v = (newest.travel - oldest.travel) / Math.max(newest.t - oldest.t, MIN_SPAN);\n return Number.isFinite(v) ? v : 0;\n}\n","import type { TimerSource } from \"../clock/port\";\nimport { createMachine, type Deadline, type Machine } from \"./machine\";\nimport { isHeld } from \"./modifiers\";\nimport { addReleaseSample, RELEASE_RULE, releaseVelocity, releaseWindowOf, type ReleaseSample } from \"./release-velocity\";\nimport type { ModifierKey, Modifiers } from \"./types\";\n\n/**\n * A paged swipe: a trackpad's two-finger scroll or a finger swipes from one page to the previous or the next, the\n * pages following it, and commits or snaps back when it ends.\n *\n * ```text\n * idle ──wheel / touch-move (arming rules pass)──► armed ──travel ≥ threshold──► tracking\n * ▲ │ │\n * │ rule breach / idle / end gesture end\n * │ ▼ ▼\n * └──────── lockout elapsed ◄── lockout ◄── settled (commit) ◄───────────── settling\n * └──────────────────────────────────────── settled (cancel) ◄───────────────────┤\n * └──────────────────────────────────────── cancel (transition stopped) ◄────────┘\n * ```\n *\n * - **Arming:** nothing else owns the pointer (`blocked`), the movement runs mostly along the swipe (more than twice\n * the cross movement), no Ctrl (a pinch), the configured modifier is held, nothing under the pointer can still\n * scroll that way (`canScrollFurther`), and there is a page on that side (or `wrap`). A wheel run that breaks a\n * rule belongs to scrolling until the wheel has been idle `idle`.\n * - **Tracking:** `progress` is the travel over the page size, −1 to 1, held at 0 towards a side with no page.\n * - **Ending:** a touch ends when the finger lifts, a wheel run after `idle` without samples. It commits when\n * `|progress| ≥ commitFraction`, or the peak speed towards the target reached `commitVelocity` (the peak starts\n * over when the travel crosses zero, so a fast fling out and a pull back does not commit the way back).\n * - **Settling** lasts as long as the host's page transition; the host sends `settled` when it is done (or `cancel`\n * when it stops the transition). After a commit, `lockout` swallows the trackpad's momentum for `lockout`, and the\n * run stays claimed after it. A cancel never skips a lockout: a committing settle that is cancelled goes to it too,\n * so momentum can't commit twice.\n * - **A finger:** a start that is `claimed` (it belongs to someone else: the system's screen edge, content that keeps\n * its gestures) never arms until the finger lifts. Something that `scrolled` while a finger swipes takes the swipe\n * (it commits nothing), and a finger that goes down before nothing has scrolled for `idle` never arms: a flick that\n * ran a scroll to its end doesn't page on the next flick. A finger that rested `flickRest` before lifting isn't flicking. With `band`, a\n * finger also tracks towards a side with no page (progress 0, never a commit), so the host can draw a rubber band\n * from `travel` ({@link rubberBand}).\n * - **The release velocity.** Every tracked sample is recorded in `samples`, and `settling` carries `releaseVelocity`:\n * {@link releaseVelocity} on those samples at `ended`, with `releaseWindow` as its window and `flickRest` as its rest\n * (a wheel run's too: it ends `idle` after its last sample, so with the default timings it ends at 0). A swipe that\n * gives way (`block`, `scrolled`, `cancel` while tracking) carries 0 and no samples: those events carry no time to\n * judge a rest by, and the pointer is no longer the swipe's.\n *\n * Pure and timer-free: {@link pagedSwipeDeadline} says when the next `tick` is due ({@link createPagedSwipe} arms it).\n * Signs: a wheel delta > 0 along the swipe heads to `next`; a finger moving towards smaller x (or y) heads to `next`.\n */\n\n/** Which side of the current page a swipe heads to. */\nexport type SwipeSide = \"prev\" | \"next\";\n\n/** Tunables of the paged swipe. */\nexport interface PagedSwipeConfig {\n /** px of travel before an armed swipe tracks. Default 24. */\n readonly threshold: number;\n /** The share of the page size that commits at the end. Default 0.35. */\n readonly commitFraction: number;\n /** px/ms: a peak speed towards the target that commits at the end. Default 0.6. */\n readonly commitVelocity: number;\n /** ms without a wheel sample that ends a wheel run. Default 120. */\n readonly idle: number;\n /** ms after a commit during which wheel samples are swallowed (momentum). Default 350. */\n readonly lockout: number;\n /** Past the last page comes the first, and back. Default false. */\n readonly wrap: boolean;\n /** The page size in px when no sample or context gives one. Default 800. */\n readonly size: number;\n /** A modifier the wheel needs held to swipe (`null`: none). Touch never needs one. Default null. */\n readonly modifier: ModifierKey | null;\n /** The swipe's direction: `\"x\"` (the default) or `\"y\"`. */\n readonly along: \"x\" | \"y\";\n /** ms: a finger resting this long before it lifts ends without a flick (its peak speed doesn't count). Default 100. */\n readonly flickRest?: number;\n /** A finger may track towards a side with no page, never committing there (for a rubber band). Default false. */\n readonly band?: boolean;\n /**\n * ms: the release velocity reads the newest 64 samples within the swipe's last `releaseWindow` ms (see\n * {@link releaseVelocity}). Default 50. A value that is not a number above 0 means the default; above 1000 (Infinity\n * too) it is 1000.\n */\n readonly releaseWindow?: number;\n}\n\nconst FLICK_REST_DEFAULT = 100;\n\n/** Defaults of {@link PagedSwipeConfig}. */\nexport const PAGED_SWIPE_DEFAULTS: PagedSwipeConfig = {\n threshold: 24,\n commitFraction: 0.35,\n commitVelocity: 0.6,\n idle: 120,\n lockout: 350,\n wrap: false,\n size: 800,\n modifier: null,\n along: \"x\",\n flickRest: FLICK_REST_DEFAULT,\n band: false,\n releaseWindow: RELEASE_RULE.lookback,\n};\n\n/** What the host knows about the pages now. */\nexport interface PagedSwipeContext {\n readonly hasPrev: boolean;\n readonly hasNext: boolean;\n /** The page size in px, or null (the config's). */\n readonly size: number | null;\n /** Something else owns the pointer (a drag): nothing arms, and a swipe in progress gives way. */\n readonly blocked: boolean;\n /** When something last `scrolled` (ms), or null (the default): a finger that goes down within `idle` of it never arms. */\n readonly scrolledAt?: number | null;\n}\n\n/** The context before the host has said anything. */\nexport const PAGED_SWIPE_EMPTY_CONTEXT: PagedSwipeContext = { hasPrev: false, hasNext: false, size: null, blocked: false, scrolledAt: null };\n\ntype Input = \"wheel\" | \"touch\";\ninterface Base {\n readonly context: PagedSwipeContext;\n /** −1 to 1; negative towards `prev`. */\n readonly progress: number;\n readonly target: SwipeSide | null;\n}\n\n/** The paged swipe's state. Every phase has a way back to `idle`. */\nexport type PagedSwipeState =\n | (Base & {\n readonly phase: \"idle\";\n /** The last wheel sample of the current run (null: none, or the run went idle). */\n readonly lastWheel: number | null;\n /** This wheel run broke the arming rules (or committed): it cannot arm until the wheel is idle `idle`. */\n readonly claimed: boolean;\n })\n | (Base & {\n readonly phase: \"armed\";\n readonly input: Input;\n /** Where the finger went down (touch). */\n readonly origin: { readonly x: number; readonly y: number };\n /** Wheel travel along the swipe and across it so far. */\n readonly travel: number;\n readonly cross: number;\n readonly last: number;\n })\n | (Base & {\n readonly phase: \"tracking\";\n readonly input: Input;\n readonly origin: { readonly x: number; readonly y: number };\n readonly travel: number;\n readonly last: number;\n /** The highest speed (px/ms) towards the current target. */\n readonly peak: number;\n /** The context the swipe armed with: its pages and size hold until it ends (a `context` meanwhile waits). */\n readonly held: PagedSwipeContext;\n /**\n * The tracked samples the release velocity will read, oldest first: the newest 64 within the last\n * `releaseWindow` ms (the newest is the one that set `last` and `travel`, unless it was the same sample as the one\n * before). The reducer always sets it; it is optional only so that a state written by hand still compiles (one\n * without it counts `{ last, travel }` as its first sample).\n */\n readonly samples?: ReadonlyArray<ReleaseSample>;\n })\n | (Base & {\n readonly phase: \"settling\";\n readonly input: Input;\n readonly outcome: \"commit\" | \"cancel\";\n readonly ended: number;\n readonly lastWheel: number;\n /**\n * px per ms, like `peak` and `commitVelocity`, signed like `travel` (positive towards `next`): how fast the swipe\n * moved when it ended, {@link releaseVelocity} on `samples` at `ended`; 0 when it gave way. A value's velocity is\n * per second: for a page drawn at `-travel`, `set(target, { velocity: -releaseVelocity * 1000 })`. The reducer\n * always sets it; it is optional only so that a state written by hand still compiles.\n */\n readonly releaseVelocity?: number;\n /** The samples it was read from (empty when the swipe gave way). Always set by the reducer, like `releaseVelocity`. */\n readonly samples?: ReadonlyArray<ReleaseSample>;\n })\n | (Base & { readonly phase: \"lockout\"; readonly until: number; readonly lastWheel: number });\n\n/** Events of the paged swipe. `t` is the clock time in ms. */\nexport type PagedSwipeInput =\n | {\n readonly type: \"wheel\";\n readonly dx: number;\n readonly dy: number;\n readonly t: number;\n readonly modifiers: Modifiers;\n /** Something under the pointer can still scroll that way: no arming. */\n readonly canScrollFurther?: boolean;\n readonly size?: number;\n }\n /** A finger went down; `claimed`: the start belongs to someone else, and this touch never arms. */\n | { readonly type: \"touch-start\"; readonly x: number; readonly y: number; readonly t: number; readonly size?: number; readonly claimed?: boolean }\n | { readonly type: \"touch-move\"; readonly x: number; readonly y: number; readonly t: number; readonly canScrollFurther?: boolean; readonly size?: number }\n | { readonly type: \"touch-end\"; readonly t: number }\n | { readonly type: \"tick\"; readonly t: number }\n | { readonly type: \"settled\" }\n | { readonly type: \"cancel\" }\n | { readonly type: \"block\"; readonly on: boolean }\n /** Something under the swipe scrolled (any axis): a finger's swipe in progress gives way, and none arms for `idle`. */\n | { readonly type: \"scrolled\"; readonly t: number }\n | { readonly type: \"context\"; readonly hasPrev: boolean; readonly hasNext: boolean; readonly size?: number };\n\n/** The idle state with no context. */\nexport const PAGED_SWIPE_IDLE: PagedSwipeState = { phase: \"idle\", context: PAGED_SWIPE_EMPTY_CONTEXT, progress: 0, target: null, lastWheel: null, claimed: false };\n\nconst idle = (context: PagedSwipeContext, lastWheel: number | null = null, claimed = false): PagedSwipeState => ({ phase: \"idle\", context, progress: 0, target: null, lastWheel, claimed });\nconst sideOf = (travel: number): SwipeSide | null => (travel > 0 ? \"next\" : travel < 0 ? \"prev\" : null);\nconst hasPage = (c: PagedSwipeContext, side: SwipeSide, wrap: boolean): boolean => (wrap ? c.hasPrev || c.hasNext : side === \"next\" ? c.hasNext : c.hasPrev);\nconst withSize = (c: PagedSwipeContext, size: number | undefined): PagedSwipeContext => (size === undefined || size === c.size ? c : { ...c, size });\nconst sizeOf = (c: PagedSwipeContext, size: number | undefined, config: PagedSwipeConfig): number => size ?? c.size ?? config.size;\n\n/** Where the swipe may head for a movement (`main` along the swipe, `cross` across it), or null when it must not arm. */\nfunction arming(c: PagedSwipeContext, main: number, cross: number, config: PagedSwipeConfig, gates: { ctrl: boolean; modifierHeld: boolean; canScrollFurther: boolean; band?: boolean }): SwipeSide | null {\n if (c.blocked || gates.ctrl || gates.canScrollFurther || !gates.modifierHeld) return null;\n if (Math.abs(main) <= 2 * Math.abs(cross)) return null;\n const side = sideOf(main);\n return side && (hasPage(c, side, config.wrap) || gates.band === true) ? side : null;\n}\n\n/** Whether something scrolled within the last `idle` ms before `t`. */\nconst scrolledRecently = (c: PagedSwipeContext, t: number, config: PagedSwipeConfig): boolean => c.scrolledAt != null && t - c.scrolledAt < config.idle;\n\n/**\n * A rubber band: how far (px) to draw a travel of `over` px past the last page, for a page `size` px long. It starts at\n * `strength` px per px of travel, grows ever more slowly, stays under `size`, keeps the sign of `over`, and never turns\n * back. Use it on `travel` while a `band` swipe heads to a side with no page.\n */\nexport function rubberBand(over: number, size: number, strength = 0.55): number {\n const d = Math.max(1, size);\n const a = Math.abs(over);\n if (!(a > 0) || !(strength > 0)) return 0;\n const drawn = (1 - 1 / ((a * strength) / d + 1)) * d;\n return over < 0 ? -drawn : drawn;\n}\n\n/** Travel to progress: over the page size, −1 to 1, 0 towards a side with no page (unless `wrap`). */\nexport function swipeProgress(travel: number, size: number, c: PagedSwipeContext, wrap: boolean): number {\n const p = Math.max(-1, Math.min(1, travel / Math.max(1, size)));\n if (wrap) return p;\n if ((p < 0 && !c.hasPrev) || (p > 0 && !c.hasNext)) return 0;\n return p;\n}\n\n/** Speed towards `side` for a step of `delta` px over `dt` ms; 0 moving away. */\nconst towards = (delta: number, dt: number, side: SwipeSide | null): number => {\n if (dt <= 0 || side === null) return 0;\n const v = (side === \"next\" ? delta : -delta) / dt;\n return v > 0 ? v : 0;\n};\n\ntype Tracking = Extract<PagedSwipeState, { phase: \"tracking\" }>;\n\n/** A tracking state's samples: its own, or (written by hand without them) its `{ last, travel }`. */\nconst samplesOf = (s: Tracking, config: PagedSwipeConfig): ReadonlyArray<ReleaseSample> =>\n s.samples ?? addReleaseSample([], { t: s.last, travel: s.travel }, releaseWindowOf(config.releaseWindow));\n\n/**\n * A tracking state: progress from the pages and size of `held` (the context the swipe armed with), not of `c`. Every\n * way into tracking, and every move while tracking, builds the state here, so each tracked sample is recorded once\n * (`before`: the samples so far, none on the way in).\n */\nfunction track(c: PagedSwipeContext, held: PagedSwipeContext, input: Input, origin: { x: number; y: number }, travel: number, t: number, peak: number, sampleSize: number | undefined, config: PagedSwipeConfig, before: ReadonlyArray<ReleaseSample> = []): PagedSwipeState {\n const progress = swipeProgress(travel, sizeOf(held, sampleSize, config), held, config.wrap);\n const samples = addReleaseSample(before, { t, travel }, releaseWindowOf(config.releaseWindow));\n return { phase: \"tracking\", context: c, held, input, origin, travel, last: t, peak, progress, target: sideOf(progress), samples };\n}\n\nfunction end(s: Tracking, t: number, config: PagedSwipeConfig): PagedSwipeState {\n const commit = s.target !== null && (Math.abs(s.progress) >= config.commitFraction || s.peak >= config.commitVelocity);\n const samples = samplesOf(s, config);\n return {\n phase: \"settling\",\n context: s.context,\n input: s.input,\n outcome: commit ? \"commit\" : \"cancel\",\n ended: t,\n lastWheel: t,\n progress: s.progress,\n target: commit ? s.target : null,\n releaseVelocity: releaseVelocity(samples, t, { lookback: config.releaseWindow, rest: config.flickRest ?? FLICK_REST_DEFAULT }),\n samples,\n };\n}\n\n/** Something else took the pointer: the swipe settles back with nothing measured (no time to judge a rest by). */\nconst giveUp = (s: Tracking, c: PagedSwipeContext): PagedSwipeState => ({\n phase: \"settling\",\n context: c,\n input: s.input,\n outcome: \"cancel\",\n ended: s.last,\n lastWheel: s.last,\n progress: s.progress,\n target: null,\n releaseVelocity: 0,\n samples: [],\n});\n\n/** The paged swipe's pure transition function. Unmatched pairs return the state unchanged. */\nexport function pagedSwipeReducer(state: PagedSwipeState, event: PagedSwipeInput, config: PagedSwipeConfig = PAGED_SWIPE_DEFAULTS): PagedSwipeState {\n const y = config.along === \"y\";\n if (event.type === \"context\") {\n return { ...state, context: { ...state.context, hasPrev: event.hasPrev, hasNext: event.hasNext, size: event.size ?? state.context.size } };\n }\n if (event.type === \"block\") {\n const c = state.context.blocked === event.on ? state.context : { ...state.context, blocked: event.on };\n if (event.on && state.phase === \"armed\") return idle(c);\n if (event.on && state.phase === \"tracking\") return giveUp(state, c);\n return c === state.context ? state : { ...state, context: c };\n }\n if (event.type === \"cancel\") {\n // Settling too: a host that will never send `settled` (it went away mid-transition) must not leave it stuck. A\n // committing settle still takes its lockout, and a lockout runs out on its own: a cancel that skipped it would let\n // the trackpad's momentum commit a second time.\n if (state.phase === \"settling\" && state.outcome === \"commit\") return { phase: \"lockout\", context: state.context, until: state.ended + config.lockout, lastWheel: state.lastWheel, progress: 0, target: null };\n if (state.phase === \"armed\" || state.phase === \"settling\") return idle(state.context);\n if (state.phase === \"tracking\") return giveUp(state, state.context);\n return state;\n }\n if (event.type === \"scrolled\") {\n const c: PagedSwipeContext = { ...state.context, scrolledAt: event.t };\n // A finger's swipe yields to the scroll; a wheel run is judged by its own samples.\n if (state.phase === \"armed\" && state.input === \"touch\") return idle(c);\n if (state.phase === \"tracking\" && state.input === \"touch\") return giveUp(state, c);\n return { ...state, context: c };\n }\n switch (state.phase) {\n case \"idle\": {\n if (event.type === \"wheel\") {\n if (state.context.blocked) return state;\n const fresh = state.lastWheel === null || event.t - state.lastWheel >= config.idle;\n if (!fresh && state.claimed) return { ...state, lastWheel: event.t };\n const main = y ? event.dy : event.dx;\n const cross = y ? event.dx : event.dy;\n const side = arming(state.context, main, cross, config, wheelGates(event, config));\n const c = withSize(state.context, event.size);\n if (side === null) return idle(c, event.t, true);\n if (Math.abs(main) >= config.threshold) return track(c, c, \"wheel\", { x: 0, y: 0 }, main, event.t, 0, event.size, config);\n return { phase: \"armed\", context: c, input: \"wheel\", origin: { x: 0, y: 0 }, travel: main, cross, last: event.t, progress: 0, target: null };\n }\n if (event.type === \"touch-start\") {\n // A claimed start, or one right after a scroll (a flick that ran it to its end), is the page's until it lifts.\n if (state.context.blocked || event.claimed === true || scrolledRecently(state.context, event.t, config)) return state;\n return { phase: \"armed\", context: withSize(state.context, event.size), input: \"touch\", origin: { x: event.x, y: event.y }, travel: 0, cross: 0, last: event.t, progress: 0, target: null };\n }\n return state;\n }\n case \"armed\": {\n if (event.type === \"wheel\") {\n if (state.input !== \"wheel\") return state;\n const main = y ? event.dy : event.dx;\n const cross = y ? event.dx : event.dy;\n // Every sample before the threshold must pass the rules too; a breach gives the run to scrolling.\n if (arming(state.context, main, cross, config, wheelGates(event, config)) === null) return idle(state.context, event.t, true);\n const c = withSize(state.context, event.size);\n const travel = state.travel + main;\n const crossTravel = state.cross + cross;\n // The run as a whole must stay along the swipe.\n if (Math.abs(crossTravel) > Math.abs(travel) / 2) return idle(c, event.t, true);\n if (Math.abs(travel) < config.threshold) return { ...state, context: c, travel, cross: crossTravel, last: event.t };\n return track(c, c, \"wheel\", state.origin, travel, event.t, towards(main, event.t - state.last, sideOf(travel)), event.size, config);\n }\n if (event.type === \"touch-move\") {\n if (state.input !== \"touch\") return state;\n const main = y ? state.origin.y - event.y : state.origin.x - event.x;\n const cross = y ? event.x - state.origin.x : event.y - state.origin.y;\n // Finger jitter.\n if (Math.hypot(main, cross) < config.threshold) return { ...state, last: event.t };\n const side = arming(state.context, main, cross, config, { ctrl: false, modifierHeld: true, canScrollFurther: event.canScrollFurther ?? false, band: config.band });\n // Across the swipe, or nowhere to go: the page owns this touch until it ends.\n if (side === null) return idle(state.context);\n const c = withSize(state.context, event.size);\n return track(c, c, \"touch\", state.origin, main, event.t, towards(main, event.t - state.last, side), event.size, config);\n }\n if (event.type === \"tick\") return state.input === \"wheel\" && event.t - state.last >= config.idle ? idle(state.context) : state;\n if (event.type === \"touch-end\") return state.input === \"touch\" ? idle(state.context) : state;\n if (event.type === \"touch-start\") {\n if (event.claimed === true || scrolledRecently(state.context, event.t, config)) return idle(state.context);\n return { ...state, context: withSize(state.context, event.size), input: \"touch\", origin: { x: event.x, y: event.y }, travel: 0, cross: 0, last: event.t };\n }\n return state;\n }\n case \"tracking\": {\n if (event.type === \"wheel\" || event.type === \"touch-move\") {\n if (state.input !== (event.type === \"wheel\" ? \"wheel\" : \"touch\")) return state;\n const travel =\n event.type === \"wheel\" ? state.travel + (y ? event.dy : event.dx) : y ? state.origin.y - event.y : state.origin.x - event.x;\n const side = sideOf(travel);\n // A wheel sample's step is its own delta: the difference of two travels can be a hair off it in floating\n // point, enough to tip a commit at the speed threshold.\n const step = event.type === \"wheel\" ? (y ? event.dy : event.dx) : travel - state.travel;\n const v = towards(step, event.t - state.last, side);\n const peak = side === sideOf(state.travel) ? Math.max(state.peak, v) : v;\n return track(state.context, state.held, state.input, state.origin, travel, event.t, peak, event.size, config, samplesOf(state, config));\n }\n if (event.type === \"tick\") return state.input === \"wheel\" && event.t - state.last >= config.idle ? end(state, event.t, config) : state;\n if (event.type === \"touch-end\") {\n if (state.input !== \"touch\") return state;\n // A finger that rested before it lifted isn't flicking.\n return end(event.t - state.last > (config.flickRest ?? FLICK_REST_DEFAULT) ? { ...state, peak: 0 } : state, event.t, config);\n }\n return state;\n }\n case \"settling\": {\n if (event.type === \"settled\") {\n if (state.outcome === \"commit\") return { phase: \"lockout\", context: state.context, until: state.ended + config.lockout, lastWheel: state.lastWheel, progress: 0, target: null };\n return idle(state.context, state.lastWheel, false);\n }\n if (event.type === \"wheel\") return { ...state, lastWheel: event.t };\n return state;\n }\n case \"lockout\": {\n if (event.type === \"wheel\") return event.t >= state.until ? idle(state.context, event.t, true) : { ...state, lastWheel: event.t };\n if (event.type === \"tick\") {\n if (event.t < state.until) return state;\n return event.t - state.lastWheel < config.idle ? idle(state.context, state.lastWheel, true) : idle(state.context);\n }\n // A finger is not momentum: it may start a swipe at once. One that would not arm (claimed, or right after a\n // scroll) doesn't end the lockout.\n if (event.type === \"touch-start\") {\n if (event.claimed === true || scrolledRecently(state.context, event.t, config)) return state;\n return pagedSwipeReducer(idle(state.context), event, config);\n }\n return state;\n }\n default:\n return state;\n }\n}\n\nfunction wheelGates(event: Extract<PagedSwipeInput, { type: \"wheel\" }>, config: PagedSwipeConfig): { ctrl: boolean; modifierHeld: boolean; canScrollFurther: boolean } {\n return { ctrl: event.modifiers.ctrl, modifierHeld: config.modifier === null || isHeld(event.modifiers, config.modifier), canScrollFurther: event.canScrollFurther ?? false };\n}\n\n/** When the next `tick` is due: a wheel run's idle end, or the end of the lockout; `null` when none is. */\nexport function pagedSwipeDeadline(state: PagedSwipeState, config: PagedSwipeConfig = PAGED_SWIPE_DEFAULTS): Deadline<PagedSwipeInput> | null {\n const tick = (t: number): PagedSwipeInput => ({ type: \"tick\", t });\n if ((state.phase === \"armed\" || state.phase === \"tracking\") && state.input === \"wheel\") return { at: state.last + config.idle, event: tick };\n if (state.phase === \"lockout\") return { at: state.until, event: tick };\n return null;\n}\n\n/** Options of {@link createPagedSwipe}. */\nexport interface PagedSwipeOptions {\n readonly clock: TimerSource;\n readonly config?: Partial<PagedSwipeConfig>;\n}\n\n/** A paged swipe on a clock: the idle and lockout timers are armed for you. */\nexport function createPagedSwipe(options: PagedSwipeOptions): Machine<PagedSwipeState, PagedSwipeInput> {\n const config: PagedSwipeConfig = { ...PAGED_SWIPE_DEFAULTS, ...options.config };\n return createMachine<PagedSwipeState, PagedSwipeInput>({\n reducer: (state, event) => pagedSwipeReducer(state, event, config),\n initial: PAGED_SWIPE_IDLE,\n clock: options.clock,\n deadline: (state) => pagedSwipeDeadline(state, config),\n });\n}\n"],"mappings":";;;;;;;;;;AAmBO,IAAM,eAAoC,OAAO,OAAO,EAAE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AAA,IACT,OAAO,QAAQ;AAAA,IACf,UAAU,CAAC,UAAU,mBAAmB,OAAO,MAAM;AAAA,EACvD,CAAC;AACH;","names":["scale","pan"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/shapes.ts","../src/values/step.ts","../src/values/settle.ts","../src/values/reveal.ts"],"sourcesContent":["/** A point or a 2D vector. */\nexport interface Point {\n x: number;\n y: number;\n}\n\n/** An axis-aligned rectangle. */\nexport interface Rect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/** Any number of components. */\nexport type Vector = readonly number[];\n\n/** The value shapes springs and tweens move: plain numbers, nothing else. */\nexport type Animatable = number | Point | Rect | Vector;\n\n/** The shape type of an {@link Animatable}: literal numbers widen to `number`. */\nexport type Widen<T> = T extends number\n ? number\n : T extends Vector\n ? Vector\n : T extends Rect\n ? Rect\n : T extends Point\n ? Point\n : never;\n\nconst SCALAR = 0;\nconst VECTOR = 1;\nconst POINT = 2;\nconst RECT = 3;\n\n/** How a shape maps onto a flat list of numbers. Internal to values/. */\nexport interface Layout {\n readonly kind: typeof SCALAR | typeof VECTOR | typeof POINT | typeof RECT;\n readonly size: number;\n}\n\nconst SCALAR_LAYOUT: Layout = { kind: SCALAR, size: 1 };\nconst POINT_LAYOUT: Layout = { kind: POINT, size: 2 };\nconst RECT_LAYOUT: Layout = { kind: RECT, size: 4 };\n\nexport function layoutOf(value: Animatable): Layout {\n if (typeof value === \"number\") return SCALAR_LAYOUT;\n if (Array.isArray(value)) return { kind: VECTOR, size: value.length };\n if (\"width\" in value) return RECT_LAYOUT;\n return POINT_LAYOUT;\n}\n\nexport function sameLayout(a: Layout, b: Layout): boolean {\n return a.kind === b.kind && a.size === b.size;\n}\n\n/** Copy `value`'s components into `out`. */\nexport function writeComponents(value: Animatable, out: Float64Array): void {\n if (typeof value === \"number\") {\n out[0] = value;\n } else if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) out[i] = value[i]!;\n } else if (\"width\" in value) {\n out[0] = value.x;\n out[1] = value.y;\n out[2] = value.width;\n out[3] = value.height;\n } else {\n const point = value as Point;\n out[0] = point.x;\n out[1] = point.y;\n }\n}\n\n/** A fresh value of `layout`'s shape from `components`. */\nexport function makeValue(layout: Layout, components: Float64Array): Animatable {\n switch (layout.kind) {\n case SCALAR:\n return components[0]!;\n case POINT:\n return { x: components[0]!, y: components[1]! };\n case RECT:\n return { x: components[0]!, y: components[1]!, width: components[2]!, height: components[3]! };\n default:\n return Array.from(components);\n }\n}\n\n/** Component-wise equality of two values of the same shape. */\nexport function shapeEquals(a: Animatable, b: Animatable): boolean {\n if (typeof a === \"number\" || typeof b === \"number\") return a === b;\n if (Array.isArray(a) || Array.isArray(b)) {\n const u = a as Vector;\n const v = b as Vector;\n if (u.length !== v.length) return false;\n for (let i = 0; i < u.length; i++) if (u[i] !== v[i]) return false;\n return true;\n }\n const p = a as Partial<Rect>;\n const q = b as Partial<Rect>;\n return p.x === q.x && p.y === q.y && p.width === q.width && p.height === q.height;\n}\n","import type { Animatable, Layout } from \"../shapes\";\nimport { layoutOf, makeValue, sameLayout, writeComponents } from \"../shapes\";\nimport type { Animator } from \"./animator\";\n\n/**\n * The exact critically damped step for one component, shared by the spring and the settle: displacement `d0` from the\n * target and velocity `v0` (per second) after `t` seconds, with `e` = e^(−w·t) worked out once per step. Writes into\n * out[0], out[1]: d(t) = e·(d0 + b·t), v(t) = e·(v0 − w·b·t), b = v0 + w·d0.\n */\nexport function criticalStep(w: number, e: number, d0: number, v0: number, t: number, out: Float64Array): void {\n const b = v0 + w * d0;\n out[0] = e * (d0 + b * t);\n out[1] = e * (v0 - w * b * t);\n}\n\n/**\n * What the spring and the settle share: a value of any {@link Animatable} shape kept as components (position, velocity\n * and target), its shape check, the rest test of a step, jump and snap. Each one adds only its own law: `begin` (what a\n * step works out once), `advance` (one component over `t` seconds) and `rests` (when a component counts as arrived).\n */\nexport abstract class ComponentAnimator implements Animator<Animatable> {\n readonly layout: Layout;\n readonly x: Float64Array;\n readonly v: Float64Array;\n readonly goal: Float64Array;\n readonly scratch = new Float64Array(2);\n settled = true;\n cachedValue: Animatable | null = null;\n /** How errors call it (\"spring\", \"settle\"). */\n private readonly name: string;\n\n constructor(initial: Animatable, name: string) {\n this.name = name;\n this.layout = layoutOf(initial);\n this.x = new Float64Array(this.layout.size);\n this.v = new Float64Array(this.layout.size);\n this.goal = new Float64Array(this.layout.size);\n writeComponents(initial, this.x);\n writeComponents(initial, this.goal);\n }\n\n get value(): Animatable {\n if (this.cachedValue === null) this.cachedValue = makeValue(this.layout, this.x);\n return this.cachedValue;\n }\n\n get velocity(): Animatable {\n return makeValue(this.layout, this.v);\n }\n\n get target(): Animatable {\n return makeValue(this.layout, this.goal);\n }\n\n check(value: Animatable, what: string): void {\n if (!sameLayout(layoutOf(value), this.layout)) {\n throw new TypeError(`${this.name}: ${what} has a different shape than the ${this.name}'s value`);\n }\n }\n\n /** At rest exactly when on the target and not moving. */\n updateSettled(): void {\n for (let i = 0; i < this.x.length; i++) {\n if (this.x[i] !== this.goal[i] || this.v[i] !== 0) {\n this.settled = false;\n return;\n }\n }\n this.settled = true;\n }\n\n abstract setTarget(target: Animatable): void;\n\n abstract setVelocity(velocity: Animatable): void;\n\n jumpTo(value: Animatable): void {\n this.check(value, \"the value\");\n writeComponents(value, this.x);\n writeComponents(value, this.goal);\n this.v.fill(0);\n this.cachedValue = null;\n this.settled = true;\n }\n\n snap(): void {\n this.x.set(this.goal);\n this.v.fill(0);\n this.cachedValue = null;\n this.settled = true;\n }\n\n /** Work out what every component's step of `t` seconds shares. */\n protected abstract begin(t: number): void;\n /** One component, `d0` from its target at `v0` per second, after `t` seconds: into out[0], out[1]. */\n protected abstract advance(d0: number, v0: number, t: number, out: Float64Array): void;\n /** Whether component `i`, now `d` from its target at `v` per second, counts as arrived. */\n protected abstract rests(i: number, d: number, v: number): boolean;\n\n step(dt: number): boolean {\n if (this.settled) return false;\n if (!(dt > 0)) return true;\n const t = dt / 1000;\n const { x, v, goal, scratch } = this;\n this.begin(t);\n let resting = true;\n for (let i = 0; i < x.length; i++) {\n this.advance(x[i]! - goal[i]!, v[i]!, t, scratch);\n x[i] = goal[i]! + scratch[0]!;\n v[i] = scratch[1]!;\n if (resting && !this.rests(i, scratch[0]!, scratch[1]!)) resting = false;\n }\n this.cachedValue = null;\n if (resting) this.snap();\n return !this.settled;\n }\n}\n","import type { Animatable, Widen } from \"../shapes\";\nimport { makeValue, writeComponents } from \"../shapes\";\nimport type { Animator } from \"./animator\";\nimport { ComponentAnimator, criticalStep } from \"./step\";\n\n/**\n * Tempos for {@link createSettle}, in 1/s: a settle covers 90 % of the way in\n * ln(10)/omega seconds and is within 1 % in twice that.\n *\n * - `calm` 20: 90 % in 115 ms, done in 230 ms.\n * - `default` 25: 90 % in 92 ms, done in 184 ms.\n * - `quick` 37: 90 % in 62 ms, done in 124 ms (a fast Hyprland setup).\n */\nexport const SETTLE_TEMPO = { calm: 20, default: 25, quick: 37 } as const;\n\n/** The values a settle is kept between, per component, in the value's shape (see {@link SettleConfig.within}). */\nexport interface SettleRange<T> {\n readonly min: T;\n readonly max: T;\n}\n\n/**\n * Settings of {@link createSettle}. `T` is the value's shape (`SettleConfig<number>`, `SettleConfig<Rect>`); a plain\n * `SettleConfig` has no range, and passes to a settle of any shape.\n */\nexport interface SettleConfig<T = never> {\n /** The tempo in 1/s (see {@link SETTLE_TEMPO}). Higher is faster. Default 25. */\n readonly omega?: number;\n /** Distance from the target that counts as arrived. Default 0.1 (tuned for pixels). */\n readonly restDelta?: number;\n /**\n * Limits how far a set velocity can carry the value: with the value and the target inside `min`…`max`, the value\n * never leaves. It does not move the value or the target; a target outside is still reached.\n *\n * A velocity set away from the target (`setVelocity`, or a value's `set(target, { velocity })`) makes the value go\n * on, stop and come back; with a range, that speed is lowered just enough for the value to stop before the bound\n * (to 0 when the value already stands at it, or the range has no width). A speed toward the target, a new target and\n * the rest are as without one. Per component; a side may be `-Infinity` or `Infinity` (open). `null` clears it.\n * Under reduced motion a value goes to its target at once, inside or not. Clearing the range later doesn't give back\n * a speed it lowered. A `min` above `max`, a side that is NaN, a `min` of `Infinity` or a `max` of `-Infinity`\n * throw a `RangeError`, and the settle is left as it was.\n */\n readonly within?: SettleRange<T> | null;\n}\n\n/**\n * The one curve for things that move to a new place: a window's rect between\n * layout targets, a drawer, a camera. Fast at the start, gentle at the end,\n * and it never passes its target.\n *\n * It is a critically damped spring (stiffness omega², damping 2·omega) with\n * one rule on its velocity, per component:\n *\n * - **Launch.** On a new target, each component gets the velocity\n * omega · distance toward it, from wherever it is drawn: standing still,\n * moving toward it, or moving away (it turns at once rather than drifting\n * further first). From there the spring follows `distance · e^(−omega·t)`\n * exactly: most of the move happens at once, the rest eases in.\n * - **Clamp.** That speed is also the most it may have toward the target, so a\n * velocity set by hand (`setVelocity`, a fling) toward the target is capped\n * there instead of shooting past.\n * - **Carry.** A velocity set by hand away from the target is kept, and the\n * value turns around; a critically damped spring turning around never\n * crosses the target either. With a range ({@link SettleConfig.within}) it\n * is lowered just enough for the value to stop before the bound on its side.\n * - **A velocity that is not a finite number** (NaN, ±Infinity, either way) is\n * taken as 0.\n *\n * So after a new target every component goes straight from where it is drawn\n * to the target and never past it: no overshoot on position, no wobble on\n * size, whatever the retargets. A new target starts from the drawn value,\n * never from the old start.\n *\n * Holding (a pointer owns the value): call `jumpTo(value)` on each move. The\n * value sits exactly there, at rest; the next `setTarget` launches from it.\n */\nexport interface Settle<T> extends Animator<T> {\n /** The tempo in 1/s. */\n readonly omega: number;\n /** The range in force ({@link SettleConfig.within}), or null. */\n readonly within: SettleRange<T> | null;\n /**\n * Set the velocity, in units per second (a gesture's release velocity in px per ms is `* 1000`); a component moving\n * toward the target is clamped as in the launch rule, one moving away is kept or, with a range, lowered.\n */\n setVelocity(velocity: T): void;\n /** Change the tempo, rest distance or range mid-flight; the value and velocity carry on, re-clamped and re-lowered. */\n configure(config: SettleConfig<T>): void;\n}\n\n/** Defaults of {@link SettleConfig}. */\nexport const SETTLE_DEFAULTS = { omega: SETTLE_TEMPO.default, restDelta: 0.1 } as const;\n\nfunction positive(name: string, value: number): number {\n if (!(value > 0) || !Number.isFinite(value)) throw new RangeError(`settle: ${name} must be a finite number > 0, got ${value}`);\n return value;\n}\n\n/** How far from its target a settle `a` (≥ 0) from it, moving away at `speed` (≥ 0), gets before it turns back. */\nfunction reach(a: number, speed: number, omega: number): number {\n // d(t) = (a + k·t)·e^(−omega·t), k = speed + omega·a, peaks at t* = speed / (omega·k).\n const k = speed + omega * a;\n return k > 0 ? (k / omega) * Math.exp(-speed / k) : a;\n}\n\n/**\n * The speed a settle `a` (≥ 0) from its target keeps when it moves away at `speed` (≥ 0) with `room` (≥ 0, Infinity:\n * none) between the target and the bound on that side: `speed` when its reach fits, 0 when it already stands at the\n * bound or past it, else the largest speed whose reach is at most `room` less a margin (so the sampled values stay\n * inside despite rounding), by bisection (the reach grows steadily with the speed).\n *\n * The margin, a billionth of the room, covers every rounding: the step's own error is a few float steps of the distance,\n * the room (bound − target) is exact when the two lie close and a half float step of the room otherwise, and the drawn\n * value, target + distance, can't pass target + room = the bound while the distance stays under the room, since float\n * addition keeps order.\n */\nfunction rangedSpeed(a: number, speed: number, room: number, omega: number): number {\n if (!(room < Infinity)) return speed;\n const inside = room - 1e-9 * room;\n if (a >= inside) return 0;\n if (reach(a, speed, omega) <= inside) return speed;\n // The reach grows with the distance too, so it is at least the reach from the target, speed / (omega·e): no speed\n // above omega·e·inside fits. Bisecting from there keeps a huge speed's answer as close as a small one's.\n let low = 0;\n let high = Math.min(speed, omega * Math.E * inside);\n for (let k = 0; k < 60; k += 1) {\n const mid = (low + high) / 2;\n if (reach(a, mid, omega) <= inside) low = mid;\n else high = mid;\n }\n return low;\n}\n\n/** A range's sides as components, checked: the error names what is wrong, and nothing is written on a throw. */\nfunction readRange(settle: SettleAnimator, range: SettleRange<Animatable>): { min: Float64Array; max: Float64Array } {\n settle.check(range.min, \"within's min\");\n settle.check(range.max, \"within's max\");\n const min = new Float64Array(settle.x.length);\n const max = new Float64Array(settle.x.length);\n writeComponents(range.min, min);\n writeComponents(range.max, max);\n for (let i = 0; i < min.length; i++) {\n const lo = min[i]!;\n const hi = max[i]!;\n if (Number.isNaN(lo) || Number.isNaN(hi) || lo > hi || lo === Infinity || hi === -Infinity) {\n throw new RangeError(`settle: within needs min <= max, each a number, min below Infinity and max above -Infinity; got ${lo} and ${hi}`);\n }\n }\n return { min, max };\n}\n\nclass SettleAnimator extends ComponentAnimator implements Settle<Animatable> {\n omega: number;\n restDelta: number;\n // One step's shared numbers (`begin`): e^(−omega·t) and the rest speed.\n private e = 1;\n private restSpeed = 0;\n private range: { min: Float64Array; max: Float64Array } | null = null;\n\n constructor(initial: Animatable, config: SettleConfig<Animatable>) {\n super(initial, \"settle\");\n this.omega = positive(\"omega\", config.omega ?? SETTLE_DEFAULTS.omega);\n this.restDelta = positive(\"restDelta\", config.restDelta ?? SETTLE_DEFAULTS.restDelta);\n if (config.within != null) this.range = readRange(this, config.within);\n }\n\n get within(): SettleRange<Animatable> | null {\n const range = this.range;\n return range === null ? null : { min: makeValue(this.layout, range.min), max: makeValue(this.layout, range.max) };\n }\n\n /** The launch/clamp/carry rule on component `i`: `launch` for a new target, else clamp or carry. */\n rule(i: number, launch: boolean): void {\n const d = this.x[i]! - this.goal[i]!;\n const limit = d === 0 ? 0 : -this.omega * d;\n if (launch) {\n this.v[i] = limit;\n return;\n }\n let v = this.v[i]!;\n if (!Number.isFinite(v)) this.v[i] = v = 0;\n if (v === 0) return;\n // Moving away from the target (d and v the same sign), or off it: carry, within the range if there is one.\n if (d === 0 || d * v > 0) {\n const range = this.range;\n if (range === null) return;\n const goal = this.goal[i]!;\n const bound = v > 0 ? range.max[i]! : range.min[i]!;\n const room = Math.max(0, v > 0 ? bound - goal : goal - bound);\n const kept = rangedSpeed(Math.abs(d), Math.abs(v), room, this.omega);\n // A plain 0 when lowered to nothing, never −0.\n this.v[i] = kept === 0 ? 0 : Math.sign(v) * kept;\n return;\n }\n // Moving toward it: no faster than a launch from here.\n if (Math.abs(v) > Math.abs(limit)) this.v[i] = limit;\n }\n\n setTarget(target: Animatable): void {\n this.check(target, \"the target\");\n writeComponents(target, this.goal);\n for (let i = 0; i < this.x.length; i++) this.rule(i, true);\n this.updateSettled();\n }\n\n setVelocity(velocity: Animatable): void {\n this.check(velocity, \"the velocity\");\n writeComponents(velocity, this.v);\n for (let i = 0; i < this.x.length; i++) this.rule(i, false);\n this.updateSettled();\n }\n\n configure(config: SettleConfig<Animatable>): void {\n // Everything is checked before anything changes.\n const range = config.within === undefined ? this.range : config.within === null ? null : readRange(this, config.within);\n const omega = config.omega === undefined ? this.omega : positive(\"omega\", config.omega);\n const restDelta = config.restDelta === undefined ? this.restDelta : positive(\"restDelta\", config.restDelta);\n this.omega = omega;\n this.restDelta = restDelta;\n this.range = range;\n for (let i = 0; i < this.x.length; i++) this.rule(i, false);\n }\n\n protected begin(t: number): void {\n this.e = Math.exp(-this.omega * t);\n // At rest when every component is within restDelta and no faster than a launch from there would be.\n this.restSpeed = this.omega * this.restDelta * 1.000001;\n }\n\n protected advance(d0: number, v0: number, t: number, out: Float64Array): void {\n criticalStep(this.omega, this.e, d0, v0, t, out);\n }\n\n protected rests(i: number, d: number, v: number): boolean {\n // Within a few float steps of the goal counts as arrived too: a restDelta finer than that would never be met.\n const near = Math.max(this.restDelta, 4 * Number.EPSILON * Math.abs(this.goal[i]!));\n return !(Math.abs(d) > near || Math.abs(v) > Math.max(this.restSpeed, this.omega * near));\n }\n}\n\n/**\n * A settle starting at rest on `initial` (a number, a vector, a point or a\n * rect; targets, velocities and a range must have the same shape). See\n * {@link Settle}.\n */\nexport function createSettle<T extends Animatable>(initial: T, config: SettleConfig<Widen<T>> = {}): Settle<Widen<T>> {\n return new SettleAnimator(initial, config as SettleConfig<Animatable>) as unknown as Settle<Widen<T>>;\n}\n","import type { Rect } from \"../shapes\";\n\n/**\n * How to draw a window whose rect is gliding without stretching its content.\n *\n * The content is laid out once at the target size and never scaled. The\n * window's element sits at its target in the layout; to draw it at the\n * gliding rect:\n *\n * - move the element by (`dx`, `dy`), so its top-left corner is the drawn rect's;\n * - draw the frame (background, border, shadow) at `width` × `height`: the drawn size;\n * - clip the content by `clipRight` and `clipBottom` so it fits a frame\n * smaller than the target (CSS: `clip-path: inset(0 clipRight clipBottom 0)`).\n *\n * A window that shrinks shows a band of its own background closing in at the\n * right and bottom; one that grows reveals content already laid out at its\n * new size. Text is never stretched. One transform and one clip per frame, no\n * layout per frame.\n */\nexport interface RevealFrame {\n /** Move the element (laid out at the target) right by this much. */\n readonly dx: number;\n /** Move the element (laid out at the target) down by this much. */\n readonly dy: number;\n /** The frame's width: the drawn rect's. */\n readonly width: number;\n /** The frame's height: the drawn rect's. */\n readonly height: number;\n /** Clip this much off the content's right edge (0 when the frame is at least as wide as the target). */\n readonly clipRight: number;\n /** Clip this much off the content's bottom edge (0 when the frame is at least as tall as the target). */\n readonly clipBottom: number;\n}\n\n/** The {@link RevealFrame} for content laid out at `target` and drawn at `drawn`. */\nexport function reveal(drawn: Rect, target: Rect): RevealFrame {\n return {\n dx: drawn.x - target.x,\n dy: drawn.y - target.y,\n width: Math.max(0, drawn.width),\n height: Math.max(0, drawn.height),\n clipRight: Math.max(0, target.width - drawn.width),\n clipBottom: Math.max(0, target.height - drawn.height),\n };\n}\n\n/** A uniform pop-in (or pop-out, run backwards): scale about the center and opacity. */\nexport interface PopIn {\n /** Scale about the window's center: the same on both axes, so nothing is stretched. */\n readonly scale: number;\n readonly opacity: number;\n}\n\n/**\n * Opening and closing: the window grows from `from` of its size to full, about\n * its center, while fading in. `progress` runs 0 to 1 (take it from a settle\n * on a number with `{ restDelta: 0.001 }`, since the default 0.1 is tuned for\n * pixels and would snap the last 10 %; or from a tween); closing runs it from\n * 1 to 0. Hyprland's default is `popin 87%`.\n */\nexport function popIn(progress: number, from = 0.87): PopIn {\n const p = Math.min(1, Math.max(0, progress));\n return { scale: from + (1 - from) * p, opacity: p };\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AO,OAAa,QAA2B;AAC7D,SAAO;AAAA,IACL,IAAI,MAAM,IAAI,OAAO;AAAA,IACrB,IAAI,MAAM,IAAI,OAAO;AAAA,IACrB,OAAO,KAAK,IAAI,GAAG,MAAM,KAAK;AAAA,IAC9B,QAAQ,KAAK,IAAI,GAAG,MAAM,MAAM;AAAA,IAChC,WAAW,KAAK,IAAI,GAAG,OAAO,QAAQ,MAAM,KAAK;AAAA,IACjD,YAAY,KAAK,IAAI,GAAG,OAAO,SAAS,MAAM,MAAM;AAAA,EACtD;AACF;AAgBO,SAAS,MAAM,UAAkB,OAAO,MAAa;AAC1D,QAAM,IAAI,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,QAAQ,CAAC;AAC3C,SAAO,EAAE,OAAO,QAAQ,IAAI,QAAQ,GAAG,SAAS,EAAE;AACpD;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/signals/signals.ts"],"sourcesContent":["/**\n * Signals: reactive values, computed values and effects.\n *\n * The graph algorithm is alien-signals' (`alien-signals/system`, the core it\n * publishes for building your own API on, also used by Vue 3.6). A write marks\n * only what depends on it (push); a computed recomputes only when it is read\n * and one of its sources really changed (pull). Both walks are iterative, so\n * depth doesn't eat the stack. bench/RESULTS.md has the comparison that\n * chose it over a hand-written graph and over @preact/signals-core.\n *\n * What this surface adds on top of that core:\n * - `.value` reads and writes, `peek()`, an `equals` option;\n * - a computed that throws keeps the error and rethrows it until a source changes;\n * - effects take a `schedule`: their runs go wherever the scheduler puts them,\n * so a frame loop phase runs each one at most once per frame, however many\n * writes land before it;\n * - an effect loop (effects that keep re-triggering each other) throws\n * instead of hanging.\n *\n * Semantics worth knowing:\n * - an effect's own writes don't re-run it (no self-loops), as in alien-signals and Vue;\n * - writes inside an effect are batched until it returns;\n * - this module's state (the tracking context, the batch depth, the effect\n * queue) is the graph's; there is no clock and no timer here.\n */\nimport { createReactiveSystem, type Link, type ReactiveNode } from \"alien-signals/system\";\n\n/** A value that can be read reactively. */\nexport interface ReadonlySignal<T> {\n /** The current value. Read inside a computed or an effect, it becomes a dependency. */\n readonly value: T;\n /** The current value, without becoming a dependency. */\n peek(): T;\n}\n\n/** A value that can be read reactively and written. */\nexport interface Signal<T> extends ReadonlySignal<T> {\n /** The current value. Writing a different value (by `equals`) notifies dependants. */\n value: T;\n}\n\n/** Decides whether a new value is the same as the old one (then nothing is notified). */\nexport type Equals<T> = (previous: T, next: T) => boolean;\n\n/** Options of {@link signal} and {@link computed}. */\nexport interface SignalOptions<T> {\n /** Equality used to skip notifications. Default `Object.is`; `false` notifies on every write. */\n readonly equals?: Equals<T> | false;\n}\n\n/** What an effect function may return: a cleanup, run before the next run and on dispose. */\nexport type EffectCleanup = () => void;\n\n/** Options of {@link effect}. */\nexport interface EffectOptions {\n /**\n * Where the effect's runs go. Without it, an effect runs synchronously at the\n * end of the outermost batch. With it, the first run and every re-run are\n * handed to `schedule(run)`; `run` is the same function each time, so a\n * scheduler that dedupes by identity (a frame loop's `scheduler(phase)`)\n * runs the effect once however many changes arrived.\n */\n readonly schedule?: (run: () => void) => void;\n}\n\n// alien-signals' ReactiveFlags (a const enum in its types, so mirrored here).\nconst NONE = 0;\nconst MUTABLE = 1;\nconst WATCHING = 2;\nconst RECURSED_CHECK = 4;\nconst RECURSED = 8;\nconst DIRTY = 16;\nconst PENDING = 32;\n\nconst SIGNAL = 0;\nconst COMPUTED = 1;\nconst EFFECT = 2;\n\n/** Runs of one effect within one flush before the graph is declared to be looping. */\nconst MAX_RUNS_PER_FLUSH = 100;\n\ninterface Node extends ReactiveNode {\n readonly kind: typeof SIGNAL | typeof COMPUTED | typeof EFFECT;\n}\n\nlet cycle = 0;\nlet runDepth = 0;\nlet batchDepth = 0;\nlet flushing = false;\nlet flushId = 0;\nlet activeSub: Node | undefined;\nconst queue: (EffectNode | undefined)[] = [];\nlet queueHead = 0;\n\nconst { link, unlink, propagate, checkDirty, shallowPropagate } = createReactiveSystem({\n update(node) {\n return (node as Node).kind === COMPUTED\n ? updateComputed(node as ComputedNode<unknown>)\n : updateSignal(node as SignalNode<unknown>);\n },\n notify(node) {\n // Not watching until it has run: further writes mark it but don't queue it again.\n node.flags &= ~WATCHING;\n queue.push(node as EffectNode);\n },\n unwatched(node) {\n const n = node as Node;\n if (n.kind === COMPUTED) {\n // Nobody observes it any more: let go of its sources; the next read recomputes.\n if (n.depsTail !== undefined) {\n n.flags = MUTABLE | DIRTY;\n disposeDeps(n);\n }\n } else if (n.kind === EFFECT) {\n (n as EffectNode).dispose();\n }\n },\n});\n\nclass SignalNode<T> implements Signal<T>, Node {\n readonly kind = SIGNAL;\n deps: Link | undefined = undefined;\n depsTail: Link | undefined = undefined;\n subs: Link | undefined = undefined;\n subsTail: Link | undefined = undefined;\n flags = MUTABLE;\n current: T;\n pending: T;\n readonly equals: Equals<T> | false;\n\n constructor(value: T, equals: Equals<T> | false) {\n this.current = value;\n this.pending = value;\n this.equals = equals;\n }\n\n get value(): T {\n const value = this.peek();\n if (activeSub !== undefined) link(this, activeSub, cycle);\n return value;\n }\n\n set value(next: T) {\n if (activeSub !== undefined && activeSub.kind === COMPUTED) {\n throw new Error(\"motion: a computed value can't write a signal\");\n }\n if (this.equals !== false && this.equals(this.pending, next)) return;\n this.pending = next;\n this.flags = MUTABLE | DIRTY;\n const subs = this.subs;\n if (subs === undefined) return;\n propagate(subs, runDepth > 0);\n if (batchDepth === 0) flush();\n }\n\n peek(): T {\n if (this.flags & DIRTY && updateSignal(this)) {\n const subs = this.subs;\n if (subs !== undefined) shallowPropagate(subs);\n }\n return this.current;\n }\n}\n\nfunction updateSignal<T>(node: SignalNode<T>): boolean {\n node.flags = MUTABLE;\n const previous = node.current;\n node.current = node.pending;\n return node.equals === false || !node.equals(previous, node.current);\n}\n\nclass ComputedNode<T> implements ReadonlySignal<T>, Node {\n readonly kind = COMPUTED;\n deps: Link | undefined = undefined;\n depsTail: Link | undefined = undefined;\n subs: Link | undefined = undefined;\n subsTail: Link | undefined = undefined;\n flags = NONE;\n current: T | undefined = undefined;\n failed = false;\n error: unknown = undefined;\n readonly getter: (previous: T | undefined) => T;\n readonly equals: Equals<T> | false;\n\n constructor(getter: (previous: T | undefined) => T, equals: Equals<T> | false) {\n this.getter = getter;\n this.equals = equals;\n }\n\n get value(): T {\n refreshComputed(this);\n if (activeSub !== undefined) link(this, activeSub, cycle);\n if (this.failed) throw this.error;\n return this.current as T;\n }\n\n peek(): T {\n refreshComputed(this);\n if (this.failed) throw this.error;\n return this.current as T;\n }\n}\n\nfunction refreshComputed<T>(node: ComputedNode<T>): void {\n const flags = node.flags;\n if (flags & RECURSED_CHECK) throw new Error(\"motion: a computed value depends on itself\");\n if (flags & DIRTY || (flags & PENDING && (checkDirty(node.deps!, node) || ((node.flags = flags & ~PENDING), false)))) {\n if (updateComputed(node)) {\n const subs = node.subs;\n if (subs !== undefined) shallowPropagate(subs);\n }\n } else if (flags === NONE) {\n // First read.\n node.flags = MUTABLE | RECURSED_CHECK;\n const previous = activeSub;\n activeSub = node;\n try {\n ++cycle;\n node.current = node.getter(undefined);\n } catch (error) {\n node.failed = true;\n node.error = error;\n } finally {\n activeSub = previous;\n node.flags &= ~RECURSED_CHECK;\n }\n }\n}\n\n/** Recompute; returns whether the value (or the error state) changed. */\nfunction updateComputed<T>(node: ComputedNode<T>): boolean {\n node.depsTail = undefined;\n node.flags = MUTABLE | RECURSED_CHECK;\n const previousSub = activeSub;\n activeSub = node;\n try {\n ++cycle;\n const previous = node.current;\n let next: T;\n try {\n next = node.getter(previous);\n } catch (error) {\n node.failed = true;\n node.error = error;\n return true;\n }\n if (node.failed) {\n node.failed = false;\n node.error = undefined;\n node.current = next;\n return true;\n }\n if (node.equals !== false && node.equals(previous as T, next)) return false;\n node.current = next;\n return true;\n } finally {\n activeSub = previousSub;\n node.flags &= ~RECURSED_CHECK;\n purgeDeps(node);\n }\n}\n\nclass EffectNode implements Node {\n readonly kind = EFFECT;\n deps: Link | undefined = undefined;\n depsTail: Link | undefined = undefined;\n subs: Link | undefined = undefined;\n subsTail: Link | undefined = undefined;\n flags = DIRTY;\n cleanup: EffectCleanup | undefined = undefined;\n disposed = false;\n lastFlush = 0;\n runsInFlush = 0;\n readonly fn: () => void | EffectCleanup;\n readonly schedule: ((run: () => void) => void) | undefined;\n /** A scheduled run: the effect, then whatever its writes triggered. */\n readonly run: () => void;\n\n constructor(fn: () => void | EffectCleanup, schedule: ((run: () => void) => void) | undefined) {\n this.fn = fn;\n this.schedule = schedule;\n this.run = () => {\n if (this.disposed) return;\n batchDepth++;\n try {\n runEffect(this);\n } finally {\n endBatch();\n }\n };\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.flags = NONE;\n disposeDeps(this);\n if (this.cleanup !== undefined) runCleanup(this);\n }\n}\n\nfunction runEffect(node: EffectNode): void {\n const flags = node.flags;\n if (flags & DIRTY || (flags & PENDING && checkDirty(node.deps!, node))) {\n if (node.cleanup !== undefined) {\n runCleanup(node);\n if (node.disposed) return;\n }\n node.depsTail = undefined;\n node.flags = WATCHING | RECURSED_CHECK;\n const previous = activeSub;\n activeSub = node;\n try {\n ++cycle;\n ++runDepth;\n const cleanup = node.fn();\n node.cleanup = typeof cleanup === \"function\" ? cleanup : undefined;\n } finally {\n --runDepth;\n activeSub = previous;\n node.flags &= ~RECURSED_CHECK;\n purgeDeps(node);\n // It disposed itself during the run: drop whatever it read after that.\n if (node.disposed) disposeDeps(node);\n }\n } else if (!node.disposed) {\n node.flags = WATCHING;\n }\n}\n\nfunction runCleanup(node: EffectNode): void {\n const cleanup = node.cleanup!;\n node.cleanup = undefined;\n const previous = activeSub;\n activeSub = undefined;\n try {\n cleanup();\n } finally {\n activeSub = previous;\n }\n}\n\nfunction disposeDeps(node: ReactiveNode): void {\n let dep = node.depsTail;\n while (dep !== undefined) {\n const previous = dep.prevDep;\n unlink(dep, node);\n dep = previous;\n }\n}\n\nfunction purgeDeps(node: ReactiveNode): void {\n const tail = node.depsTail;\n let dep = tail !== undefined ? tail.nextDep : node.deps;\n while (dep !== undefined) dep = unlink(dep, node);\n}\n\nfunction endBatch(): void {\n if (--batchDepth === 0) flush();\n}\n\nfunction flush(): void {\n if (flushing) return;\n flushing = true;\n batchDepth++;\n const id = ++flushId;\n let failed = false;\n let error: unknown;\n try {\n while (queueHead < queue.length) {\n const node = queue[queueHead]!;\n queue[queueHead++] = undefined;\n if (node.disposed) continue;\n try {\n if (node.schedule !== undefined) {\n node.schedule(node.run);\n continue;\n }\n if (node.lastFlush !== id) {\n node.lastFlush = id;\n node.runsInFlush = 0;\n }\n if (++node.runsInFlush > MAX_RUNS_PER_FLUSH) {\n // Leave it watching so a later change still reaches it.\n node.flags |= WATCHING | RECURSED;\n throw new Error(`motion: effects kept re-triggering each other (one ran more than ${MAX_RUNS_PER_FLUSH} times)`);\n }\n runEffect(node);\n } catch (caught) {\n if (!failed) {\n failed = true;\n error = caught;\n }\n }\n }\n } finally {\n queue.length = 0;\n queueHead = 0;\n batchDepth--;\n flushing = false;\n }\n if (failed) throw error;\n}\n\n/** A writable reactive value. */\nexport function signal<T>(initial: T, options?: SignalOptions<T>): Signal<T> {\n return new SignalNode(initial, options?.equals ?? Object.is);\n}\n\n/**\n * A value derived from other signals. It recomputes lazily, on read, and only\n * when a source changed; `fn` gets the previous value. If `fn` throws, reading\n * the computed throws the same error until a source changes.\n */\nexport function computed<T>(fn: (previous: T | undefined) => T, options?: SignalOptions<T>): ReadonlySignal<T> {\n return new ComputedNode(fn, options?.equals ?? Object.is);\n}\n\n/**\n * Run `fn` now (or through `options.schedule`) and again whenever a signal it\n * read changes. Returns `dispose`. If the first synchronous run throws, the\n * effect is disposed and the error rethrown.\n */\nexport function effect(fn: () => void | EffectCleanup, options?: EffectOptions): () => void {\n const node = new EffectNode(fn, options?.schedule);\n const dispose = (): void => node.dispose();\n if (node.schedule !== undefined) {\n node.schedule(node.run);\n return dispose;\n }\n try {\n node.run();\n } catch (error) {\n node.dispose();\n throw error;\n }\n return dispose;\n}\n\n/** Run `fn` with effects held until it returns; nested batches flush at the outermost end. */\nexport function batch<T>(fn: () => T): T {\n batchDepth++;\n try {\n return fn();\n } finally {\n endBatch();\n }\n}\n\n/** Run `fn` without tracking what it reads. */\nexport function untracked<T>(fn: () => T): T {\n const previous = activeSub;\n activeSub = undefined;\n try {\n return fn();\n } finally {\n activeSub = previous;\n }\n}\n\n/** Whether `value` is a signal or a computed value made by this module. */\nexport function isSignal(value: unknown): value is ReadonlySignal<unknown> {\n return value instanceof SignalNode || value instanceof ComputedNode;\n}\n"],"mappings":";AAyBA,SAAS,4BAA0D;AAyCnE,IAAM,OAAO;AACb,IAAM,UAAU;AAChB,IAAM,WAAW;AACjB,IAAM,iBAAiB;AACvB,IAAM,WAAW;AACjB,IAAM,QAAQ;AACd,IAAM,UAAU;AAEhB,IAAM,SAAS;AACf,IAAM,WAAW;AACjB,IAAM,SAAS;AAGf,IAAM,qBAAqB;AAM3B,IAAI,QAAQ;AACZ,IAAI,WAAW;AACf,IAAI,aAAa;AACjB,IAAI,WAAW;AACf,IAAI,UAAU;AACd,IAAI;AACJ,IAAM,QAAoC,CAAC;AAC3C,IAAI,YAAY;AAEhB,IAAM,EAAE,MAAM,QAAQ,WAAW,YAAY,iBAAiB,IAAI,qBAAqB;AAAA,EACrF,OAAO,MAAM;AACX,WAAQ,KAAc,SAAS,WAC3B,eAAe,IAA6B,IAC5C,aAAa,IAA2B;AAAA,EAC9C;AAAA,EACA,OAAO,MAAM;AAEX,SAAK,SAAS,CAAC;AACf,UAAM,KAAK,IAAkB;AAAA,EAC/B;AAAA,EACA,UAAU,MAAM;AACd,UAAM,IAAI;AACV,QAAI,EAAE,SAAS,UAAU;AAEvB,UAAI,EAAE,aAAa,QAAW;AAC5B,UAAE,QAAQ,UAAU;AACpB,oBAAY,CAAC;AAAA,MACf;AAAA,IACF,WAAW,EAAE,SAAS,QAAQ;AAC5B,MAAC,EAAiB,QAAQ;AAAA,IAC5B;AAAA,EACF;AACF,CAAC;AAED,IAAM,aAAN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","../src/layout/anchored.ts"],"sourcesContent":["import type { FrameInfo, FrameLoop, Phase } from \"../clock/frame-loop\";\nimport type { Rect } from \"../shapes\";\nimport { popIn, reveal, type PopIn, type RevealFrame } from \"../values/reveal\";\nimport { createSettle, SETTLE_TEMPO, type Settle } from \"../values/settle\";\n\n/**\n * What a {@link Drawable} draws on a frame: where the item is drawn, the box its content is laid out in, how to draw\n * the one at the other without stretching ({@link reveal}), and its appearance ({@link popIn}).\n */\nexport interface DrawFrame {\n /** Where the item is drawn this frame (its frame: background, border, shadow). */\n readonly drawn: Rect;\n /** The box its content is laid out in: where it is heading, or (held) where it was laid out last. */\n readonly box: Rect;\n /** How to draw `box`'s content at `drawn`: a move, the frame at the drawn size, the content clipped. */\n readonly reveal: RevealFrame;\n /** Its uniform appearance: scale about its center and opacity. */\n readonly pop: PopIn;\n /** How shown it is, 0 (gone) to 1. */\n readonly shown: number;\n /** All the way gone: hidden and at rest (out of sight and out of the way of the pointer). */\n readonly gone: boolean;\n}\n\n/**\n * How an item reaches the screen. The layout motion never measures or touches anything itself: it lays an item's\n * content out once per new box and draws it once per frame through this. {@link domDrawable} writes an element's\n * style; a canvas or a test can draw anything else.\n */\nexport interface Drawable {\n /** Lay the content out in `box` (its position and size): called once per new box, never per frame. */\n layOut(box: Rect): void;\n /** Draw the item for this frame. */\n draw(frame: DrawFrame): void;\n}\n\n/**\n * One item the layout motion moves: give it a new place and it settles there from wherever it is drawn, once a frame\n * has shown it there.\n *\n * - {@link LayoutItem.moveTo}: a settle to the new place, retargeted from the drawn rect (no jump, no overshoot);\n * the content is laid out at the new box at once and the item redrawn at once, so no frame shows the old offset\n * from the new box.\n * - Seen: a rect placed by a jump ({@link LayoutMotion.add}, {@link LayoutItem.jumpTo}) is seen once a frame of the\n * loop has ended after it reached the screen (drawn; batched, written). A new target before that is a jump too: no\n * frame showed the rect a glide would start from, so the first frame shows the final place. `jumpTo` and `add` say\n * \"be here\", and motion checks them; `hold` and `glideFrom` say \"it is on screen here\", and motion believes them.\n * - A size change is revealed: the content is laid out at the target size and the frame clipped, never scaled.\n * - {@link LayoutItem.show}: appear or disappear with a uniform-scale fade.\n */\nexport interface LayoutItem {\n readonly id: string;\n /** Where it is drawn now. */\n readonly drawn: Rect;\n /** Where it is heading (its settle's target). */\n readonly target: Rect;\n /** The box its content is laid out in. */\n readonly box: Rect;\n /** At rest on its target. */\n readonly settled: boolean;\n /** How shown it is, 0 to 1, and whether it is heading for shown. */\n readonly shown: number;\n readonly showing: boolean;\n /** Its appearance is at rest (fully shown, or gone). */\n readonly shownSettled: boolean;\n /**\n * Settle to `to` from where it is drawn; lays the content out at `to` and redraws at once. While the drawn rect was\n * placed by a jump and is not seen yet, this is a jump to `to` instead.\n */\n moveTo(to: Rect): void;\n /**\n * Settle to `to` from where it is drawn, like {@link LayoutItem.moveTo}, but keep the content laid out in its box\n * while `to` is the box's size: for chasing a moving point (a pointer), which would otherwise lay the content out\n * again on every frame. A new size lays it out at `to`, as `moveTo` does. Optional, so an item from before it (or\n * a test double) still works where it is used: {@link holdItem} falls back to `moveTo`. `createLayoutMotion`'s\n * items always have it. Before a jumped rect is seen, a jump, as for `moveTo`.\n */\n retarget?(to: Rect): void;\n /**\n * Be at `to` now, at rest: no glide. `jumpTo` and `add` say \"be here\", and motion checks them; `hold` and\n * `glideFrom` say \"it is on screen here\", and motion believes them: `to` is seen once a frame has ended after it,\n * and a target given before that jumps too.\n */\n jumpTo(to: Rect): void;\n /**\n * Drawn at `from` now, then settle to `to` (a FLIP's invert and play: `from` in the item's own coordinates). The way\n * to animate an entrance. `jumpTo` and `add` say \"be here\", and motion checks them; `hold` and `glideFrom` say \"it\n * is on screen here\", and motion believes them: `from` counts as seen, and a new target glides on from the drawn\n * rect.\n */\n glideFrom(from: Rect, to: Rect): void;\n /**\n * Exactly at `r`, at rest (what a pointer holds); the content stays laid out in its box, moved with it. `jumpTo` and\n * `add` say \"be here\", and motion checks them; `hold` and `glideFrom` say \"it is on screen here\", and motion believes\n * them: `r` counts as seen, and a drop right after it glides. Never hold a rect that was not on screen to get a glide.\n */\n hold(r: Rect): void;\n /** Appear (true) or disappear (false) with a uniform-scale fade; `now`: without the fade. */\n show(on: boolean, options?: { readonly now?: boolean }): void;\n /** Draw it again now (after its drawable's element was laid out anew from outside). */\n redraw(): void;\n}\n\n/** A task the layout motion runs on every frame before it steps the items; true keeps the frames coming. */\nexport type LayoutTask = (frame: FrameInfo) => boolean | void;\n\n/** One item's frame in a batch ({@link LayoutMotionOptions.onDraw}). */\nexport interface DrawEntry {\n readonly id: string;\n readonly frame: DrawFrame;\n}\n\nexport interface LayoutMotionOptions {\n /** The frame loop every item steps on (one loop for all of them). */\n readonly loop: FrameLoop;\n /** The settle tempo, per second ({@link SETTLE_TEMPO}); default `SETTLE_TEMPO.default`. */\n readonly omega?: number;\n /** The frame phase the items step and draw in; default `\"layout\"`. */\n readonly phase?: Phase;\n /** Where an appearing item grows from, as a share of its size ({@link popIn}'s `from`); default 0.87. */\n readonly popFrom?: number;\n /**\n * Reduced motion: read on every new target and every show or hide. While true an item is placed on its new\n * target at once (no glide) and appears or disappears at once (no fade). A boolean, or the host's query (such as\n * the reduced-motion media query). Default false.\n */\n readonly reducedMotion?: boolean | (() => boolean);\n /**\n * Batched drawing: every item that changed is drawn in one pass per frame, after the items step: each one's\n * drawable, then this, once, with all of their frames. Changes made between frames (a new target, a hold) are\n * drawn on the next frame, or now by {@link LayoutMotion.flush}. Without it, each item is drawn as it changes.\n */\n readonly onDraw?: (batch: readonly DrawEntry[]) => void;\n /**\n * Called when frames start running (true) and when they stop (false: nothing moves any more), once per change, and\n * with false on `dispose` while they run. The one way to learn that the layout is idle; a test awaits\n * {@link LayoutMotion.idle} instead.\n */\n readonly onActiveChange?: (active: boolean) => void;\n}\n\n/**\n * Layout motion: items with an id and a target rect, each settled to its place on one shared frame loop.\n *\n * Give an item a new place ({@link LayoutItem.moveTo}) and it glides there from wherever it is drawn: the window\n * motion rules of `values/` (settle, reveal, popIn) applied to every item at once. The loop runs only while\n * something moves, or a task asks for frames, and stops by itself.\n *\n * A rect placed by a jump glides on only once it is seen: a frame of the loop has ended after it reached the screen\n * (see {@link LayoutItem}). An unbatched jump asks the loop for that one frame as a task, once per burst of jumps:\n * `loop.active` and the loop's queue count show it, as they show any scheduled task, but it is not a movement, so\n * `onActiveChange` is not called and {@link LayoutMotion.idle} does not wait for it. \"Seen\" is the clock's word: a\n * frame is the clock's statement that what was drawn before it ended is now presented (`ClockPort.requestFrame`).\n *\n * It only animates the rects it is given: which items move where, and when, is the caller's layout.\n */\nexport interface LayoutMotion {\n /**\n * Add an item drawn by `drawable`, at `at`, shown (or gone: `{ shown: false }`). Its content is laid out at once.\n * `jumpTo` and `add` say \"be here\", and motion checks them; `hold` and `glideFrom` say \"it is on screen here\", and\n * motion believes them: a target given before a frame has seen `at` is a jump. To animate an entrance, add it at its\n * place and {@link LayoutItem.glideFrom} where it comes from.\n */\n add(id: string, drawable: Drawable, at: Rect, options?: { readonly shown?: boolean }): LayoutItem;\n get(id: string): LayoutItem | undefined;\n /** Stop moving an item (its drawable is not touched again). */\n remove(id: string): void;\n /** Remove every item whose id is not in `ids` (the ones that left the layout). */\n retain(ids: Iterable<string>): void;\n /**\n * With {@link LayoutMotionOptions.onDraw}: draw the items changed since the last frame now, outside the loop. A\n * host calls it right after it commits a new layout, so the next paint shows every item where it is drawn, not a\n * frame at its new box. Without batching each item is already drawn as it changes, and it does nothing. It hands\n * the batch to the host but ends no frame: a jump flushed and then given a target still jumps.\n */\n flush(): void;\n readonly items: ReadonlyMap<string, LayoutItem>;\n /** Run `task` on every frame, before the items step; returns how to stop it. */\n task(task: LayoutTask): () => void;\n /** Call `listener` on every frame, after the items have stepped and been drawn; returns how to stop it. */\n onFrame(listener: (frame: FrameInfo) => void): () => void;\n /** Make sure at least one more frame runs (a task has something to do). */\n wake(): void;\n /** Set the tempo for every item (and the ones added later). */\n configure(config: { readonly omega?: number }): void;\n /**\n * Resolves once nothing moves (at once if nothing does): for a test. A host learns it from\n * {@link LayoutMotionOptions.onActiveChange}. Right after a jump it resolves at once, before the frame that sees the\n * jump: a target given then is still a jump. A test that means \"drawn and seen\" runs a frame (`clock.frame()`).\n */\n idle(): Promise<void>;\n /** Stop the frames and forget every item. */\n dispose(): void;\n}\n\n/** Two rects the same within a hundredth of a pixel. */\nconst same = (a: Rect, b: Rect): boolean =>\n Math.abs(a.x - b.x) < 0.01 && Math.abs(a.y - b.y) < 0.01 && Math.abs(a.width - b.width) < 0.01 && Math.abs(a.height - b.height) < 0.01;\nconst copy = (r: Rect): Rect => ({ x: r.x, y: r.y, width: r.width, height: r.height });\n\n/** Create the {@link LayoutMotion} for one surface. */\nexport function createLayoutMotion(options: LayoutMotionOptions): LayoutMotion {\n const { loop } = options;\n const phase = options.phase ?? \"layout\";\n const popFrom = options.popFrom ?? 0.87;\n let omega = options.omega ?? SETTLE_TEMPO.default;\n const items = new Map<string, LayoutItem>();\n const steps = new Map<string, (dt: number) => boolean>();\n const tasks = new Set<LayoutTask>();\n const frames = new Set<(frame: FrameInfo) => void>();\n const tempos = new Set<() => void>();\n /** What removing an item undoes besides its entry (its tempo hook). */\n const removers = new Map<string, () => void>();\n let waiters: (() => void)[] = [];\n let stop: (() => void) | null = null;\n let woken = false;\n let ticking = false;\n let active = false;\n const reduced = (): boolean => (typeof options.reducedMotion === \"function\" ? options.reducedMotion() : options.reducedMotion === true);\n const { onDraw, onActiveChange } = options;\n /** Batched drawing: how to draw each item, and the ones that changed since the last batch. */\n const drawers = new Map<string, () => DrawEntry>();\n const dirty = new Set<string>();\n /**\n * Items whose drawn rect was placed by a jump and is not seen yet: the count of the loop's ended frames when the\n * rect reached the screen (unbatched: drawn at the jump; batched: written by a batch), or null while no batch has\n * written it. The loop counts a frame only after all of its phases ran, so the rect is seen once that count has\n * grown, and a target later in the same frame, in any phase or order, still jumps. The count is `framesEnded`,\n * which `resetStats()` never touches.\n */\n const unseen = new Map<string, number | null>();\n /** Cancels the frame asked for to see the unbatched jumps, while it is pending. */\n let seeing: (() => void) | null = null;\n const ended = (): number => loop.framesEnded;\n /** The one function the frame to see jumps runs, so a burst of jumps queues one task. */\n const sawFrame = (): void => {\n seeing = null;\n };\n /** A rect placed by a jump (\"be here\"). Under reduced motion every target is a jump already: nothing to record. */\n const jumped = (id: string): void => {\n if (reduced()) return;\n unseen.set(id, onDraw ? null : ended());\n if (!onDraw && !seeing) seeing = loop.schedule(\"write\", sawFrame);\n };\n const isUnseen = (id: string): boolean => {\n const at = unseen.get(id);\n if (at === undefined) return false;\n if (at === null || at === ended()) return true;\n unseen.delete(id);\n return false;\n };\n /**\n * The caller says it is on screen (`hold`, `glideFrom`), or it left. When no jump is left to see, the frame asked\n * for them is cancelled, so a loop shared with other work isn't kept busy by this one.\n */\n const seen = (id: string): void => {\n unseen.delete(id);\n if (!seeing) return;\n const now = ended();\n for (const [other, at] of unseen) if (at !== null && at !== now) unseen.delete(other);\n if (unseen.size === 0) {\n seeing();\n seeing = null;\n }\n };\n\n const setActive = (on: boolean): void => {\n if (on === active) return;\n active = on;\n onActiveChange?.(on);\n };\n\n const wake = (): void => {\n woken = true;\n if (stop) return;\n stop = loop.repeat(phase, tick);\n setActive(true);\n };\n\n /** Draw every item that changed, then hand the batch over once. */\n function writeBatch(): void {\n if (!onDraw || dirty.size === 0) return;\n const batch: DrawEntry[] = [];\n for (const id of dirty) {\n const entry = drawers.get(id)?.();\n if (entry) batch.push(entry);\n // A jumped rect reaches the screen when a batch writes it.\n if (unseen.get(id) === null) unseen.set(id, ended());\n }\n dirty.clear();\n if (batch.length > 0) onDraw(batch);\n }\n\n function tick(frame: FrameInfo): boolean {\n let moving = woken;\n woken = false;\n ticking = true;\n for (const task of [...tasks]) if (task(frame)) moving = true;\n for (const step of [...steps.values()]) if (step(frame.delta)) moving = true;\n writeBatch();\n ticking = false;\n for (const listener of [...frames]) listener(frame);\n if (moving || woken) return true;\n stop = null;\n setActive(false);\n const resolve = waiters;\n waiters = [];\n for (const r of resolve) r();\n return false;\n }\n\n function add(id: string, drawable: Drawable, at: Rect, opts: { readonly shown?: boolean } = {}): LayoutItem {\n if (items.has(id)) throw new Error(`layout motion: item \"${id}\" is already added (remove it first)`);\n const rect: Settle<Rect> = createSettle<Rect>(copy(at), { omega });\n // A number from 0 to 1: rest within a thousandth, not the default tenth (tuned for pixels).\n const pop: Settle<number> = createSettle(opts.shown === false ? 0 : 1, { omega, restDelta: 0.001 });\n let box = copy(at);\n const frameOf = (): DrawFrame => {\n const drawn = rect.value;\n return { drawn, box, reveal: reveal(drawn, box), pop: popIn(pop.value, popFrom), shown: pop.value, gone: pop.settled && pop.value === 0 };\n };\n const drawNow = (): DrawEntry => {\n const frame = frameOf();\n drawable.draw(frame);\n return { id, frame };\n };\n // Batched: mark it changed (the batch draws it); a change between frames asks for a frame to draw it in.\n const draw = (): void => {\n if (!onDraw) {\n drawNow();\n return;\n }\n dirty.add(id);\n if (!ticking) wake();\n };\n const layOut = (to: Rect): void => {\n box = copy(to);\n drawable.layOut(box);\n };\n /** Head for `to`: a settle from the drawn rect, or (reduced motion) there at once. */\n const aim = (to: Rect): void => {\n if (reduced()) {\n rect.jumpTo(copy(to));\n draw();\n return;\n }\n rect.setTarget(copy(to));\n wake();\n };\n /** It moved on the last step (so the step that brings it to rest still draws it, batched). */\n let moved = false;\n const tempo = (): void => {\n rect.configure({ omega });\n pop.configure({ omega });\n };\n const item: LayoutItem = {\n id,\n get drawn() {\n return rect.value;\n },\n get target() {\n return rect.target;\n },\n get box() {\n return box;\n },\n get settled() {\n return rect.settled;\n },\n get shown() {\n return pop.value;\n },\n get showing() {\n return pop.target === 1;\n },\n get shownSettled() {\n return pop.settled;\n },\n moveTo(to) {\n if (same(box, to) && same(rect.target, to)) return;\n // Placed by a jump and not seen yet: no frame showed where a glide would start, so this is a jump too.\n if (isUnseen(id)) {\n item.jumpTo(to);\n return;\n }\n layOut(to);\n // Laid out in the new box now: draw it at once at the drawn rect, else until the next frame it would show\n // the old offset from the new box (a dropped item would flash a frame away from where it was let go).\n draw();\n if (same(rect.target, to)) return;\n aim(to);\n },\n retarget(to) {\n if (to.width !== box.width || to.height !== box.height) {\n item.moveTo(to);\n return;\n }\n if (same(rect.target, to)) return;\n // Not seen yet: a jump, keeping the content laid out in its box as a retarget does.\n if (isUnseen(id)) {\n rect.jumpTo(copy(to));\n draw();\n jumped(id);\n return;\n }\n aim(to);\n },\n jumpTo(to) {\n layOut(to);\n rect.jumpTo(copy(to));\n draw();\n jumped(id);\n },\n glideFrom(from, to) {\n rect.jumpTo(copy(from));\n layOut(to);\n draw();\n aim(to);\n // The caller's word: `from` is on screen.\n seen(id);\n },\n hold(r) {\n rect.jumpTo(copy(r));\n draw();\n // The caller's word: `r` is on screen (where the pointer holds it), so a drop right after it glides.\n seen(id);\n },\n show(on, o = {}) {\n const want = on ? 1 : 0;\n if (o.now || reduced()) pop.jumpTo(want);\n else if (pop.target !== want) {\n pop.setTarget(want);\n wake();\n }\n draw();\n },\n redraw: draw,\n };\n drawers.set(id, drawNow);\n drawable.layOut(box);\n draw();\n items.set(id, item);\n // Placed at once: an add says \"be here\", like a jump.\n jumped(id);\n tempos.add(tempo);\n steps.set(id, (dt) => {\n const a = rect.step(dt);\n const b = pop.step(dt);\n // Batched, only an item that moved is drawn; else every item, every frame.\n if (!onDraw || a || b || moved) draw();\n moved = a || b;\n return a || b;\n });\n removers.set(id, () => {\n tempos.delete(tempo);\n drawers.delete(id);\n dirty.delete(id);\n });\n return item;\n }\n\n function remove(id: string): void {\n items.delete(id);\n steps.delete(id);\n removers.get(id)?.();\n removers.delete(id);\n seen(id);\n }\n\n return {\n add,\n get: (id) => items.get(id),\n remove,\n retain(ids) {\n const keep = new Set(ids);\n for (const id of [...items.keys()]) if (!keep.has(id)) remove(id);\n },\n flush: writeBatch,\n items,\n task(task) {\n tasks.add(task);\n wake();\n return () => tasks.delete(task);\n },\n onFrame(listener) {\n frames.add(listener);\n return () => frames.delete(listener);\n },\n wake,\n configure(config) {\n if (config.omega !== undefined) omega = config.omega;\n for (const t of tempos) t();\n },\n idle: () => (stop ? new Promise<void>((r) => waiters.push(r)) : Promise.resolve()),\n dispose() {\n stop?.();\n stop = null;\n setActive(false);\n items.clear();\n steps.clear();\n drawers.clear();\n dirty.clear();\n tasks.clear();\n frames.clear();\n tempos.clear();\n removers.clear();\n unseen.clear();\n seeing?.();\n seeing = null;\n const resolve = waiters;\n waiters = [];\n for (const r of resolve) r();\n },\n };\n}\n","import type { Point, Rect } from \"../shapes\";\nimport type { LayoutItem } from \"./motion\";\n\n/**\n * An item held by a pointer: the real item (no copy) follows the pointer 1:1 from where it was grabbed, at the size\n * it was lifted at; its place stays reserved (that is the caller's layout). Then:\n *\n * - {@link HeldDrag.snapTo}: glide into a slot (a snap preview); `null` leaves the slot and glides back to the\n * pointer, following it as it moves ({@link HeldDrag.follow} once a frame), until it is under it again.\n * - {@link HeldDrag.land}: let go into a slot: the landing settles from where it was let go (the release rect), never\n * from its old home. Snapped into that slot already, it simply finishes that glide.\n * - {@link HeldDrag.cancel}: let go with no drop: it glides home from where it was let go.\n * - {@link HeldDrag.preview}: the three drop previews, per frame: indicator and gap keep the item under the pointer\n * (gap with the caller's room open), snap glides it into the slot; leaving glides it back to the pointer.\n * - {@link HeldDrag.resize}: the item takes a new size mid-drag (its content laid out anew by the caller), held at the\n * caller's `grab` in it where given: it settles to it from where it is drawn, the size revealed (never stretched),\n * and is held 1:1 again once there.\n */\nexport interface HeldDrag {\n /** Where the pointer is (null before the first move). */\n readonly pointer: Point | null;\n /** Where the pointer holds the item: the pointer less the grab offset, at the held size (lifted, or resized). */\n readonly held: Rect | null;\n /** The slot it sits in (a snap), or null. */\n readonly snapped: Rect | null;\n /** It left a slot (or took a new size) and is gliding back to the pointer. */\n readonly returning: boolean;\n /** The pointer moved: held 1:1 (unless it sits in a slot or is on its way back). */\n move(pointer: Point): void;\n /**\n * Into `slot` (a glide from where it is drawn; the same slot again does nothing), or out of the slot it sits in\n * (`null`: back to the pointer). Returns what changed: `\"snapped\"`, `\"left\"`, or null.\n */\n snapTo(slot: Rect | null): \"snapped\" | \"left\" | null;\n /** Once a frame: on its way back, retarget to the pointer; true on the frame it is under the pointer again. */\n follow(): boolean;\n /**\n * Once a frame, a drop preview's part for the item (`plan`: `@n-uf/motion/drag`'s `previewPlan`, or any\n * `{ snapItem }`): with `snapItem` it glides into `slot` (snap); else it stays under the pointer, or glides back to\n * it from a slot it left (indicator, gap). The room, if the plan makes any, is the caller's layout. In place of\n * {@link HeldDrag.snapTo} and {@link HeldDrag.follow}; returns what changed.\n */\n preview(plan: { readonly snapItem: boolean }, slot: Rect | null): \"snapped\" | \"left\" | null;\n /**\n * Hold it at `size` from now on (the caller has laid its content out for that size), the pointer holding it at `grab`\n * (px from the top-left corner at that size: where the caller's new form puts the spot the user pressed, a docking\n * drag's `DockAfter.grab`). Without `grab` the grab point keeps its share of the item. The item settles from where it\n * is drawn to its new held rect, the pointer less `grab` at `size` (its size revealed, never stretched): the held\n * point moves with the size on that one settle, so a still pointer sees both arrive together. Then it is held 1:1\n * again ({@link HeldDrag.follow} once a frame). In a slot it stays there, taking the new size when it leaves. The same\n * size and grab again do nothing; returns true on a change.\n */\n resize(size: { readonly width: number; readonly height: number }, grab?: Point): boolean;\n /** Where the pointer holds the item now, px from its top-left corner at the held size (the lift's, or the last resize's). */\n readonly grab: Point;\n /** Let go into `slot`: returns the release rect, where the landing starts. */\n land(slot: Rect): Rect;\n /** Let go with no drop: glides `home` from the release rect, which it returns. */\n cancel(home: Rect): Rect;\n}\n\n/** How close (px, every component) the way back has to come to count as under the pointer again. */\nconst CAUGHT = 0.5;\n\n/** Hold `item` from the pointer at `grab` (the pointer's offset from its top-left corner), at its drawn size now. */\nexport function holdItem(item: LayoutItem, grab: Point): HeldDrag {\n let size = { width: item.drawn.width, height: item.drawn.height };\n let at = { x: grab.x, y: grab.y };\n let pointer: Point | null = null;\n let snapped: Rect | null = null;\n let returning = false;\n const heldRect = (): Rect | null => (pointer ? { x: pointer.x - at.x, y: pointer.y - at.y, width: size.width, height: size.height } : null);\n const same = (a: Rect, b: Rect): boolean => Math.max(Math.abs(a.x - b.x), Math.abs(a.y - b.y), Math.abs(a.width - b.width), Math.abs(a.height - b.height)) < 0.01;\n const snapTo = (slot: Rect | null): \"snapped\" | \"left\" | null => {\n if (slot) {\n if (snapped && same(snapped, slot)) return null;\n snapped = { ...slot };\n returning = false;\n item.moveTo(slot);\n return \"snapped\";\n }\n if (!snapped) return null;\n snapped = null;\n returning = true;\n return \"left\";\n };\n const follow = (): boolean => {\n const goal = heldRect();\n if (!returning || !goal) return false;\n // A chase of the pointer: retargeted every frame, laid out again only when its size changes (an item without\n // retarget, from before it or a test double, moves to it).\n if (item.retarget) item.retarget(goal);\n else item.moveTo(goal);\n const d = item.drawn;\n if (Math.max(Math.abs(d.x - goal.x), Math.abs(d.y - goal.y), Math.abs(d.width - goal.width), Math.abs(d.height - goal.height)) >= CAUGHT) return false;\n returning = false;\n item.hold(goal);\n return true;\n };\n const letGo = (to: Rect): Rect => {\n const release = { ...item.drawn };\n snapped = null;\n returning = false;\n item.moveTo(to);\n return release;\n };\n return {\n get pointer() {\n return pointer;\n },\n get held() {\n return heldRect();\n },\n get snapped() {\n return snapped;\n },\n get returning() {\n return returning;\n },\n move(p) {\n pointer = { x: p.x, y: p.y };\n if (snapped || returning) return;\n item.hold(heldRect()!);\n },\n snapTo,\n follow,\n preview(plan, slot) {\n const change = snapTo(plan.snapItem && slot ? slot : null);\n follow();\n return change;\n },\n get grab() {\n return { x: at.x, y: at.y };\n },\n resize(next, grab) {\n const sameSize = Math.abs(next.width - size.width) < 0.01 && Math.abs(next.height - size.height) < 0.01;\n if (sameSize && (!grab || (Math.abs(grab.x - at.x) < 0.01 && Math.abs(grab.y - at.y) < 0.01))) return false;\n // The caller's grab in the new form, else the old one's share of the item.\n at = grab ? { x: grab.x, y: grab.y } : { x: size.width ? (at.x / size.width) * next.width : 0, y: size.height ? (at.y / size.height) * next.height : 0 };\n size = { width: next.width, height: next.height };\n if (!snapped && pointer) {\n returning = true;\n follow();\n }\n return true;\n },\n land: letGo,\n cancel: letGo,\n };\n}\n","import type { Point, Rect } from \"../shapes\";\nimport { createSettle, SETTLE_TEMPO, type SettleConfig } from \"../values/settle\";\n\n/** A width and a height, px. */\nexport interface BoxSize {\n readonly width: number;\n readonly height: number;\n}\n\n/**\n * A box held at a point that changes size about an anchor: the anchor is the spot of the box that sits on the point\n * (a pointer's offset from the box's top-left corner). Its size and its anchor settle together to a new size and the\n * new box's anchor ({@link AnchoredMorph.to}), from wherever they are drawn, so a retarget mid-flight turns at once,\n * with no jump and no overshoot. At every step the anchor lies exactly on the point ({@link AnchoredMorph.rectAt}): a\n * caller who draws the old and the new content each with its own anchor on the point never moves either from under\n * the pointer, and fades between them by {@link AnchoredMorph.progress}.\n */\nexport interface AnchoredMorph {\n /** The size now. */\n readonly size: BoxSize;\n /** The anchor now: its offset from the box's top-left corner. */\n readonly anchor: Point;\n /** Where it is heading. */\n readonly target: { readonly size: BoxSize; readonly anchor: Point };\n /** At rest on the target. */\n readonly settled: boolean;\n /**\n * How far along the way from where the last retarget started to the target, 0 to 1 (1 at rest): to fade the content\n * it came from out and the target's in.\n */\n readonly progress: number;\n /** Head for `size` with `anchor` from where it is drawn. The same target again does nothing; true on a change. */\n to(size: BoxSize, anchor: Point): boolean;\n /** Be at `size` with `anchor` now, at rest. */\n jumpTo(size: BoxSize, anchor: Point): void;\n /** Advance by `dt` ms; true while still moving. */\n step(dt: number): boolean;\n /** The box now with its anchor on `point`. */\n rectAt(point: Point): Rect;\n}\n\n/**\n * The default tempo, a quick settle (`SETTLE_TEMPO.quick`): 90 % of the way in about 60 ms, within 1 % in about\n * 125 ms; the last pixels take longer for large size changes (a 300 px change rests after about 225 ms).\n */\nexport const MORPH_TEMPO = SETTLE_TEMPO.quick;\n\n/** A box of `size` held at `anchor`, at rest; `config` is the settle's (default tempo {@link MORPH_TEMPO}). */\nexport function anchoredMorph(size: BoxSize, anchor: Point, config: SettleConfig = {}): AnchoredMorph {\n // One settle over the four numbers, as a rect: x, y the anchor, width and height the size.\n const pack = (s: BoxSize, a: Point): Rect => ({ x: finite(a.x), y: finite(a.y), width: Math.max(0, finite(s.width)), height: Math.max(0, finite(s.height)) });\n const settle = createSettle<Rect>(pack(size, anchor), { omega: MORPH_TEMPO, ...config });\n let from: Rect = settle.value;\n const gap = (a: Rect, b: Rect): number => Math.max(Math.abs(a.x - b.x), Math.abs(a.y - b.y), Math.abs(a.width - b.width), Math.abs(a.height - b.height));\n return {\n get size() {\n const v = settle.value;\n return { width: v.width, height: v.height };\n },\n get anchor() {\n const v = settle.value;\n return { x: v.x, y: v.y };\n },\n get target() {\n const t = settle.target;\n return { size: { width: t.width, height: t.height }, anchor: { x: t.x, y: t.y } };\n },\n get settled() {\n return settle.settled;\n },\n get progress() {\n const whole = gap(from, settle.target);\n if (settle.settled || whole < 1e-9) return 1;\n return Math.min(1, Math.max(0, 1 - gap(settle.value, settle.target) / whole));\n },\n to(s, a) {\n const goal = pack(s, a);\n if (gap(goal, settle.target) < 0.01) return false;\n from = settle.value;\n settle.setTarget(goal);\n return true;\n },\n jumpTo(s, a) {\n settle.jumpTo(pack(s, a));\n from = settle.value;\n },\n step(dt) {\n return settle.step(dt);\n },\n rectAt(p) {\n const v = settle.value;\n return { x: p.x - v.x, y: p.y - v.y, width: v.width, height: v.height };\n },\n };\n}\n\nconst finite = (v: number): number => (Number.isFinite(v) ? v : 0);\n"],"mappings":";;;;;;;;AAoMA,IAAM,OAAO,CAAC,GAAS,MACrB,KAAK,IAAI,EAAE,IAAI,EAAE,CAAC,IAAI,QAAQ,KAAK,IAAI,EAAE,IAAI,EAAE,CAAC,IAAI,QAAQ,KAAK,IAAI,EAAE,QAAQ,EAAE,KAAK,IAAI,QAAQ,KAAK,IAAI,EAAE,SAAS,EAAE,MAAM,IAAI;AACpI,IAAM,OAAO,CAAC,OAAmB,EAAE,GAAG,EAAE,GAAG,GAAG,EAAE,GAAG,OAA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