@n-uf/motion 26.11.48 → 26.11.50

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 CHANGED
@@ -3,6 +3,61 @@
3
3
  Versions are calendar versions, `YY.M.R` (year, month of the release, counter
4
4
  within the month), the same scheme as `@n-uf/hypr-tiling`.
5
5
 
6
+ ## 26.11.50
7
+
8
+ Sliding spots: a free stretch exposed as one spot, where the item lands at the hand. With `@n-uf/placement`'s
9
+ `stretchPositions: "free"` (placement's default from this release). Host notes: additive; pass the press's `grab` to `createLandingModel`, draw `frame.landing`
10
+ (it moves with the pointer over a sliding spot) and commit a sliding spot through its target's `after(point, grab)`,
11
+ as for a float. A host that commits a spot by its id alone must pass the pointer for a sliding one.
12
+
13
+ - `./drag`, **`LandingSpot.slide`** (`LandingSlide`: `{ from, to, snaps, snapDistance? }`, additive): over a sliding
14
+ spot the frame's `landing` is the spot's landing moved along the lane to the pointer less the grab, clamped to
15
+ `[from, to]` and snapped to the nearest snap point within `snapDistance` (`SNAP_DISTANCE`, 8 px). No steps inside it;
16
+ passing a neighbor is still one step.
17
+ - `./drag`, **`LandingOptions.grab`** (additive): where the pointer holds the item, from its top left corner; default
18
+ the middle of `regions.item`.
19
+ - `./drag`, **`LandingRelease.at`** (additive): on a sliding spot, the landing's start along the lane, exactly as the
20
+ frame shows it (a snap point, else on the spot's `step`), read once at the release; `home` holds only at the
21
+ item's own place.
22
+ - `./drag`, **`LandingSlide.step`** (additive, default 1): the grain of a start that snaps to nothing, px, clamped to
23
+ `[from, to]` (0: wherever the pointer puts it). The frame, a release's `at` and the spot's own commit round by the
24
+ same step, so the rect a frame draws is the rect the drop commits; placement's spots carry `step: 1` (whole pixels).
25
+ A host that builds its own sliding spots and wants the old unrounded frame gives `step: 0`.
26
+ - `./drag`, **the lift zone is the item's own lane's** (fix): within `margins.lift` of the lift point the landing model
27
+ now takes `home.lane` as the lane whenever the pointer lies in it, whatever lane the pointer came through, and
28
+ `home.spot` as the spot (a sliding one still lets the landing follow the hand and snap). Before, only owning lanes (a rail drop strip) were kept out of the zone: a plain lane's
29
+ band lying over the home lane's corner (an empty bar over the top of a rail) kept the pointer on a slow return and
30
+ the release landed in that lane instead of home. Away and back to the lift point is home on every layout, at any
31
+ speed; within `lift` of the press no nudge to a neighboring spot is reachable. The zone is a held state with
32
+ hysteresis: the drag starts in it, leaves it past `margins.lift` and re-enters only within `margins.lift -
33
+ margins.spot`, so a wobble at its edge never flips a cut near the press.
34
+ - `./drag`, **`guideRects` keeps every guide `clearance` px clear of `clear`** (fix, `GuideRectsOptions.clearance`,
35
+ additive, default 2): a box never read `clear` and could touch the content (0 px); it is now cut on the side that faces
36
+ each clear rect (the rect grown by `clearance` taken out, the largest remaining part kept, none: dropped). A thin guide
37
+ keeps being thinned from the content side, now with the same 2 px gap (a strip beside content is 2 px thinner than
38
+ before, and may fall under `minThickness` and be left out). Clearance is per clear rect: `clear` takes `Rect |
39
+ ClearRect` (`{ rect, clearance, kinds? }`, additive type). A plain rect keeps the default gap for every kind; pass
40
+ `{ rect, clearance: 0 }` for content a thin guide may run flush against, which is the old thin-guide result, and `kinds:
41
+ ["line", "hatch"]` where a box may still lie over it (an empty lane's real-size box moves the content aside).
42
+
43
+ ## 26.11.49
44
+
45
+ Guides placed inside the window, and no "Can't go here" while the pointer enters a lane. With `@n-uf/placement`
46
+ 26.11.49. Host notes: draw guides through `guideRects` (or keep your own placing); nothing else changes for a host.
47
+
48
+ - `./drag`, **`guideRects(guides, { inside, inset?, clear?, minThickness? })`** (additive): where to draw guides
49
+ inside a window. Every guide lies inside `inside` by `inset` (2 px). A box is clipped. A thin guide (a line, a
50
+ striped strip or end: its shorter side is its thickness) keeps its thickness and moves inside rather than being
51
+ clipped, so a line at a lane's far end is as thick as at its head. It is then thinned from the content side to stay
52
+ clear of `clear` (the content), so a thin strip lies between the inset and the content, the same on both sides. A
53
+ thin guide under `minThickness` (2 px) is left out. A guide already in place comes back as given (the same object).
54
+ `GuideRectsOptions` and `PlacedGuide` are its types.
55
+ - `./drag`, **`pending` past a held lane's rect** (fix): a pointer coming from a refused stretch of a column into a
56
+ docked rail beside it showed "Can't go here" in the rail's first pixels (the column still holds there, within its
57
+ exit margin, and refuses). The held lane still holds, so lane to lane never passes through the float, and where the
58
+ pointer is inside another lane it hasn't entered yet the frame names that lane `pending`: a host shows no "Can't go
59
+ here" while it is set.
60
+
6
61
  ## 26.11.48
7
62
 
8
63
  The landing model's guides gain a kind, and a lane over a place that takes nothing is easier to reach. With
package/README.md CHANGED
@@ -7,42 +7,32 @@
7
7
  >
8
8
  > Version numbers are dates (YY.M.R), not semantic versions, so any release may break things, including how frames are scheduled, how springs settle and how gestures are timed. Pin an exact version and read the [CHANGELOG](https://github.com/n-uf/motion/blob/main/packages/motion/CHANGELOG.md) before you upgrade. If you need a stable animation library, use [Motion](https://motion.dev) or [GSAP](https://gsap.com). Both work on the DOM, so neither is a drop-in replacement.
9
9
 
10
- Site and live demos: [motion.n-uf.com](https://motion.n-uf.com)
11
-
12
- One frame loop with an injected clock, fine-grained signals, springs and
13
- tweens, and a DOM-free gesture recognizer. No DOM, no framework, no globals:
14
- the host hands in a clock, and tests hand in a fake one.
10
+ How things move. One frame loop on an injected clock, fine-grained signals, values that animate (springs, tweens and one settle curve for moving windows), a DOM-free gesture recognizer, the drag intent and the landing model, and layout motion that glides a whole layout. No DOM, no framework, no globals: the host hands in a clock and plain event objects and reads plain numbers back, and tests hand in a fake clock.
15
11
 
16
12
  ```sh
17
13
  npm i @n-uf/motion
18
14
  ```
19
15
 
20
- - **clock/**: one frame loop that runs tasks in phases (input → update →
21
- layout → write) with a frame budget and stats, on a clock you pass in.
22
- - **signals/**: reactive values, computed values and effects; a change
23
- recomputes only what depends on it, and effects can run once per frame.
24
- - **values/**: springs and tweens over numbers, points, rects and vectors,
25
- stepped by the clock, with velocity that carries over a retarget, settle
26
- detection and a reduced-motion switch; and the window motion rules:
27
- `settle` (one fast-then-gentle curve that never passes its target), direct
28
- drag (`settle.hold`: what a pointer owns sits exactly under it) and `reveal`
29
- (glide a window without stretching its content).
30
- - **gestures/**: a recognizer that turns pointer, wheel and trackpad events
31
- (plain objects) into one gesture stream (click or drag, double click, long
32
- press, pinch, scroll, zoom, recovery from lost releases), a frame coalescer,
33
- and a dwell machine, for spring-loading.
16
+ ## Entry points
34
17
 
35
- One package, nine entries: `@n-uf/motion` (everything in the core), its four
36
- folders on their own (`@n-uf/motion/clock`, `/signals`, `/values`,
37
- `/gestures`), `@n-uf/motion/drag` (the drag intent), `@n-uf/motion/layout`
38
- (the window motion rules applied to a whole layout), `@n-uf/motion/testing`
39
- (frame-sampled checks of the motion rules, for tests and browser specs), and
40
- `@n-uf/motion/browser`, the clock on `requestAnimationFrame` and the
41
- reduced-motion media query. The core entries touch no DOM; importing several of
42
- them still gives one signal graph.
18
+ | Entry | What it gives |
19
+ |---|---|
20
+ | `@n-uf/motion` | Everything in `/clock`, `/signals`, `/values` and `/gestures`, and the shared value shapes (`Point`, `Rect`, `Vector`). |
21
+ | `@n-uf/motion/clock` | The frame loop (phases input, update, layout, write; a budget; stats) and a fake clock for tests. |
22
+ | `@n-uf/motion/signals` | `signal`, `computed`, `effect`, `batch`: a change recomputes only what depends on it, and effects can run once per frame. |
23
+ | `@n-uf/motion/values` | Springs, tweens and the settle curve, as motion values stepped by the loop; `reveal` and `popIn`; easing functions. |
24
+ | `@n-uf/motion/gestures` | The recognizer (click or drag, double click, long press, pinch, scroll, zoom), a frame coalescer, and state machines for touch press, paged swipe and dwell. |
25
+ | `@n-uf/motion/drag` | The drag intent (when a drop indicator shows, which target, what a release lands on), grip presses, drop previews and the landing model. |
26
+ | `@n-uf/motion/layout` | Layout motion: items glide to new rects, a held item follows the pointer 1:1 and lands, FLIP for DOM groups. |
27
+ | `@n-uf/motion/testing` | Frame-sampled checks of the motion rules (no overshoot, no jumps, held under the pointer), for tests and browser specs. |
28
+ | `@n-uf/motion/browser` | The clock on `requestAnimationFrame` and the reduced-motion media query. |
29
+
30
+ The core entries touch no DOM; importing several of them still gives one signal graph. `/drag`, `/layout`, `/testing` and `/browser` are not in the root.
43
31
 
44
32
  ## One frame
45
33
 
34
+ A pointer drives a spring that follows a target, and the DOM is written once per frame, only while something moves.
35
+
46
36
  ```ts
47
37
  import { computed, createFrameCoalescer, createFrameLoop, effect, signal, springValue } from "@n-uf/motion";
48
38
  import { createBrowserClock, prefersReducedMotion } from "@n-uf/motion/browser";
@@ -68,345 +58,9 @@ effect(() => {
68
58
  }, { schedule: loop.scheduler("write") });
69
59
  ```
70
60
 
71
- ## clock/
72
-
73
- | | |
74
- |---|---|
75
- | `ClockPort` | `{ now, requestFrame, cancelFrame, setTimer, clearTimer }`, the shape of hypr-tiling's `SchedulerPort`. |
76
- | `createFrameLoop({ clock, budgetMs?, frameMs?, maxDeltaMs?, maxRounds?, onError?, onOverBudget? })` | The loop. It requests a frame only while it has work. |
77
- | `loop.schedule(phase, task, { deferrable? })` | Run `task` once: this frame if `phase` is still ahead, else the next. Deduped by function; returns cancel. A `deferrable` task waits for a later frame when the budget is spent. |
78
- | `loop.repeat(phase, task)` | Run `task` every frame until it returns `false`; returns stop. |
79
- | `loop.scheduler(phase)` | For `effect(fn, { schedule })`: the effect runs in `phase`, at most once per frame. |
80
- | `loop.frames(phase)` | A frame source in that phase (for a coalescer). |
81
- | `loop.stats()` / `resetStats()` | Frames, frames over budget, deferred tasks, errors, last / max / mean frame ms, ms per phase, repeating and queued tasks. |
82
- | `createFakeClock({ now?, frameMs? })` | A clock that moves only when told: `tick(ms)`, `frame(dt?)`, `frames(n)`, `runUntilIdle()`, `spend(ms)` (work that takes time), `pendingFrames`, `pendingTimers`. |
83
-
84
- Each task gets `{ time, delta, index, phase, budgetMs, elapsed(), remaining() }`.
85
- `delta` is the time since the last frame, clamped to `maxDeltaMs` (default
86
- 64), and `frameMs` for the first frame after the loop was idle.
87
-
88
- Within a phase, one-shot tasks run first, then the repeating ones, then any
89
- one-shots they queued for that phase. A task queued for a later phase runs in
90
- the same frame; one queued for an earlier phase runs in the next.
91
-
92
- ```ts
93
- import { createFakeClock, createFrameLoop } from "@n-uf/motion";
94
-
95
- const clock = createFakeClock();
96
- const loop = createFrameLoop({ clock, budgetMs: 8 });
97
- loop.schedule("write", () => console.log("write"));
98
- loop.schedule("input", () => console.log("input"));
99
- clock.frame(); // input, write
100
- loop.stats(); // { frames: 1, overBudget: 0, ... }
101
- ```
102
-
103
- ## signals/
104
-
105
- | | |
106
- |---|---|
107
- | `signal(value, { equals? })` | Read and write `.value`; `peek()` reads without tracking. |
108
- | `computed(fn, { equals? })` | Lazy and cached; `fn(previous)`; a thrown error is kept and rethrown until a source changes. |
109
- | `effect(fn, { schedule? })` | Runs now and on every change; `fn` may return a cleanup. With `schedule`, runs go to the scheduler. Returns dispose. |
110
- | `batch(fn)`, `untracked(fn)`, `isSignal(x)` | |
61
+ ## A drag
111
62
 
112
- An effect's own writes don't re-run it; writes inside an effect are batched
113
- until it returns; effects that keep re-triggering each other throw instead
114
- of hanging. The graph algorithm is
115
- [alien-signals](https://github.com/stackblitz/alien-signals)' published core
116
- (`alien-signals/system`, the same core Vue 3.6 uses), under this API;
117
- [bench/RESULTS.md](./bench/RESULTS.md) has the comparison behind that choice.
118
-
119
- ```ts
120
- import { computed, createFakeClock, createFrameLoop, effect, signal } from "@n-uf/motion";
121
-
122
- const loop = createFrameLoop({ clock: createFakeClock() });
123
- const width = signal(800);
124
- const columns = computed(() => Math.max(1, Math.floor(width.value / 300)));
125
- effect(() => console.log("columns", columns.value), { schedule: loop.scheduler("write") });
126
- width.value = 850; // still 2 columns: the effect won't run
127
- width.value = 1300; // runs once, in the next frame's write phase
128
- ```
129
-
130
- ## values/
131
-
132
- | | |
133
- |---|---|
134
- | `createSpring(initial, { stiffness?, damping?, dampingRatio?, mass?, restDelta?, restSpeed? })` | Critically damped by default (`dampingRatio: 1`, `stiffness: 300`). Each step is the exact closed-form solution, so the curve doesn't depend on the frame rate. |
135
- | `createTween(initial, { duration?, easing? })` | Default 250 ms, `easeOutCubic`. A new target starts a new run from the current value. |
136
- | `motionValue(loop, animator, { phase?, reducedMotion? })` | Steps an animator on the loop while it moves; reading `.value` tracks it. |
137
- | `springValue(loop, initial, options)` / `tweenValue(...)` | The two together. |
138
- | `mv.set(target, { velocity? })`, `jump(value)`, `snap()`, `follow(() => target)`, `onSettle(fn)`, `dispose()`, `moving`, `velocity`, `target` | |
139
- | `springStep(state, target, params, dtMs)` | One pure scalar step, for hosts that step by hand. |
140
- | `linear`, `ease`, `easeIn`, `easeOut`, `easeInOut`, `easeOutCubic`, `easeInOutCubic`, `cubicBezier(x1, y1, x2, y2)` | Easing functions (functions, not CSS strings). |
141
-
142
- Values are plain: a number, `{ x, y }`, `{ x, y, width, height }` or an array
143
- of numbers, a fresh object after every change. Velocity is in units per
144
- second. A spring keeps its velocity when its target changes mid-flight. A
145
- value is at rest when it is within `restDelta` of the target and slower than
146
- `restSpeed` (defaults 0.1 and 1, tuned for pixels; use about 0.001 and 0.01
147
- for opacity or scale), and then it snaps onto the target exactly. With
148
- `reducedMotion` on (a boolean or a function read on every target and frame),
149
- targets are reached at once.
150
-
151
- Motion values step in the `layout` phase by default, after that phase's
152
- one-shot tasks: a target set in input, update or layout moves the value in
153
- the same frame, and `write` sees it.
154
-
155
- ```ts
156
- import { createFakeClock, createFrameLoop, springValue } from "@n-uf/motion";
157
-
158
- const clock = createFakeClock();
159
- const loop = createFrameLoop({ clock });
160
- const rect = springValue(loop, { x: 0, y: 0, width: 200, height: 100 }, { dampingRatio: 0.7 });
161
- rect.onSettle((r) => console.log("settled at", r));
162
- rect.set({ x: 300, y: 40, width: 240, height: 100 });
163
- clock.runUntilIdle(); // settled at { x: 300, y: 40, width: 240, height: 100 }
164
- ```
165
-
166
- ### Window motion: settle, direct drag, reveal
167
-
168
- Three rules make windows move the way a tiling window manager feels smooth
169
- (Hyprland is the reference): what the pointer drags is glued to it, everything
170
- else moves on one front-loaded curve that never passes its target, and content
171
- is never stretched.
172
-
173
- | | |
174
- |---|---|
175
- | `createSettle(initial, { omega?, restDelta? })` | The one curve for moving to a new place. On a new target every component gets the velocity `omega · distance` toward it from wherever it is drawn, so it follows `distance · e^(−omega·t)`: 90 % in `ln(10)/omega` s, then it eases in, and never passes the target (no overshoot on position, no wobble on size), however often it is retargeted. A velocity set by hand toward the target is capped at that speed; one away from it is kept, and the value turns around without crossing. |
176
- | `SETTLE_TEMPO` | `{ calm: 20, default: 25, quick: 37 }` (1/s): 90 % in 115, 92 or 62 ms. |
177
- | `settle.hold(value)` | Pin the value exactly there, at rest (same as `jumpTo`), for a direct drag. Call it on each pointer move; the next `setTarget` launches from there. |
178
- | `settleValue(loop, initial, { omega?, restDelta?, phase?, reducedMotion? })` | The settle on a frame loop. Pin it with `mv.jump(rect)`. |
179
- | `reveal(drawn, target)` | How to draw a window gliding at `drawn` whose content is laid out at `target`: move the element by `dx, dy`, draw the frame (chrome) at `width × height`, clip the content by `clipRight, clipBottom`. No scale, no layout per frame. |
180
- | `popIn(progress, from = 0.87)` | Opening and closing: a uniform scale about the center plus opacity. Drive `progress` with a settle on a number with `{ restDelta: 0.001 }` (the default 0.1 is for pixels) or a tween. |
181
-
182
- ```ts
183
- import { createFakeClock, createFrameLoop, settleValue } from "@n-uf/motion";
184
-
185
- const clock = createFakeClock();
186
- const loop = createFrameLoop({ clock });
187
- const win = settleValue(loop, { x: 0, y: 0, width: 400, height: 300 });
188
- win.set({ x: 400, y: 0, width: 200, height: 300 }); // a reflow: position and size arrive together
189
- clock.frame();
190
- win.set({ x: 300, y: 0, width: 300, height: 300 }); // retargeted mid-flight: on from where it is drawn
191
- clock.runUntilIdle();
192
- console.log(win.value); // { x: 300, y: 0, width: 300, height: 300 }, never past it on the way
193
- ```
194
-
195
- ## layout/
196
-
197
- `@n-uf/motion/layout` applies the window motion rules to a whole layout:
198
- give each item an id and a target rect, and it moves the real elements, every
199
- one on one frame loop that runs only while something moves. It animates the
200
- rects it is given and nothing else: which items move where (making room,
201
- drop targets) is the caller's layout.
202
-
203
- | | |
204
- |---|---|
205
- | `createLayoutMotion({ loop, omega?, phase?, popFrom?, reducedMotion?, onDraw?, onActiveChange? })` | The layout motion: `add(id, drawable, at, { shown? })`, `get`, `remove`, `retain(ids)` (removes every item not listed), `items`; `task(fn)` runs before the items step each frame, `onFrame(fn)` after; `onIdle`, `idle()`, `running`, `wake()`, `configure({ omega })`, `flush()`, `dispose()`. |
206
- | `reducedMotion` | A boolean or the host's query (the reduced-motion media query), read on every new target and every show or hide: while true, items are placed and shown at once, with no glide and no fade. |
207
- | `onDraw(batch)`, `flush()` | Batched drawing: every item that moved is drawn in one pass per frame (its drawable, then `onDraw` once with all their frames); an item at rest is not drawn. A change made between frames waits for the next frame, or `flush()` draws it now, which a host calls right after it commits a layout so the next paint shows no frame at the new box. |
208
- | `onActiveChange(active)` | Called once when the frames start and once when they stop. |
209
- | `item.moveTo(rect)` | Settle there from wherever it is drawn (a retarget mid-flight goes on from the drawn rect). The content is laid out at the new box once, and the item redrawn at once, so no frame shows the old offset from the new box. A size change is revealed, never scaled. |
210
- | `item.retarget(rect)` | Optional on a `LayoutItem`. Settle there like `moveTo`, but keep the content laid out where it is while the size is unchanged: for chasing a moving point (the direct drag's glide back to the pointer uses it), which would otherwise lay the content out on every frame. `holdItem` falls back to `moveTo` for an item without it. |
211
- | `item.jumpTo(rect)`, `item.hold(rect)`, `item.glideFrom(from, to)` | At once; drawn exactly where a pointer puts it (the content moves with it); drawn at `from`, then settle to `to`. |
212
- | `item.show(on, { now? })` | Appear or disappear with a uniform-scale fade (`popIn`); collapsing is a `moveTo` to the collapsed size, revealed. |
213
- | `item.drawn`, `target`, `box`, `settled`, `shown`, `showing`, `shownSettled` | Where it is drawn, where it is heading, where its content is laid out. |
214
- | `holdItem(item, grab)` | A direct drag of the real item, no copy: `move(pointer)` draws it 1:1 from the grab offset; `snapTo(slot)` glides into a slot, `snapTo(null)` back to the pointer (`follow()` once a frame until it is under it again); `land(slot)` and `cancel(home)` settle from the release rect, which they return. `preview(plan, slot)` once a frame plays a drop preview (`plan` from `@n-uf/motion/drag`'s `previewPlan`): `indicator` and `gap` (make room) keep the item under the pointer (`gap` with the caller's room open), `snap` glides it into the slot, and a release there finishes that glide. `resize(size)` holds it at a new size from now on (the caller laid its content out for it): the grab point keeps its share of the item, and it settles there from where it is drawn, revealed, never stretched (in a slot it stays put and takes the size when it leaves). |
215
- | `anchoredMorph(size, anchor, config?)` | A box held at a point that changes size about an anchor (its spot that sits on the point). `to(size, anchor)` settles the size and the anchor together from where they are drawn (at `MORPH_TEMPO`, which is `SETTLE_TEMPO.quick`: 90 % in about 60 ms, within 1 % in about 125 ms, the last pixels longer for large size changes, unless `config` says otherwise; a retarget mid-flight turns at once, no jump, no overshoot; true when the target changed); `jumpTo(size, anchor)` is there at once; `step(dt)` once a frame; `size`, `anchor`, `target` and `settled` read where it is drawn, heading and at rest; `rectAt(point)` is the box with its anchor exactly on the point, every frame; `progress` (0 to 1 since the last retarget) fades the content it came from out and the target's in. Draw each content with its own anchor on the point and neither moves from under the pointer. |
216
- | `flip(entries, change)` | FLIP for DOM groups on settle: record where each node is drawn, run `change` (the DOM moves), then each item glides from its old rect. |
217
- | `domDrawable({ node, frame?, content? })`, `layOutBox`, `drawBox` | Draw onto DOM styles: the node laid out at the box, moved by one transform, the frame at the drawn size, the content (or the node) clipped; hidden when gone. Any `{ layOut, draw }` drawable works (a canvas, a test). |
218
-
219
- ```ts
220
- import { createFakeClock, createFrameLoop } from "@n-uf/motion";
221
- import { createLayoutMotion, holdItem } from "@n-uf/motion/layout";
222
-
223
- const clock = createFakeClock();
224
- const loop = createFrameLoop({ clock });
225
- const motion = createLayoutMotion({ loop });
226
- const panel = motion.add("panel", { layOut: () => {}, draw: () => {} }, { x: 0, y: 0, width: 200, height: 100 });
227
- panel.moveTo({ x: 300, y: 0, width: 240, height: 100 }); // a settle, its new width revealed
228
- clock.runUntilIdle();
229
- const held = holdItem(panel, { x: 20, y: 10 }); // grabbed 20 px in, 10 px down
230
- held.move({ x: 120, y: 60 }); // a direct drag, 1:1: drawn at { x: 100, y: 50 }
231
- const release = held.land({ x: 0, y: 0, width: 200, height: 100 });
232
- console.log(release); // { x: 100, y: 50, width: 240, height: 100 }: the landing starts there
233
- clock.runUntilIdle();
234
- console.log(panel.drawn); // { x: 0, y: 0, width: 200, height: 100 }
235
- ```
236
-
237
- A host that draws every item itself, once per frame:
238
-
239
- ```ts
240
- import { createFakeClock, createFrameLoop } from "@n-uf/motion";
241
- import { createLayoutMotion } from "@n-uf/motion/layout";
242
-
243
- const clock = createFakeClock();
244
- const loop = createFrameLoop({ clock });
245
- const batches: string[][] = [];
246
- const host = createLayoutMotion({ loop, onDraw: (batch) => batches.push(batch.map((e) => e.id)) });
247
- const noop = { layOut: () => {}, draw: () => {} };
248
- const a = host.add("a", noop, { x: 0, y: 0, width: 100, height: 100 });
249
- host.add("b", noop, { x: 0, y: 200, width: 100, height: 100 });
250
- host.flush(); // both drawn now, in one batch: ["a", "b"]
251
- a.moveTo({ x: 300, y: 0, width: 100, height: 100 });
252
- host.flush(); // right after the host's commit: ["a"], at the rect it is drawn at
253
- clock.runUntilIdle(); // one batch per frame, each ["a"] (b is at rest)
254
- host.retain(["a"]); // b left the layout
255
- console.log(host.items.size); // 1
256
- ```
257
-
258
- ## testing/
259
-
260
- `@n-uf/motion/testing` checks recorded frames against the rules. Record what
261
- was drawn each frame (on the fake clock, or in a browser spec once per
262
- animation frame) and ask:
263
-
264
- | | |
265
- |---|---|
266
- | `checkNoOvershoot(samples, from, to, tolerance?)` | Every component stays between its start and end: no overshoot, no size wobble. |
267
- | `checkMonotonic(samples, to, tolerance?)` | The distance to the target never grows: no bounce, no restart backwards. |
268
- | `checkNoJumps(samples, omega, slack?)` | No frame moves further than a settle at `omega` could: catches snaps and restarts from an old place. Sample times are the stepped time (the loop's `delta`s), not wall-clock timestamps. |
269
- | `checkHeld(samples, tolerance?)` | A directly dragged rect is where the pointer puts it, every frame. |
270
- | `checkContentScale(samples, { uniformOnly?, tolerance? })` | Content's transform is never non-uniform (stretched); with `uniformOnly: false`, never scaled at all. |
271
- | `checkTempo(samples, from, to, t90, tolerance?, startT?)` | 90 % of the way within `t90` ms of `startT` (default: the first sample, so record the frame the move began); returns the measured time too. |
272
-
273
- Each returns `{ ok, failures }`, a failure naming the frame and component.
274
- The motion lab in the [n-uf/motion repository](https://github.com/n-uf/motion)
275
- (`apps/lab`) runs them on every move.
276
-
277
- ## gestures/
278
-
279
- | | |
280
- |---|---|
281
- | `createRecognizer({ toCanvas, timers?, dragModifier?, platform?, thresholds?, longPress?, multiClick?, pinch?, wheel?, staleMs? }, emit)` | Raw pointer, wheel and Safari gesture events in, `InputGesture`s out: `press`, `dragStart`, `move`, `longPress`, `release` (with `click` and `clickCount`), `cancel` (with a reason), `hover`, `pinch` (touch or trackpad, pinch or two-finger pan), `scroll`, `zoom`. Methods: `feed`, `cancel(reason)`, `reset`, `active`, `pinching`, `setDragModifier`, `dispose`. |
282
- | `GesturePointer` | The pointer every gesture reports (`screen`, `canvas`, `kind`, `buttons`, `modifiers`, `pointerId`, `button`). `SurfacePointer`, its old name, is removed: import `GesturePointer`. |
283
- | `RECOGNIZER_DEFAULTS` | Click-or-drag thresholds 4 / 6 / 8 px (mouse / pen / touch), long press after 500 ms for touch and pen, double click within 500 ms and 5 px (`DOUBLE_CLICK`, the package's one double click), pinch at 5 % scale or 10 px pan (read once both fingers have moved as often as each other, or one is three moves ahead, or one lifts). |
284
- | `wheelDeltaPx`, `classifyWheel`, `dampWheelPan`, `WHEEL_DEFAULTS`, `WHEEL_PAN_DEFAULTS` | Wheel normalization: lines and pages to px, Cmd/Ctrl+wheel (and the ctrl+wheel trackpad pinch) zooms by 2^(−dy / 300), Shift turns a vertical wheel horizontal, and a damped pan per event. |
285
- | `toModifiers`, `resolveDragModifier`, `defaultDragModifier`, `isHeld`, `modHeld`, `platformButton` | Modifier keys in one shape; the drag modifier per platform (Cmd on macOS, Alt elsewhere); on macOS a Ctrl+click is the secondary button. |
286
- | `createFrameCoalescer(onFrame, frames, { merge? })` | `schedule(sample)`, `flush()`, `cancel()`, `pending`. One delivery per frame with the latest sample (or `merge`d ones) and how many were folded. Same shape as hypr-tiling's. |
287
- | `dwellReducer`, `DWELL_IDLE`, `dwellDeadline`, `createDwellMachine` | `idle → dwelling → fired`, for spring-loaded targets: hold over the same key long enough and it fires once. |
288
- | `createMachine({ reducer, initial, clock, deadline? })` | Runs a pure reducer on a clock: arms the timer the state's deadline asks for and sends its input when it fires. `state` is reactive. |
289
- | `touchPressReducer`, `TOUCH_PRESS_IDLE`, `touchPressDeadline`, `createTouchPress`, `TOUCH_PRESS_DEFAULTS` | A touch on something draggable in a scrolling page, `idle → pressed → lifted \| scrolled`: before the hold (220 ms), travel mostly along the page's scroll direction (`scroll: "y"` or `"x"`) past 10 px is a scroll, which never lifts (short of 10 px it waits, so a finger scroll reported a few px at a time never lifts on the way); travel past 6 px mostly across it lifts where the finger is; a still finger lifts where it was pressed after the hold. |
290
- | `pagedSwipeReducer`, `PAGED_SWIPE_IDLE`, `pagedSwipeDeadline`, `createPagedSwipe`, `PAGED_SWIPE_DEFAULTS`, `swipeProgress` | Swiping between pages with a trackpad's wheel run or a finger, `idle → armed → tracking → settling → lockout`. It arms only along the swipe (more than twice the cross movement), without Ctrl, with the configured modifier, when nothing under the pointer scrolls further and a page is there; a run that breaks a rule belongs to scrolling until the wheel rests 120 ms. Past 24 px it tracks: `progress` is the travel over the page size, −1 to 1, held at 0 towards a missing page. At the end it commits at 35 % of the page or a peak of 0.6 px/ms towards it (the peak starts over when the travel crosses zero); the host sends `settled` after its transition, and a 350 ms lockout swallows the trackpad's momentum. On x or y (`along`). |
291
-
292
- The recognizer takes plain objects the host copies out of DOM events, with
293
- their timestamps; nothing in it touches the DOM. Mouse, pen and touch share
294
- one path. There is one press at a time, a second finger turns it into a
295
- pinch, and a press only becomes a drag past its device's threshold, so a
296
- modifier+click stays a click for the content. It recovers releases that never
297
- arrive (a move with no buttons down, the same pointer pressing again, a press
298
- left untouched for `staleMs` when another pointer goes down). Its `timers`
299
- are a clock (any `ClockPort`), used for the long press. Hit testing and
300
- routing (what is under a point, who gets the gesture) are the host's.
301
-
302
- ```ts
303
- import { createFakeClock, createRecognizer } from "@n-uf/motion";
304
-
305
- const clock = createFakeClock();
306
- const recognizer = createRecognizer({ toCanvas: (p) => p, timers: clock }, (g) => console.log(g.type));
307
- const finger = { pointerId: 1, pointerType: "touch", button: 0, screen: { x: 0, y: 0 } } as const;
308
- recognizer.feed({ ...finger, type: "pointerdown", buttons: 1, time: clock.now() }); // press
309
- clock.tick(500); // longPress
310
- recognizer.feed({ ...finger, type: "pointerup", buttons: 0, time: clock.now() }); // release, click: false
311
- ```
312
-
313
- A paged swipe, its timers on a clock:
314
-
315
- ```ts
316
- import { createFakeClock, createPagedSwipe, NO_MODIFIERS } from "@n-uf/motion";
317
-
318
- const clock = createFakeClock();
319
- const swipe = createPagedSwipe({ clock });
320
- swipe.send({ type: "context", hasPrev: true, hasNext: true, size: 1000 });
321
- swipe.send({ type: "wheel", dx: 400, dy: 0, t: clock.now(), modifiers: NO_MODIFIERS });
322
- console.log(swipe.state.phase, swipe.state.progress); // tracking 0.4
323
- clock.tick(120); // the wheel rests: past 35 %, it commits
324
- console.log(swipe.state.phase, swipe.state.target); // settling next
325
- swipe.send({ type: "settled" }); // the host's page transition is done: momentum is locked out
326
- console.log(swipe.state.phase); // lockout
327
- ```
328
-
329
- ## drag/
330
-
331
- `@n-uf/motion/drag` decides, from the pointer's path, when a drop indicator
332
- shows, which target it shows, when the others make room, and what a release
333
- lands on. It is pure: the host feeds it the pointer once a frame and plain-data
334
- targets, and draws what it says. It is only there, not in the root.
335
-
336
- | | |
337
- |---|---|
338
- | `createDragIntent({ home, lift?, liftRect?, floating?, earlyRelease?, tuning?, placeOf? })` | `update(point, time, targets, keys?)` once a frame while an item is dragged, returning `{ shown, room, roomPlace, aiming, atHome, arming, forced, refused, refusedSinceShown }` (`refusedSinceShown`: no target shows and the pointer has crossed a refusal since one last did, so a host that commits only drawn targets commits `release` too, as a quick drag across a refusal let go beyond it has no indicator drawn: read it from an `update` at the release point, called before `release`; the field is required, so a host or mock that builds a frame itself sets it; `arming`: the spring-loaded target the pointer dwells on, not armed yet; `forced`: `"float"` or `"rail"` when a modifier key won (the float key wins over dock targets only: over a refusal, or outside the float's `bounds`, it shows nothing and a release lands nowhere, `refused` naming the refusal); `refused`: the refusal under the pointer, a target marked `refuse: true` that the pick lands on, which no held target's band or grace covers, so nothing shows there and a release lands nowhere: pass a host's refusals in with the targets; a refused place is never drawn (no tint, outline or zone label), and while `refused` is set a host may say "Can't go here" at the pointer; `atHome`: the pointer is back inside `home` after it has been outside `home` itself; never true at the press or while it moves about inside `home`; with `floating` (the held item floats, `home` its box: a free placement, ranked like the float) home holds only where the pick there, home ignored, is no refusal and inside the window, so over a refusal in its box the frame is refused and a release lands nowhere, and on or past the window's edge nothing is picked; a docked item's home holds wherever it lies. A host sets it at lift from the placement layout, `floating: layout.items[id]?.floating === true`: the option is the intent's, read from `@n-uf/placement`'s layout item flag of the same name, not that flag itself. Over home no target is shown and a release does nothing, so a host that wants to say "a drop here returns it" draws its own indicator at the home rect for that frame); `release(point, targets, keys?)`, the target a release lands on or null (home); before the item has settled on a target that follows `earlyRelease`: `"target"` (the default) lands on the shown target, else the one under the pointer, and `"float"` makes what shows what lands, so the item floats where it is (over a refusal or outside the float's `bounds`, nowhere); `hide(time)` while the view scrolls under the pointer; `moveHome(dx, dy)`; `state`; `tuning`. |
339
- | `DRAG_DEFAULTS` | Lift at 5 px (a touch: a 180 ms hold, then 8 px); aiming below 0.45 px/ms over 50 ms, or within 12 px for 90 ms; a 10 px hysteresis margin (`band`) and a 4 px breakthrough, each at most a fifth of the hit areas' extents (`bandShare` 0.2), a 120 ms grace across the gap between two hit areas (`gapGrace`); a switch waits 150 ms (the switch delay); room after 160 ms (`roomAfter`, so a pointer moving across targets doesn't reflow the layout; a target marked `opensRoom`, whose indicator would lie over what its room moves, holds that long, or its own `roomHold` in ms, before it shows and has `room` in the frame that first shows it, and an armed spring-loaded target has its room as it shows; with its room open, one with a `roomHit` (its hit and landing rect) holds in `hit ∪ roomHit`, over a refusal or a target no more precise than it there, while a more precise target past the breakthrough and a held key still win); a spring-loaded target arms after a 200 ms dwell (`railArmDwellMs`: a pass at travelling speed never arms it, and platforms spring-load after a similar rest), never within 16 px of the lift point (`liftZone`: the "changed my mind" spot); Shift floats and ⌘/Ctrl (`"Mod"`, either key) goes to the nearest rail (`modifiers`; Alt is left free, so an app can keep it for unfreezing a frozen layout). Each is overridable per intent. |
340
- | `targetAt(targets, point)`, `inRect(rect, point, margin?)` | The most precise target under a point (priority 1, 2, 3, then the smaller hit area; a rect holds its edges exactly); a point in a rect grown or shrunk by a margin. A `DragTarget` whose hit area isn't one rect gives `hits`, every piece of it (`hit` is then the largest): the pointer is in the hit area when it is in any piece, and the hit area's size, for the smaller-hit-area rule and the drag intent's bands, is the pieces' together. A refusal ranks at `REFUSAL_RANK` (2.5, an ordering rank, not a priority: priorities stay 1, 2 and 3, and `refuse: true` is a refusal's tier; it orders after every target of priority 1 and 2, so a real target wins wherever the two meet or overlap, before the float's 3); `pickRank(t)` gives a target's rank. A zone with `bounds` (a refusal's and the float's: the window's stage) holds only points strictly inside it, its band and gap grace too, so a pointer clamped exactly onto the window's edge (`x + width`; a host that clamps to `width - 0.5` still picks inside) is never in it. This is the one pick rule: `@n-uf/placement/scene/cases` takes it as its hosts' `pick`. |
341
- | `liftDecision({ touch, distance, elapsed }, tuning?)` | `"wait"`, `"lift"` or `"refuse"`: when a press becomes a drag (`"refuse"` is a touch that moved before the hold: scroll wins). |
342
- | `createGripPress({ tuning?, double? })`, `GripRelease`, `DOUBLE_CLICK` | A press on a grip, start to end: `down(point, time, { touch?, clicks? })`, `move(point, time)` (the lift rule), `up(point, time)` → `"click"`, `"doubleActivate"` or null (it lifted). Two presses within `DOUBLE_CLICK` (500 ms and 5 px, the package's one double click, which the recognizer's `clickCount` uses too; browsers don't expose the system setting, so this is the common desktop default; `double` tunes it, and `clicks`, a `mousedown`'s `detail`, overrides it) give a click, then a double-activate: never a second click, never a lift. A press past the lift distance is a drag, also as the second press. |
343
- | `previewPlan(frame, preview, slotted?)`, `DragPreview`, `DRAG_PREVIEW_DEFAULT` | What to draw for a frame under one of four drop preview modes: `{ showIndicator, makeRoom, snapItem }`. `"item"`: the dragged item is the only preview, with no indicator for any target: it sits in a slotted target once the room is open and otherwise stays on the pointer (pair it with `earlyRelease: "float"`, so a release lands what shows). `"indicator"`: only the indicator, nothing moves. `"gap"` (make room): the others make room once the intent does; the item stays under the pointer. `"snap"` (the default): room opens and the item glides into a slotted target's room, with no indicator (a target without a slot keeps it). The object form `{ mode: "outline" \| "placeholder" \| "snap", placeGuides? }` (`DropPreviewMode`) draws with `"indicator"`'s, `"gap"`'s and `"item"`'s plan and adds `guides` (`PlaceGuides`: `"off"`, `"near"`, `"all"`; defaults `PLACE_GUIDES_DEFAULT`: snap and placeholder near, outline off): the guides to draw while no landing shows, `"off"` whenever one does, so a host shows where the item can go or where it will land, never both. It also carries `emptyLanes` (`"real"` by default, or `"edge"`), for the host to pass to `lanes()`: an empty lane drawn at its real size or as a thin striped edge. The string forms give `guides: "off"`. |
344
- | `createLandingModel({ regions, regionsFor?, floatLanding?, home?, margins?, gates?, approach?, placeGuides? })` | The landing model: where a docking drag lands, as state instead of a per-frame pick. `regions` are the drag's lanes (each with its spots in order: `along` stretch and `landing` rect), refused places, content and what blocks it, the stage and the item's size: what `@n-uf/placement/scene`'s `lanes()` gives, as plain data. `update(point, time, keys?)` returns `{ region, lane, spot, landing, room, guides, shift, pending? }` (`pending`: the lane the pointer is inside but hasn't entered yet; show no "Can't go here" while it is set, though a release lands nowhere), and `release()` the same answer (`{ kind: "spot" }`, `{ kind: "float", rect }` or null). The stage's edge is the easiest place to dock: a pointer up to `edge` (48 px) past the stage counts as on its edge, deep in the lane drawn there; beyond, nowhere. A held lane holds while the pointer is within `exit` (12 px) of it; over a spot's stretch it is that spot, over a refused stretch refused (`lanes()` joins a stretch shorter than the item to its spots). Entering a lane needs `path` (40 px) of slow path along it inside it (steps of at most `step`, so a crossing at 0.375 px/ms or faster never enters at any angle), or a still step (1.5 px per 8 ms) `depth` (8 px) inside it, the depth counted only from the sides facing into the stage, so a fly-through of a thin bar or rail opens no room. Inside a lane that touches the held one, past its exit margin, the held lane holds until that lane's gate passes or the pointer has slid `path` px along it at any speed (across it at most a third as far), then that lane takes it: lane to lane never passes through the float, and a fast crossing of the touching lane opens no room. Along a lane the spot changes `spot` (6 px) past a boundary, the same margin everywhere, so a wobble within it never flips the spot (passing a neighbor much longer than the held item, the single frame before the hop may find the landing up to 56 px from the pointer; every other frame is within 48 px); where the change reflows the window (the spots' `others` keys differ), on a step of at most `step` (3 px per 8 ms), or once the held landing trails the pointer by more than `trail` (40 px): a fast hand across docked items reflows only as often as it must to keep the item near, and a change that moves only the held item follows at any speed. With `regionsFor`, a reflowing change is kept only if, in the new spot's own regions (its room open), the pointer still picks it (cached per spot until `setRegions`). Outside lanes: refused, open space (`"open"`: the content less what blocks it, where the float lands), or nowhere. Shift makes a lane or open space open space and hides the guides. Guides (`{ id, lane, kind: "line" \| "box" \| "hatch", rect }`, keyed by `id`; a hatch is a striped cue in the guides' color, a short end inside a box whose room partly fits or a thin edge where an empty side rail would open, never a measure of the landing): a lane's `marks`, else its spots' landings; `"near"` the held lane's, else the approached lane's (within 80 px, kept until another is 16 px nearer or past 96 px), and over a refused place the nearest lane's at any distance; `"all"` every lane's. The model has no waits of its own; steps are normalized to 125 Hz. The host calls `update` whenever it likes (per pointer sample, per animation frame, or both): a repeated point keeps the last step and counts as still only once the pointer has stayed put for `rest` (22 ms) after a slow step or on the stage's edge, else for `pause` (60 ms), so a fast hand with samples far apart (20–30 Hz, dropped events) is never still between them; the first point (the lift) is never still either, so a lift over a lane's band doesn't enter it; and the host need only call again after the pointer stops (every frame does), and calls again with the same point when a key changes. `setRegions(regions, regionsFor?)` remaps spots by id and takes the `regionsFor` that answers for the new state; `hide()` lets the lane go. Additive: `createDragIntent` is unchanged. |
345
-
346
- A target is `{ id, priority, hit, slot?, label?, free? }`: `hit` is the hit
347
- area the pointer can be in, `priority` how precise it is (a tab strip 1, an
348
- insertion point 2, a large area 3). The rules:
349
-
350
- - The indicator shows only when the pointer has left the item's home, a target
351
- is under it, and the pointer aims (slows down or holds still). Crossing
352
- targets at speed shows nothing.
353
- - Hysteresis: the current target keeps the pointer within a margin (`band`)
354
- around its hit area, unless a more precise target is clearly under the
355
- pointer. That is for the seam between two tiles only: leaving a `free`
356
- target (the float) for a tile, or nothing, switches at once, so a hit area at
357
- the window's edge takes its first px. Both scale with the hit areas:
358
- along each axis, at most a fifth of the current hit area's extent and of the
359
- hit area under the pointer, so a small one (a 28 px row) is entered by a
360
- direct glide from its neighbor. Leaving the shown target, a
361
- travelling pointer hides the indicator at once; an aiming one moves it once
362
- the new target has held 150 ms (the switch delay), so no indicator ever shows
363
- for less.
364
- - Room is made once the shown target, and the place in it (`placeOf`: a tab
365
- index, say), have held 160 ms; never for a `free` target.
366
- - `placeOf(target, point, previous)` gets the place it gave that target on the
367
- last sample, so a place can hold near its boundary. A null place is no
368
- target: nothing shows there (a target beneath with a place can), no room
369
- opens, and a release there lands on a target beneath, else goes home.
370
- `placeOf` is also asked about the current target just outside its hit area
371
- (within the margin or the gap grace): answer the nearest place there, and
372
- return null only for a part of the target that takes no drop. It runs on
373
- every sample for each target under the pointer, so keep it cheap.
374
- - A release lands on the shown target whenever one shows (drop = shown), else
375
- on the target under the pointer, else nowhere. A release over home does
376
- nothing.
377
- - Spring-loading: a target marked `arm: "dwell"` (a side's rail, say) is no
378
- target until the pointer has rested in its hit area for `railArmDwellMs`; a
379
- fast pass, or a drop before then, lands on what lies beneath (the float).
380
- Armed, it shows at once and its hit area is `armedHit` (grown: a magnet, the
381
- armed target's band); moving out past that band's outer edge disarms it, and
382
- re-entering needs a new full dwell. The frame's `arming` lets a host highlight the
383
- strip while the dwell runs, and say the armed state in its live region. Home
384
- doesn't gate it: a strip that overlaps the item's own place (an item alone in its
385
- column, dragged to its own side's edge) arms by dwell there, shows while armed,
386
- and takes a release over home; an unarmed target, and a target that isn't
387
- spring-loaded, still never show over home, and a release there does nothing.
388
- A spring-loaded target arms only after the pointer has entered its hit area
389
- during the drag: the point the drag starts at counts as not entered, so a drag
390
- that starts inside the strip (a panel's grip under it at the window's edge)
391
- must leave it and come back before it arms, while entering from over home
392
- counts. Nothing arms by dwell within `liftZone` (16 px, about a grip's size)
393
- of the point the drag was lifted at (`lift`, else the first sample): back
394
- where it was lifted, a pause is "changed my mind" and commits nothing, even
395
- with the grip under a strip (a flush drawer at the window's edge). A host can
396
- give the zone as a rect instead (`liftRect`, the part of the grip the strip
397
- covers): then nothing arms inside that rect, the radius is not applied, and
398
- the strip arms just past the grip. Elsewhere,
399
- home under the strip included, it arms as above, and the rail key still forces
400
- the rail anywhere, the lift zone too.
401
- - Keys win over geometry: with `keys` passed (`DragKeys`: `{ shift?, alt?, ctrl?,
402
- meta? }`, the modifiers held on a pointer event; `tuning.modifiers` says which
403
- key does what, default Shift and ⌘/Ctrl), the float key (Shift) shows and lands
404
- on the `free` target over a dock target, a spring-loaded one or open space
405
- inside the window (over a refusal the frame is refused, and outside the
406
- float's `bounds` nothing shows); the rail key (⌘/Ctrl, `"Mod"`) on the nearest
407
- spring-loaded target, from anywhere. The frame's `forced` says which won.
408
- - The four drop preview values (`"indicator"`, `"gap"`, `"snap"`, `"item"`) only change what is drawn: all follow
409
- these rules, so a drop lands where the preview showed it in each.
63
+ The drag intent is pure: feed it the pointer once a frame and plain-data targets, and draw what it says.
410
64
 
411
65
  ```ts
412
66
  import { createDragIntent, type DragTarget } from "@n-uf/motion/drag";
@@ -416,69 +70,17 @@ const intent = createDragIntent({ home: { x: 300, y: 300, width: 100, height: 50
416
70
  for (let t = 0; t <= 300; t += 16) intent.update({ x: 100, y: 50 }, t, [slot]); // held still over the slot
417
71
  console.log(intent.state.shown?.id); // "slot"
418
72
  console.log(intent.release({ x: 100, y: 50 }, [slot])?.id); // "slot"
419
-
420
- // A pane that takes drops on its right half only; that half holds 6 px past the line.
421
- const pane: DragTarget = { id: "pane", priority: 2, hit: { x: 0, y: 0, width: 200, height: 100 } };
422
- const zones = createDragIntent<DragTarget>({
423
- home: { x: 300, y: 300, width: 100, height: 50 },
424
- placeOf: (_t, p, previous) => (p.x >= (previous === "right" ? 94 : 100) ? "right" : null),
425
- });
426
- for (let t = 0; t <= 300; t += 16) zones.update({ x: 50, y: 50 }, t, [pane]); // held over its left half
427
- console.log(zones.state.shown, zones.release({ x: 50, y: 50 }, [pane])); // null null: nothing shows, the item goes home
428
73
  ```
429
74
 
430
- The intent works in one coordinate space: the one its targets and home are in. On a page drawn scaled (a zoomed
431
- canvas, a fitted preview), convert each pointer sample into page coordinates first, `(p − origin) / scale`, and the
432
- hysteresis margin, breakthrough and stillness distances stay page px:
433
-
434
- ```ts
435
- // The page is drawn at half size, its top-left corner at (300, 200) on screen; targets are in page px.
436
- const origin = { x: 300, y: 200 };
437
- const scale = 0.5;
438
- const toPage = (p: { x: number; y: number }) => ({ x: (p.x - origin.x) / scale, y: (p.y - origin.y) / scale });
439
- const onPage = createDragIntent({ home: { x: 600, y: 600, width: 100, height: 50 } });
440
- const screen = { x: 350, y: 225 }; // the pointer, as the browser reports it
441
- for (let t = 0; t <= 300; t += 16) onPage.update(toPage(screen), t, [slot]); // page (100, 50): over the slot
442
- console.log(onPage.state.shown?.id, onPage.release(toPage(screen), [slot])?.id); // "slot" "slot"
443
- ```
444
-
445
- A host contract: clamp the pointer into the stage (the window the targets tile) before it reaches `update` and
446
- `release`, so a pointer past the window's edge means its nearest point of the window. A drop target at the window's
447
- edge then stays under a hand that overshoots it, which is what makes an edge target easy to hit. Draw the dragged item at
448
- the pointer itself. While a drag is in progress, suppress the context menu (a Ctrl-click on macOS opens one) and the
449
- browser shortcuts of the rail key (⌘/Ctrl): `preventDefault` on `contextmenu`, and on the `keydown` of Meta or Control.
450
- The intent doesn't see DOM events, and the gesture recognizer has no hook for this, so it is the host's job; leave keys
451
- alone when no drag is active.
452
-
453
- ## @n-uf/motion/browser
454
-
455
- | | |
456
- |---|---|
457
- | `createBrowserClock({ host?, fallbackFrameMs? })` | The `ClockPort` on `requestAnimationFrame`, `performance.now` and `setTimeout`; timeouts stand in for frames where there is no `requestAnimationFrame`. |
458
- | `prefersReducedMotion(host?)` | A function reading `(prefers-reduced-motion: reduce)`, for `reducedMotion`. |
459
-
460
- The host is typed by its shape, not by lib.dom, so tests and workers can pass
461
- their own.
462
-
463
- ## Testing
464
-
465
- Everything runs on `createFakeClock()`: frames, timers, springs and machine
466
- deadlines move only when the test moves the clock, so motion is exact and
467
- repeatable. `@n-uf/motion/testing` (above) checks the frames you record.
468
-
469
- ## Benchmarks
470
-
471
- `pnpm bench` times the signals against alien-signals' and
472
- @preact/signals-core's own APIs on graphs of a few thousand nodes, and prints
473
- bundle sizes and the deepest chain each survives. Results and the choice
474
- they led to are in [bench/RESULTS.md](./bench/RESULTS.md).
75
+ ## Documentation
475
76
 
476
- ## Versions
77
+ - [Design page](https://github.com/n-uf/motion/blob/main/docs/motion.md): the concept, the parts, the rules a consumer relies on.
78
+ - [Reference](https://github.com/n-uf/motion/blob/main/docs/motion-reference.md): every entry point's API, rules and longer examples.
79
+ - [CHANGELOG](https://github.com/n-uf/motion/blob/main/packages/motion/CHANGELOG.md)
80
+ - Site and live demos: [motion.n-uf.com](https://motion.n-uf.com)
477
81
 
478
- Calendar versions `YY.M.R` (year, month of the release, counter within the
479
- month), the same scheme as `@n-uf/hypr-tiling`. `pnpm version:bump` sets the
480
- next one; never type one by hand.
82
+ Its sibling [`@n-uf/placement`](https://www.npmjs.com/package/@n-uf/placement) owns where things go.
481
83
 
482
84
  ## License
483
85
 
484
- [PolyForm Perimeter 1.0.1](./LICENSE).
86
+ [PolyForm Perimeter 1.0.1](https://github.com/n-uf/motion/blob/main/LICENSE).