# Gestures and motion

zero-native's version of react-native-gesture-handler + Reanimated + worklets, built our own way. The plan and its
decisions are in `docs/gestures-and-motion-v1.md` (D1–D10). This file is the reference: the model, every API, and the
do / don't / why. Android is built (registry 24); iOS has all of it, in every build since 2026-11-24 (§13, §14).
Where iOS differs in a detail, `docs/guides/platform-differences.md` §3 says so.

Code: `packages/core/src/motion.ts` (JS), `compiler/src/motion.ts` (derive), `android/runtime/.../ZnMotion.kt`
(values, animations), `ZnFormula.kt` (derive), `ZnGesture.kt` (gestures), `ZnMotionUi.kt` (element values, corners,
layout motion), `ZnShared.kt` (shared elements), `ZnReorder.kt` (List reorder), `ZnMotionApi.kt` (plugins, tilt).
iOS (`ios/ZnRuntime/Swift/`): `ZnMotionEngine.swift` and `ZnMotionModule.swift` (values, animations), `ZnFormula.swift`
(derive), `ZnMotionBindings.swift` (bindings), `ZnGesture*.swift` and `ZnZoom.swift` (gestures), `ZnElementMotion.swift`
(element values), `ZnLayoutMotion.swift` (animateLayout), `ZnShared.swift` (shared elements), `ZnListReorder.swift`
(List reorder), `ZnMotionApi.swift` and `ZnTilt.swift` (plugins, tilt).

## 1. The model in one paragraph

A **motion value** lives in native code. JS makes it (`useMotion(0)`), gives it to elements (`style={{ opacity: v }}`),
and sends it commands (`v.to(1)`). Native moves it frame by frame on the UI thread and draws every element bound to it
in the same frame, **with no JS in the loop**. A finger moves values through **gestures** (`usePan`) that are options,
not callbacks. Maths between values is **`derive(() => ...)`**, compiled at build time into a small formula native runs
each frame. JS hears only what it asks for: events (`onEnd`), and the value itself if it reads it (`v()`). So a drag
stays smooth while JS is busy.

Why not JS on the UI thread (Reanimated worklets)? A second JS runtime costs memory and start time, gives authors two
kinds of JS, and puts code from an OTA bundle on the UI thread. Formulas, springs, gestures as data and native plugin
sources cover what visuals need (plan §10).

## 2. Motion values

```tsx
const x = useMotion(0)                       // owned by the component: gone when it unmounts
<Box style={{ transform: [{ translateX: x }], opacity: x.map([0, 200], [1, 0]) }} />
await x.to(200)                              // spring (default); resolves { finished: true | false }
x.to(0, { duration: 250, easing: "standard" })
x.to(1, "bouncy"); x.to(1, 300); x.to(1, { spring: { damping: 20, stiffness: 200 } })
x.set(5); x.stop(); x.decay({ velocity: 800, clamp: [0, 300] })
x.sequence([{ to: 1, timing: 200 }, { set: 0 }, { decay: { velocity: 300 } }], { repeat: "forever", reverse: true })
x()          // read in JS (a signal: native starts sending changes); x.peek() reads without subscribing
```

- **Timings:** a number (ms tween), `"spring"`, `"bouncy"`, `{ duration, easing }` (easing: `"standard"`, `"linear"`,
  `"ease-in"`, `"ease-out"`, `"back"`, or `[x1, y1, x2, y2]`), `{ spring: { damping, stiffness, mass } }` (Reanimated's
  numbers), `{ spring: { duration, dampingRatio } }`, `overshootClamp`, or a plugin's `{ driver }` (§10).
- **Velocity hand-off:** a new command starts from where the value is, with the speed it has. Always on.
- **Promises in order:** an interrupted command resolves `{ finished: false }` before the next one resolves.
- **The finger wins (D2):** a command to a value a finger holds is dropped (`{ finished: false }`), unless
  `{ interrupt: true }`, which cancels the touch.
- **`.map(inputs, outputs, extrapolate?)`** (Reanimated's interpolate; `"clamp"` default, `"extend"`, `"identity"`) and
  **`.mapColor(inputs, colours)`** make derived values; they are made once per arguments.
- **`useTimeline({ duration, easing?, repeat?, yoyo? })`:** a 0 → 1 value with `play()` (resumes after `pause()` with
  the time left), `pause()`, `restart()`, `reverse()`, `seek(p)`. One timeline drives many elements through `.map`.
- **`follow(source, timing)`:** a value that chases another with a spring (chat heads, an elastic parallax).
- **`v.format({ decimals: 0 | 1 | 2, grouping: "en-IN" | "standard" | "none", prefix, suffix })`:** the value as
  native text, as the whole content of a `<Text>`: `<Text>{amount.format({ prefix: "₹" })}</Text>`. Indian grouping
  (12,34,567) by default; halves round away from zero; the minus goes before the prefix.
  Text around it in the same `<Text>` (`<Text>Saved {amount.format()}</Text>`) becomes its prefix and suffix (core
  `labelInText`). One format per `<Text>`.
- **Reduced motion:** with Android's "Remove animations" or iOS's Reduce Motion on, commands jump to their end and
  loops don't run.

## 3. Window and size values

`env.width`, `env.height`, `env.insets.top / bottom / start / end`, `env.keyboardHeight` (follows the keyboard frame by
frame), `env.keyboardTarget` (where it is going). Read them as `env.width()` inside `derive`. Inside `derive`, `self.width` / `self.height` (the element
the formula is bound on) and `parent.width` / `parent.height`. A route with `keyboard: "none"` lets a screen move things
itself with `env.keyboardHeight`. For a chat, add `keyboardDismissMode="interactive"` to its `<List>`: a drag on the
messages then moves the keyboard itself, and `env.keyboardHeight` follows (guide §76).

## 4. derive: maths each frame

```tsx
const tilt = derive(() => pan.x() / 18)
const fill = derive(() => clamp((pan.x() + 28) / parent.width, 0, 1))
const bg = derive(() => interpolateColor(progress(), [0, 1], ["#FFFFFF", "#5B5BD6"]))
```

- Read a motion value with `()` inside the arrow, as in JS. Allowed: numbers, motion values, `+ - * / %`, comparisons,
  `&& || !`, `? :`, `Math.min / max / abs / floor / ceil / round / sign / sqrt / pow / sin / cos / tan / atan2 /
  hypot / exp / log`, `Math.PI`, `clamp()`, `interpolate(x, [in], [out], extrapolate?)`, `interpolateColor()` (only as
  the whole formula), `self.*`, `parent.*`. Tables are literal numbers or top-level `const` numbers of the file.
- Any other name becomes an input fixed when the arrow is reached (a number) or a motion value. A signal or your own
  function is a build or run error with a hint: compute it in JS (one frame late) or make it a motion value.
- At most 64 steps and a stack of 16 (D1): split a long formula into two `derive`s. `x / 0 = 0`; NaN never reaches a
  view (the element keeps its last good value).
- **Why compiled:** the arrow never runs. The build turns it into postfix data native evaluates with no allocation.

## 5. What a motion value can drive

| Where | Keys |
|---|---|
| `style` | `opacity`, `backgroundColor` (a motion colour), `transform` (`translateX/Y`, `scale`, `scaleX/Y`, `rotate`, `rotateX`, `rotateY`), `cameraDistance`, `blurRadius` (Android 12+; every iOS version), border radii (corner morphs) |
| Svg parts | `fill`, `stroke` (motion colours), `opacity`, transforms, `trimStart / trimEnd / trimOffset` |
| `<Text>` | its content as `v.format(...)` |
| `<NativeView props>` | any prop a plugin reads with `scope.motion(name)` (§10); `<LottieView progress>` (registry 24) |
| `style` layout keys | `width`, `height` only (registry 24): one element lays out again each frame, its neighbours move with it |
| Gestures | anchors, magnets and bounds as `Coord`s (a value, `"N%"`, `"N%self"`, `"N%parent"`, dp) |

Other layout keys (`margin`, `padding`, `flex`...) don't follow a motion value. `width` / `height` do (registry 24), but
each frame lays the element and its neighbours out again: fine for one header or one panel, not for many rows. Prefer
a transform (`scaleY`, `translateY`) when the neighbours need not move, or `animateLayout` (§7) when the size only
changes now and then.

## 6. Gestures

```tsx
const pan = usePan({
  axis: "x",
  bounds: { x: [0, "100%"] },                     // "100%": the room to travel (parent minus own size)
  anchors: [{ id: "start", x: 0 }, { id: "paid", x: "100%" }],
  release: { threshold: { velocity: 400 } },      // or project: true (where a fling would stop), decay: true
  a11yLabel: "Slide to pay ₹499",                 // required with anchors (usePan throws): one TalkBack / VoiceOver action each
  haptic: { snap: "success" },
  onEnd: (e) => e.anchor === "paid" && pay(),
})
<Box gesture={pan} style={{ transform: [{ translateX: pan.x }] }} />
```

- **Zoom (registry 24):** `useZoom({ max: 5, doubleTap: 2.5, aspect })` gives `scale`, `x`, `y` for a photo: pinch
  around the fingers, pan inside the photo's edges, double tap to zoom in at the tap and back out, fling, rubber band
  past the edges and below 1x. Not zoomed, one finger is left to the parent (a pager, a drag to close); zoomed and
  dragged sideways at an edge, it lets the pager turn the page. Put the gesture on a box that fills the page and the
  transform on the photo inside: `transform: [{ translateX: z.x }, { translateY: z.y }, { scale: z.scale }]`.
  `aspect` (width / height, a number or a value) tells it where the photo's edges are inside the box.
  `z.zoomTo(3, { x, y })` and `z.reset()` from JS; TalkBack and VoiceOver get "zoom in" / "zoom out" actions.
- **Kinds:** `usePan` (x, y, progress, touchX, touchY, magnets), `usePinch` (scale, focalX, focalY, min / max),
  `useRotate` (angle), `useTap` (taps, maxDelay, maxDistance), `useLongPress` (pressed, held), `useFling` (directions).
- **Pan options:** `initial`, `bounds`, `rubber`, `anchors` (1D or 2D), `magnets` (`{ id, x, y, radius, pull }`, a pull
  toward a dismiss zone), `release`, `cross` + `onCross` (thresholds with haptics), `minDistance`,
  `activeOffsetX / Y`, `failOffsetX / Y`, `minPointers / maxPointers`, `activateAfterLongPress`, `dropZones`.
- **Events:** `onBegin`, `onStart`, `onUpdate` (coalesced; prefer bindings), `onEnd`, `onFinalize`, `onSettle`,
  `onMagnet`, `onCross`, `onZone`. `pan.snapTo(anchor)` springs it from JS (a failed payment springs the slider back).
- **One element, many gestures:** `Gesture.simultaneous(pinch, pan)`, `Gesture.exclusive(doubleTap, tap)` (in order),
  `Gesture.race(a, b)` (first wins). Groups nest.
- **With the scroll around it:** a one-axis pan leaves the other axis to the scroll. `withParent: "after-edge"` (an
  inner list scrolls first, then this moves: a sheet with a list), `"simultaneous"`, `"block"` (takes the touch even
  from a child).
- **Across elements (phase 3):** `requireToFail: [g]` (start only after g fails; fail if g starts),
  `simultaneousWith: [g]` (neither takes the touch from the other), `manualActivation: true` with
  `Gesture.activate(g)` / `Gesture.fail(g)` (one round trip to JS: use only when the rule can't be an option).
- **Drop zones:** `usePan({ dropZones: [m1, m2] })` with `useElementMotion()` objects bound on the targets; native
  compares the finger with their boxes, `onZone` hears enter / leave, `onEnd`'s `zone` says where it was dropped.
- **Edges:** a horizontal pan asks Android to keep the back gesture away from it (the whole element if ≤ 200 dp tall,
  else a 200 dp band, Android's limit). iOS's back swipe leaves the same area alone, only where the element shows.
- **At rest on an anchor,** the gesture follows the anchor if it moves (the keyboard opens), with no JS.

## 7. Layout motion

- **`animateLayout="spring"`** (or a timing): when the element's size or place changes, it animates there (a card
  that expands, siblings that reflow). Reanimated's layout transitions.
- **`<List itemAnimation="fade" | "move">`:** rows added, removed or moved animate.
- **`enter` / `exit`:** fade, fade-up, fade-down, scale, pop, slide-left / right / up / down, zoom, bounce, flip-x,
  flip-y, stretch-x, stretch-y, or your own `{ opacity, translateX, translateY, scale, rotateX, rotateY, scaleX, scaleY,
  duration | spring, delay }`. Flips and stretches need registry 24.
- **Shared elements:** `sharedTag={"store-" + id}` on an element of two screens. Push moves it from one to the other;
  Back and the predictive back gesture play it backwards with the finger. An `<Image>` moves as it is; other elements
  move their box and cross-fade. On iOS the edge swipe scrubs the flight with the finger and puts it back on cancel.
  Not inside a Sheet or Modal (they are their own windows), nor on a screen whose route has no transition, nor for a
  see-through screen's own tags; with reduced motion the screens change with no flight.

## 8. Values from elements

```tsx
const m = useElementMotion()
<Scroll motion={m}> ... </Scroll>
<Box style={{ opacity: m.scrollY.map([0, 120], [0, 1]) }} />    // a header that fades in, no JS
```

| Element | Values |
|---|---|
| any | `x`, `y`, `width`, `height` (the box in the window, dp), `measure()` (async, RN's measureInWindow) |
| `<Scroll>` | `scrollY` |
| `<List>` | `index`, `offset` (first visible row, how far past it), `scrollY` / `scrollX` (Android: exact near the top, estimated after; iOS: exact) |
| `<Carousel>` | `page` (2.5 = half way from 2 to 3) |
| `<Pressable>` | `pressed` (0 → 1, springy) |
| `<Sheet>` | `progress` (0 closed → 1 at the tallest detent; follows drag, open, close and predictive back; on iOS the default UIKit sheet only, not `ZN_IOS_SHEET=swiftui`) |
| pull to refresh | `pull` (0 → 1 at the refresh line, up to 1.5) |

`m.follow(v)` drives the scroll from a value on the UI thread: a Scroll by dp, a List by item index (3.5 = half way
through item 3), a Carousel by page. `null` stops. Use it for an A–Z side bar, tabs synced with pages.

A tab indicator that follows the finger: put the pages in a `<Carousel motion={m}>` and bind the indicator to
`m.page`. (`<Tabs>` itself shows one child and has no swipe, so it has no progress.)

## 9. JS hears values when it asks

- `v()` inside a component or effect subscribes: native sends changes, coalesced to one message per frame at most,
  final values first. `v.peek()` never subscribes.
- `useFrame(({ t, dt }) => ...)` calls JS once per frame for logic (a timer, a score). Frames are skipped, never
  queued, when JS is busy. Visuals belong in bindings.

## 10. Native plugins (the extension point, D8)

For what a formula can't do: custom physics, an audio level, a video's position, a sensor we don't ship.

```kotlin
// In the plugin's module (Kotlin): JS made the id.
function("orbit", onMain = true) { call ->
    val h = ZnMotionApi.value(call.int("id"))
    val job = ZnMotionApi.onFrame { now -> h.value = ...; true }   // no allocation here
    h.onDispose { job.cancel() }
    call.resolve()
}
ZnMotionApi.registerDriver("myplugin.wobble") { from, to, velocity, params -> object : ZnMotionApi.Driver { ... } }
// In a NativeView: a prop JS gave as a motion value, read while drawing.
val level = scope.motion("level")   // () -> Float, or null
```

```swift
// The same on iOS (ZnMotionApi.swift; ios/Sample/DeviceTestPlugin.swift has the whole orbit).
let h = ZnMotionApi.value(id)
let frames = ZnMotionApi.onFrame { now in h.value = ...; return true }
h.onDispose { frames.cancel() }
ZnMotionApi.registerDriver("myplugin.wobble") { from, to, velocity, params in ... }   // a ZnMotionDriver
let level = scope.motion("level")             // (() -> Float)?, read while drawing
scope.onMotion("level") { v in ... }          // iOS only: called on each frame the value moves (UIKit views)
```

```ts
// In the plugin's package (TS): helpers that call its module, so a bundle that uses them needs the plugin.
export const orbit = () => nativeMotion((id) => MyPlugin.orbit({ id }))
export const wobble = (): MotionTiming => ({ driver: "myplugin.wobble", params: { rings: 3 } })
```

Rules: main thread; what runs each frame must not allocate; in the app binary only (an OTA bundle can't add native
code). An app without the plugin refuses a bundle that calls its module; an unknown driver fails the command. The test
plugin `plugins/device-test` (iOS: `ios/Sample/DeviceTestPlugin.swift`) has a working example (orbit, wobble, the fake
view's `level`). `onDispose` adds a block on both platforms: earlier blocks run first, and each runs once.

`useTilt()` is the built-in sensor: `{ x, y }` from -1 to 1 (how the phone leans), smoothed, turned with the screen,
listening only while held and while the app is in front.

## 11. Drag to reorder

`<List reorderable onReorder={(from, to) => move(from, to)}>`: a long press on a row picks it up, a drag moves it
(the list scrolls near its edges), the drop calls `onReorder`. Move the row in your data there (remove at `from`,
insert at `to`). Until JS's rows change, the list shows the new order itself; if JS doesn't move it within 1 s, the row
glides back. Not with `stickyHeaderIndices` or `numColumns`. The rows glide to their new places (as `itemAnimation="move"`)
unless the List sets its own `itemAnimation`.

In a reorderable List the long press on a row **is** the pick-up, so a row's own `onLongPress` is ignored there (Pavan's
decision 7, 2026-11-21): neither iOS nor Android runs it (nor offers it to TalkBack / VoiceOver), and the compiler
warns at build time for every `onLongPress` in a row. The long press only drags. Use `onPress` or a button in the row
instead. The header, footer and empty item keep their `onLongPress`. With
pinned rows the List doesn't reorder, and `onLongPress` works as usual.

iOS uses UIKit's own drag and drop inside the list (the lift, the room the other rows make, the scroll near the ends,
VoiceOver's drag actions); the drag stays in the app.

## 12. Do / don't / why

- **Do** bind visuals to motion values; **don't** set signals from `onUpdate` to move things: that's a JS round trip
  per frame and it stutters when JS is busy.
- **Do** give a gesture with anchors or a tap an `a11yLabel`: TalkBack and VoiceOver users get an action per anchor.
  `usePan` with anchors throws without it.
- **Do** use `derive` for maths; **don't** call your own functions in it (build error): it runs natively.
- **Don't** animate layout keys each frame; use transforms or `animateLayout`.
- **Do** use `pan.snapTo` to put a slider back after a failed payment; **don't** fight the finger with `v.to` during a
  drag (it is dropped by design, D2).
- **Do** test with the "keep JS busy" button in the labs: a gesture must not care.
- **Porting from RN:** see `docs/rn-compatibility.md` "Gestures and motion". No RNGH / Reanimated aliases (D10).

## 13. Versions and OTA

Everything here needs registry 24 and the `Motion` module (version 1): an app file that imports a motion API from
`@zeronative/core` makes the bundle require `Motion 1`, so an older app build refuses it and keeps its own bundle. Flip and
stretch presets raise the bundle's registry need through the `transition.depth` format. Plugin sources and drivers
are gated by their plugin's module version.

iOS (2026-11-24): the engine is `Motion` v1 in every build, with Android's functions (a test,
`tools/test/motion-coverage.test.ts`, fails when Android registers one iOS lacks, or a plugin's driver). iOS apps
below host API 10 had a stub of the same name and number that answered every call "unavailable": the update server
sends them no bundle that requires `Motion` (docs/ota.md §3.2, "Motion on older iOS apps"). If one gets there anyway,
core (from 2026-11-24) treats an unavailable `to` / `decay` / `sequence` / `snapTo` / `zoomTo` as done at once and
says so once in the log (an older core rejects them at once). `ZN_MOTION_ENGINE=0` (environment, Debug builds only)
swaps the engine for ZnMotionOff, the old stub (every call "unavailable"), to see what an older iOS app does with a
bundle and to compare a screen's cost.

## 14. iOS port (for the iOS session)

Done (2026-11-24; docs/milestones-ios.md "Gestures and motion"). As built (`ios/ZnRuntime/Swift/`):
- Values, timings and commands: `ZnMotionEngine.swift` on a CADisplayLink, the maths in `ZnMotionMath.swift`
  (Android's numbers, checked by the `motion` Mac suite); formulas: `ZnFormula.swift`, op for op.
- Bindings: a slot that holds a motion value is read in a leaf modifier (`ZnMotionBindings.swift`: ZnLayer, the
  background, the corners, ZnSizeFrame); the value's cell is `@Observable`, so a moving value redraws only those
  modifiers, never a screen's body (about 5 ms of main thread per frame for 30 bound elements on the simulator: 4.8 ms
  Release, up to 5.9 with blur, 3D and corners; about 2 ms fixed per frame, then about 0.1 ms an element).
- Gestures: one hub per screen (`ZnGestureHub.swift`) feeds UITouches to recognizers ported from ZnGesture.kt
  (`ZnGestureRecognizers.swift`, the `gestures` Mac suite); useZoom is `ZnZoom.swift`, not a UIScrollView zoom.
- Element values: `ZnElementMotion.swift` (boxes, `pressed`, scroll values, follow); shared elements: `ZnShared.swift`
  with ZnSlideAnimator (`ZnNavHost.swift`) for the slide; reorder: UIKit drag and drop (`ZnListReorder.swift`); tilt:
  `ZnTilt.swift`; plugin API: `ZnMotionApi.swift`; transparent routes: `ZnSeeThrough.swift` (one box per opaque
  entry, drawn with the see-through screens over it, not a modal presentation).

The notes below are the port's plan, kept for the reasons.

Same JSON from JS; port in this order: values + timings (CADisplayLink), env values (keyboard frame notifications),
formulas (port ZnFormula.kt op for op: same opcodes, `x / 0 = 0`, JS Math.round), bindings (CALayer properties or
values read in a per-frame draw, never a SwiftUI body per frame), gestures (UIKit recognizers with a delegate:
`shouldRecognizeSimultaneouslyWith`, `shouldRequireFailureOf`, `gestureRecognizerShouldBegin` failing a sideways pan
on a vertical scroll; not SwiftUI `DragGesture` inside a ScrollView), element values (UIScrollView KVO, page from the
paging scroll), shared elements (zoom transitions / matchedGeometryEffect), reorder (UICollectionView drag), drop zones
(window rects), tilt (CMMotionManager gravity), plugin API (a Swift `ZnMotionApi` with the same three parts). Kotlin
tests in `ZnMotionTest.kt` list the numbers the Swift port must match.
Two rules found on the phone: a value JS disposed stays readable at its last value for whatever still draws it (a
leaving screen keeps its dragged place for its exit, its ₹ text stays); and a node whose only motion prop is
`sharedTag` still gets the shared-element modifier.
Registry 24, second batch (2026-11-09):
- **useZoom:** port `ZnZoomMath` (ZnZoom.kt) as it is, with `ZnZoomTest.kt`'s numbers. A UIPinch + UIPan pair with
  `shouldRecognizeSimultaneouslyWith`, the pan failing when not zoomed with one finger (so a parent pager or drag gets
  it), and failing at the edge it is dragged toward. Not a `UIScrollView` zoom: its values would not be zn motion values.
- **Scroll snapping and events:** `scrollViewWillEndDragging(_:withVelocity:targetContentOffset:)` picks the snap point
  with `ZnSnap.pick`'s rules (offsets, interval, alignment, start / end); `isPagingEnabled` for `pagingEnabled`;
  `decelerationRate` maps to `.normal` / `.fast` or the number. One event (`onScrollEvent`, id 27) with `k` = "s", "b",
  "e", "mb", "me" and RN's `nativeEvent` fields; "s" at most once per frame unless the throttle says less often.
- **Transparent route:** `modalPresentationStyle = .overFullScreen` with no transition (the screen animates itself), so
  the screen below stays drawn. No shared elements into it (same as Android).
- **Image viewer:** the TSX screen is shared. iOS needs only the view `imageviewer.page` (load with headers / held data,
  EXIF, draw moved by `scale` / `x` / `y` each frame with a CALayer transform, a sharp tile once the zoom rests, events
  `loaded` {width, height} and `error`) and `hold`. `ios/ImageViewerPlugin.swift`'s full screen goes once Android's old
  screen is deleted.
- **Width / height from a value:** set the frame in a per-frame layout pass (CADisplayLink, then setNeedsLayout), never
  a SwiftUI body per frame.
- **Lottie progress from a value:** set `LottieAnimationView.currentProgress` each frame from the value.

`keyboardDismissMode` (Scroll / List, registry 24) is UIScrollView's own `keyboardDismissMode`: `.onDrag` and
`.interactive` (with `.interactiveWithAccessory` not needed). Android's "on-drag" also clears focus, as iOS resigns
the first responder.
