From 427202816851ca7500716a6c2eb3f4d258731827 Mon Sep 17 00:00:00 2001 From: Effect Bot Date: Sat, 28 Nov 2026 02:27:30 +0000 Subject: [PATCH 1/2] Add native animation to @effect/ui-native Animation drives opacity and transform on React Native's native animated driver, and LayoutAnimation animates a step's layout changes. --- .changeset/native-animation.md | 5 + examples/native/README.md | 2 +- examples/native/src/App.ts | 32 +- packages/ui-native/README.md | 4 +- packages/ui-native/src/Native.ts | 10 +- packages/ui-native/src/NativeHost.ts | 45 +- packages/ui-native/src/internal/kinds.ts | 17 + packages/ui-native/src/internal/node.ts | 7 + packages/ui-native/src/kit/Animation.ts | 927 ++++++++++++++++++ packages/ui-native/src/kit/LayoutAnimation.ts | 130 +++ packages/ui-native/src/kit/index.ts | 2 + packages/ui-native/test/Animation.test.ts | 371 +++++++ .../ui-native/test/AnimationFallback.test.ts | 41 + packages/ui-native/test/NativeHost.test.ts | 10 +- packages/ui-native/test/utils/FakeAnimated.ts | 228 +++++ packages/ui-native/test/utils/FakeFabric.ts | 22 + 16 files changed, 1831 insertions(+), 22 deletions(-) create mode 100644 .changeset/native-animation.md create mode 100644 packages/ui-native/src/kit/Animation.ts create mode 100644 packages/ui-native/src/kit/LayoutAnimation.ts create mode 100644 packages/ui-native/test/Animation.test.ts create mode 100644 packages/ui-native/test/AnimationFallback.test.ts create mode 100644 packages/ui-native/test/utils/FakeAnimated.ts diff --git a/.changeset/native-animation.md b/.changeset/native-animation.md new file mode 100644 index 000000000..d6d887faf --- /dev/null +++ b/.changeset/native-animation.md @@ -0,0 +1,5 @@ +--- +"@effect/ui-native": minor +--- + +Add `Animation` to animate opacity and transforms with React Native’s native driver, and `LayoutAnimation` to animate layout changes requested through `$.viewTransition`. Both are available from `@effect/ui-native/kit` and excluded from bundles that do not import them. diff --git a/examples/native/README.md b/examples/native/README.md index 2bf4575e5..4cb0b3649 100644 --- a/examples/native/README.md +++ b/examples/native/README.md @@ -1,6 +1,6 @@ # Native example -An Expo app built with `@effect/ui-native`: a counter, a controlled name input that Reset clears, nested text, and a scrolling list. It has no React components of its own; React Native's renderer is replaced by `NativeApp.register` in `src/main.ts`. +An Expo app built with `@effect/ui-native`: a counter, a controlled name input that Reset clears, nested text, and a scrolling list. The list's sticky header follows the scroll on the native driver, and new rows fade in with `LayoutAnimation`. It has no React components of its own; React Native's renderer is replaced by `NativeApp.register` in `src/main.ts`. The commands below run from this directory after `pnpm install` at the repository root, with the Android SDK and a JDK installed. The `android` and `ios` directories are generated and not committed. diff --git a/examples/native/src/App.ts b/examples/native/src/App.ts index 7a565fa29..63642b773 100644 --- a/examples/native/src/App.ts +++ b/examples/native/src/App.ts @@ -1,12 +1,20 @@ // Every export of this module is a component, so an edit to it swaps in // place in the dev client and keeps the count, the name and the list. -import { Image, Pan, Pressable, VirtualView } from "@effect/ui-native/kit" +import { + Animation, + Image, + LayoutAnimation, + Pan, + Pressable, + VirtualView +} from "@effect/ui-native/kit" import * as Native from "@effect/ui-native/Native" import * as Command from "@effect/ui/Command" import * as Component from "@effect/ui/Component" import * as Renderer from "@effect/ui/Renderer" import * as UiSchema from "@effect/ui/UiSchema" import * as Effect from "effect/Effect" +import { pipe } from "effect/Function" import * as Option from "effect/Option" import * as Schema from "effect/Schema" import mark from "./assets/mark.png" @@ -119,6 +127,7 @@ export const App = Native.component({ ClickedReset: ($) => $.evolve({ count: 0, name: "", notes: "" }), ChangedName: ($, { value }) => $.evolve({ name: value }), ChangedNotes: ($, { value }) => $.evolve({ notes: value }), + // New rows fade in as the list makes room for them. ClickedAdd: ($) => $.evolve({ items: ( @@ -127,7 +136,7 @@ export const App = Native.component({ ...items, `Item ${items.length + 1}: ${$.model.name || "stranger"}` ] - }), + }).viewTransition([LayoutAnimation.easeInEaseOut]), SelectedItem: ($, { item }) => $.evolve({ selected: item }), Dragged: ($, { dx }) => $.evolve({ dragged: $.model.dropped + dx }), Dropped: ($) => $.evolve({ dropped: $.model.dragged }), @@ -197,6 +206,8 @@ export const App = Native.component({ ) ) } + const list = h.id("list") + const scrolled = Animation.scroll(list, "y") return h.view.style({ flex: 1, paddingTop: 64, @@ -255,7 +266,22 @@ export const App = Native.component({ h.text.style({ fontSize: 16, color: "#374151" }).children( model.selected === "" ? "Tap an item" : `Selected ${model.selected}` ), - h.scroll.style({ flex: 1 }).children( + pipe(h.scroll.style({ flex: 1 }), Animation.source(list)).children( + // A sticky header: it moves down as far as the list scrolls up, on + // the UI thread, and its rule fades in once the rows pass under it. + pipe( + h.view.style({ backgroundColor: "white", zIndex: 1 }), + Animation.style({ transform: [{ translateY: scrolled }] }) + ).children( + h.text.style({ fontSize: 14, color: "#6b7280", paddingVertical: 8 }) + .children(`${model.items.length} items`), + pipe( + h.view.style({ height: 1, backgroundColor: "#d1d5db" }), + Animation.style({ + opacity: Animation.interpolate(scrolled, [0, 24], [0, 1], "clamp") + }) + ) + ), ...model.items.map((item) => Pressable(h, { onPress: Message.SelectedItem({ item }), diff --git a/packages/ui-native/README.md b/packages/ui-native/README.md index 70d05bbba..55cdb1aa8 100644 --- a/packages/ui-native/README.md +++ b/packages/ui-native/README.md @@ -10,7 +10,7 @@ React Native vocabulary and Fabric host for `@effect/ui`. Apps render native vie ## Modules - `Native`: `Native.component`, `Native.H`, the element vocabulary (`view`, `text`, `scroll`, `input`), style, prop and event types, `Native.Host`, `Native.clear`, `Native.setSelection`, and `Native.defineView` for custom native views -- `@effect/ui-native/kit`: native controls and APIs beyond the vocabulary, bundled only when imported. `Css` parses CSS strings into the style forms native reads, `Image` and `ImageBackground` render images, `RefreshControl` adds pull to refresh, and `Modal`, `SafeArea`, `Drawer` and `InputAccessory` are screen containers. `Pressable` adds press states, a pressed style and the Android ripple; `Pan` handles drags after a configurable movement threshold +- `@effect/ui-native/kit`: native controls and APIs beyond the vocabulary, bundled only when imported. `Css` parses CSS strings into the style forms native reads, `Image` and `ImageBackground` render images, `RefreshControl` adds pull to refresh, and `Modal`, `SafeArea`, `Drawer` and `InputAccessory` are screen containers. `Pressable` adds press states, a pressed style and the Android ripple; `Pan` handles drags after a configurable movement threshold. `Animation` animates `opacity` and `transform` on React Native's native driver, and `LayoutAnimation` animates a step's layout changes - `@effect/ui-native/assets`: ambient TypeScript declarations for static image imports (`import logo from "./logo.png"`) - `NativeHost`: `make`, the `Renderer.Host` that builds Fabric shadow trees and commits them to a surface - `NativeApp`: `mount`, `mountEffect`, and `register`, which runs an app on every surface native starts; the `Surface` service @@ -75,4 +75,4 @@ Use native prop names and plain style objects. React Native's `aria-*` and `id` ## Example -See `examples/native` and its README, which covers the development client, release builds and measuring the bundle. It is an Expo app with a counter, a controlled input, nested text, a draggable handle, and a scrolling list of pressable rows. Its `babel.config.cjs` runs TypeScript's type stripper before Expo's, because Metro compiles the workspace's TypeScript sources there and Flow's stripper rejects `declare` class fields. +See `examples/native` and its README, which covers the development client, release builds and measuring the bundle. It is an Expo app with a counter, a controlled input, nested text, a draggable handle, and a scrolling list of pressable rows under a sticky header. Its `babel.config.cjs` runs TypeScript's type stripper before Expo's, because Metro compiles the workspace's TypeScript sources there and Flow's stripper rejects `declare` class fields. diff --git a/packages/ui-native/src/Native.ts b/packages/ui-native/src/Native.ts index 1cb49a682..db41bf5f1 100644 --- a/packages/ui-native/src/Native.ts +++ b/packages/ui-native/src/Native.ts @@ -958,7 +958,8 @@ export interface ContentSizeChangePayload { /** * The events of a `view`. A press ends on the element, or at most 20 points * outside it. `layout` fires when layout changes the element's position or - * size. + * size. `animationEnd` fires when every transition `Animation.style` started + * on the element has reached its target. * * `accessibilityTap` (iOS) fires when VoiceOver activates an `accessible` * element, and `accessibilityEscape` (iOS) on VoiceOver's escape gesture. @@ -970,6 +971,7 @@ export interface ContentSizeChangePayload { export interface ViewEvents { readonly press: PressPayload readonly layout: LayoutPayload + readonly animationEnd: {} readonly accessibilityAction: AccessibilityActionPayload readonly accessibilityTap: {} readonly accessibilityEscape: {} @@ -1150,6 +1152,12 @@ export interface ViewHost { readonly fire: (node: NativeNode, event: string, payload: unknown) => void /** Commits the surface's changes now, outside a render. */ readonly commit: () => void + /** + * Gives the node a new native view, with a new tag, at the next commit. + * Its descendants get new views too, and native state such as a scroll + * offset is lost. + */ + readonly recreate: (node: NativeNode) => void } /** diff --git a/packages/ui-native/src/NativeHost.ts b/packages/ui-native/src/NativeHost.ts index e9a99ce54..c467e34d8 100644 --- a/packages/ui-native/src/NativeHost.ts +++ b/packages/ui-native/src/NativeHost.ts @@ -18,8 +18,20 @@ */ import type * as Renderer from "@effect/ui/Renderer" import type * as Context from "effect/Context" -import { flushInputs, kinds } from "./internal/kinds.ts" -import { isColor, markDirty, mounted, surface } from "./internal/node.ts" +import { + commits, + flushInputs, + kinds, + layouts, + props +} from "./internal/kinds.ts" +import { + container, + isColor, + markDirty, + mounted, + surface +} from "./internal/node.ts" import { drop, fire, rectOf, route } from "./internal/touch.ts" import * as Native from "./Native.ts" @@ -67,6 +79,11 @@ export interface UIManager { isJSResponder: boolean, blockNativeResponder: boolean ): void + configureNextLayoutAnimation( + config: object, + onEnd: () => void, + onFail: () => void + ): void } /** @@ -146,11 +163,11 @@ const defaultsOf = ({ host, kind: { defaults } }: NativeNode) => typeof defaults === "function" ? defaults(host) : defaults const rawText: Native.ViewKind = { viewName: "RCTRawText" } -const container: Native.ViewKind = { viewName: "" } let lastTag = 0 const none = {} +const noop = () => {} /** * Makes a host for the surface `rootTag`, and the node its root mounts in. @@ -214,6 +231,8 @@ export const make = (options: Options): { ) => { if (n.shadow !== undefined) ui.dispatchCommand(n.shadow, name, args) } + // The LayoutAnimation config for the next commit that changes the tree. + let layout: object | undefined const commit = () => { flushInputs(view) if (root.dirty) { @@ -225,8 +244,13 @@ export const make = (options: Options): { ui.appendChildToSet(set, build(place(k), rootTag)) } } + if (layout !== undefined) { + ui.configureNextLayoutAnimation(layout, noop, noop) + } ui.completeRoot(rootTag, set) } + layout = undefined + for (const hook of commits) hook(view) onCommit?.() } const view: Native.ViewHost = { @@ -236,7 +260,12 @@ export const make = (options: Options): { color, command, fire, - commit + commit, + // `build` recreates a view whose parent tag changed. + recreate(n) { + n.parentTag = 0 + markDirty(n) + } } const root = new NativeNode(surface, view) @@ -421,7 +450,11 @@ export const make = (options: Options): { else setProp(n, propOf(name), true) } }, - commit + commit, + viewTransition(update, types) { + for (const type of types) layout = layouts.get(type) ?? layout + update() + } } const operations: Context.Service.Shape = { command, @@ -457,7 +490,7 @@ const same = (a: any, b: any): boolean => { } const setProp = (n: NativeNode, name: string, value: unknown) => { - const set = n.kind.props?.[name] + const set = n.kind.props?.[name] ?? props.get(name) if (set === undefined) n.host.set(n, name, value) else set(n, value, n.host) } diff --git a/packages/ui-native/src/internal/kinds.ts b/packages/ui-native/src/internal/kinds.ts index 3afd4ae55..f0da166c7 100644 --- a/packages/ui-native/src/internal/kinds.ts +++ b/packages/ui-native/src/internal/kinds.ts @@ -184,6 +184,23 @@ const input: ViewKind = { } } +/** + * Setters for props any element takes, added by kit modules such as + * `Animation`, so the host carries none of their code. + * + * @internal + */ +export const props = new Map< + string, + (node: NativeNode, value: unknown, host: ViewHost) => void +>() + +/** Called after every commit, by kit modules that follow nodes. @internal */ +export const commits = new Set<(host: ViewHost) => void>() + +/** `LayoutAnimation` configs by view transition type. @internal */ +export const layouts = new Map() + /** * Seeded with core vocabulary kinds here so `NativeHost` keeps them even when * `Native.tags` is tree-shaken. diff --git a/packages/ui-native/src/internal/node.ts b/packages/ui-native/src/internal/node.ts index b50de8f7f..c129f2033 100644 --- a/packages/ui-native/src/internal/node.ts +++ b/packages/ui-native/src/internal/node.ts @@ -8,6 +8,13 @@ import type { NativeNode } from "../NativeHost.ts" */ export const surface: ViewKind = { viewName: "" } +/** + * The kind of the node holding a kept child out of the tree. + * + * @internal + */ +export const container: ViewKind = { viewName: "" } + /** * The root of the tree the node is in: a surface's root while mounted. * diff --git a/packages/ui-native/src/kit/Animation.ts b/packages/ui-native/src/kit/Animation.ts new file mode 100644 index 000000000..3227c672a --- /dev/null +++ b/packages/ui-native/src/kit/Animation.ts @@ -0,0 +1,927 @@ +/** + * Animates `opacity` and `transform` on React Native's native driver, so + * frames run on the UI thread with no JS in the loop. + * + * A view states what a style should be, and the driver gets it there: + * + * - A number is a target. When a render changes it, the driver animates + * from wherever the value is, with the element's transition. + * - An expression follows a native event: `scroll` reads a scroll view's + * offset, and `interpolate`, `add`, `multiply` and `diffClamp` derive + * from it. + * + * Nothing about an animation is kept in the Model. The `animationEnd` event + * fires when every target of the element has been reached, so `update` can + * pick the next one. + * + * Only `opacity` and `transform` are animated: React Native keeps the + * driver's values for those two when a later commit changes the view's + * other props. The element's `style` must not set them. + * + * Apps that don't import this module bundle none of it. + * + * **Example** (A sticky header, and a panel that fades in) + * + * ```ts + * import { Animation } from "@effect/ui-native/kit" + * import { pipe } from "effect/Function" + * + * // A header that scrolls away with the list, then stops. + * const list = h.id("list") + * h.view( + * pipe( + * h.view.style({ height: 80 }), + * Animation.style({ + * transform: [{ + * translateY: Animation.interpolate( + * Animation.scroll(list, "y"), + * [0, 80], + * [0, -80], + * "clamp" + * ) + * }] + * }) + * ), + * pipe(h.scroll, Animation.source(list)).children(rows) + * ) + * + * // A panel that fades in when it mounts, and out when `open` turns false. + * pipe( + * h.view, + * Animation.style({ opacity: model.open ? 1 : 0 }, Animation.spring(), { + * opacity: 0 + * }) + * ) + * ``` + * + * @stability experimental + * @since 0.1.0 + */ +import * as View from "@effect/ui/View" +import { dual } from "effect/Function" +import { get } from "react-native/Libraries/TurboModule/TurboModuleRegistry" +import { commits, props } from "../internal/kinds.ts" +import { container, rootOf, surface } from "../internal/node.ts" +import type * as Native from "../Native.ts" +import type { NativeNode } from "../NativeHost.ts" + +/** + * A transform the driver can animate. + * + * @stability experimental + * @category models + * @since 0.1.0 + */ +export type TransformKey = + | "translateX" + | "translateY" + | "scale" + | "scaleX" + | "scaleY" + +/** + * A target, or an expression the driver evaluates on the UI thread. + * + * @stability experimental + * @category models + * @since 0.1.0 + */ +export type Value = number | Expression + +/** + * A value derived from native events. Make one with `scroll`, + * `interpolate`, `add`, `multiply` or `diffClamp`. + * + * @stability experimental + * @category models + * @since 0.1.0 + */ +export type Expression = + | { + readonly _tag: "Scroll" + readonly source: string + readonly axis: "x" | "y" + } + | { + readonly _tag: "Interpolate" + readonly input: Value + readonly inputRange: ReadonlyArray + readonly outputRange: ReadonlyArray + readonly extrapolate: "extend" | "clamp" | "identity" + } + | { + readonly _tag: "Add" | "Multiply" + readonly left: Value + readonly right: Value + } + | { + readonly _tag: "DiffClamp" + readonly input: Value + readonly min: number + readonly max: number + } + +/** + * Animated style values. Each transform has one key, as in a React Native + * `transform`. + * + * @stability experimental + * @category models + * @since 0.1.0 + */ +export interface Style { + readonly opacity?: A | undefined + readonly transform?: + | ReadonlyArray<{ readonly [K in TransformKey]?: A }> + | undefined +} + +/** + * How a target is reached. Make one with `timing` or `spring`, or use + * `immediate`. + * + * @stability experimental + * @category models + * @since 0.1.0 + */ +export interface Transition { + /** The native driver's config, without `toValue`. */ + readonly config: object | undefined +} + +/** + * Sets the value at once. Like any transition, it commits the end value and + * fires `animationEnd`. + * + * @stability experimental + * @category transitions + * @since 0.1.0 + */ +export const immediate: Transition = { config: undefined } + +const frame = 1000 / 60 +const easeInOut = (t: number) => + t < 0.5 ? 4 * t * t * t : 1 - (2 - 2 * t) ** 3 / 2 + +/** + * Animates over `duration` milliseconds (300 by default) along `easing` + * (a cubic ease in and out by default), after `delay` milliseconds. The + * curve is sampled once per frame for the native driver. + * + * @stability experimental + * @category transitions + * @since 0.1.0 + */ +export const timing = (options?: { + readonly duration?: number | undefined + readonly easing?: ((t: number) => number) | undefined + readonly delay?: number | undefined +}): Transition => { + const easing = options?.easing ?? easeInOut + const count = Math.round((options?.duration ?? 300) / frame) + const frames: Array = [] + for (let i = Math.round((options?.delay ?? 0) / frame); i > 0; i--) { + frames.push(0) + } + for (let i = 0; i < count; i++) frames.push(easing(i / count)) + frames.push(easing(1)) + return { config: { type: "frames", frames, iterations: 1 } } +} + +/** + * Animates with a spring. The defaults match React Native's + * `Animated.spring`. + * + * @stability experimental + * @category transitions + * @since 0.1.0 + */ +export const spring = (options?: { + readonly stiffness?: number | undefined + readonly damping?: number | undefined + readonly mass?: number | undefined + readonly velocity?: number | undefined + readonly overshootClamping?: boolean | undefined +}): Transition => ({ + config: { + type: "spring", + stiffness: options?.stiffness ?? 230.2, + damping: options?.damping ?? 22, + mass: options?.mass ?? 1, + initialVelocity: options?.velocity ?? 0, + overshootClamping: options?.overshootClamping ?? false, + restDisplacementThreshold: 0.001, + restSpeedThreshold: 0.001, + iterations: 1 + } +}) + +/** + * The scroll offset along `axis` of the scroll view named `source` with + * `Animation.source`. It is `0` until the scroll view scrolls. + * + * @stability experimental + * @category expressions + * @since 0.1.0 + */ +export const scroll = (source: string, axis: "x" | "y"): Expression => ({ + _tag: "Scroll", + source, + axis +}) + +/** + * Maps `input` from `inputRange` onto `outputRange`, linearly between + * stops. Outside the range, `"extend"` (the default) continues the nearest + * segment, `"clamp"` holds its end and `"identity"` returns `input`. + * + * @stability experimental + * @category expressions + * @since 0.1.0 + */ +export const interpolate = ( + input: Value, + inputRange: ReadonlyArray, + outputRange: ReadonlyArray, + extrapolate: "extend" | "clamp" | "identity" = "extend" +): Expression => ({ + _tag: "Interpolate", + input, + inputRange, + outputRange, + extrapolate +}) + +/** + * The sum of two values. + * + * @stability experimental + * @category expressions + * @since 0.1.0 + */ +export const add = (left: Value, right: Value): Expression => ({ + _tag: "Add", + left, + right +}) + +/** + * The product of two values. + * + * @stability experimental + * @category expressions + * @since 0.1.0 + */ +export const multiply = (left: Value, right: Value): Expression => ({ + _tag: "Multiply", + left, + right +}) + +/** + * Follows the changes of `input`, held between `min` and `max`: a header + * that hides as a list scrolls down and comes back as soon as it scrolls up. + * + * @stability experimental + * @category expressions + * @since 0.1.0 + */ +export const diffClamp = ( + input: Value, + min: number, + max: number +): Expression => ({ _tag: "DiffClamp", input, min, max }) + +/** + * Animates the element's `opacity` and `transform` to `style`, with + * `transition` (`timing()` by default). A later call on the same element + * replaces the keys it sets, so each key can have its own transition. + * + * **Details** + * + * The element first shows `from`, or else `style`, and animates from there. + * An expression shows its value at a scroll offset of `0` until the driver + * takes over. When every target is reached, the end values are committed, + * so a press on a moved view lands where it is shown, and `animationEnd` + * fires. A target set with `immediate` is reached at once. + * + * **Gotchas** + * + * Native keeps showing the driver's last value for a key until the view is + * deleted. When a mounted element stops animating a key, it gets a new + * native view, which loses native state such as a scroll offset or focus. + * + * @stability experimental + * @category combinators + * @since 0.1.0 + */ +export const style: { + ( + style: Style, + transition?: Transition, + from?: Style + ): >(self: B) => B + >( + self: B, + style: Style, + transition?: Transition, + from?: Style + ): B +} = dual( + (args) => View.isElementBuilder(args[0]), + ( + self: Native.Element, + style: Style, + transition?: Transition, + from?: Style + ) => { + install() + const spec: Record = { ...(self.props.animation as Spec) } + for (const key in style) { + const value = style[key as keyof Style] + // A transform with no keys, such as `[]` or `[{}]`, animates nothing. + if ( + value === undefined || + (Array.isArray(value) && !(value as Transforms).some(hasKey)) + ) delete spec[key] + else spec[key] = { value, transition, from: from?.[key as keyof Style] } + } + return self.prop("animation", hasKey(spec) ? spec : undefined) + } +) + +const hasKey = (o: object): boolean => { + for (const _ in o) return true + return false +} + +/** + * Names a scroll view as the source of `scroll` expressions. Make the name + * with `h.id`, which is unique to the component instance, and pass it to the + * elements that follow the scroll, in this component or another. + * + * @stability experimental + * @category combinators + * @since 0.1.0 + */ +export const source: { + ( + name: string + ): >(self: B) => B + >( + self: B, + name: string + ): B +} = dual(2, (self: Native.ViewElement, name: string) => { + install() + return self.prop("animationSource", name) +}) + +type Transforms = NonNullable + +interface Layer { + readonly value: Value | Transforms + readonly transition: Transition | undefined + readonly from: number | Style["transform"] +} + +type Spec = Readonly> + +interface Target { + readonly tag: number + to: number + /** The running animation's id, or `0`. */ + anim: number +} + +interface Graph { + /** A props node for the node's own view, and one for its wrapper's. */ + readonly props: ReadonlyArray + /** Nodes other than the targets. */ + readonly nodes: Array + /** Parent and child tags, in pairs. */ + readonly edges: Array + readonly sources: Array +} + +interface Connection { + readonly tag: number + readonly outer: boolean + /** The view tag it is connected to, or `0`. */ + view: number +} + +interface Entry { + readonly node: NativeNode + spec: Spec | undefined + built: Spec | undefined + shape: string | undefined + /** The props the wrapper takes, if the graph was built for one. */ + outer: RegExp | undefined + graph: Graph | undefined + /** The value nodes of numeric leaves, by path. A rebuild keeps them. */ + readonly targets: Map +} + +interface Source { + node: NativeNode | undefined + /** The view tag the scroll events are bound to, or `0`. */ + bound: number + users: number + x?: number | undefined + y?: number | undefined +} + +/** What the driver follows on one surface. */ +interface Driver { + readonly entries: Map + readonly sources: Map +} + +/** The part of `NativeAnimatedModule` the driver uses. */ +interface AnimatedModule { + createAnimatedNode(tag: number, config: object): void + connectAnimatedNodes(parent: number, child: number): void + disconnectAnimatedNodes(parent: number, child: number): void + connectAnimatedNodeToView(tag: number, viewTag: number): void + disconnectAnimatedNodeFromView(tag: number, viewTag: number): void + dropAnimatedNode(tag: number): void + startAnimatingNode( + id: number, + tag: number, + config: object, + end: (result: { readonly finished: boolean }) => void + ): void + stopAnimation(id: number): void + setAnimatedNodeValue(tag: number, value: number): void + addAnimatedEventToView(viewTag: number, event: string, mapping: object): void + removeAnimatedEventFromView( + viewTag: number, + event: string, + valueTag: number + ): void + startOperationBatch?(): void + finishOperationBatch?(): void +} + +const drivers = new WeakMap() +// The specs shown without a native driver. +const plain = new WeakMap() +let animated: AnimatedModule | null | undefined +let installed = false +let batching = false +let fallback: Transition | undefined +// React Native's `Animated` counts node tags and animation ids from 1. +// Starting far above keeps the two apart in an app that loads both. +let lastTag = 1 << 24 + +const install = () => { + if (installed) return + installed = true + props.set("animation", setSpec) + props.set("animationSource", setSource) + commits.add(flush) +} + +const driverOf = (host: Native.ViewHost): Driver | undefined => { + // Bridgeless iOS registers the module under its TurboModule name. + if (animated === undefined) { + animated = (host.os === "ios" + ? get("NativeAnimatedTurboModule") + : null) ?? get("NativeAnimatedModule") ?? null + } + if (animated === null) return undefined + let d = drivers.get(host) + if (d === undefined) { + drivers.set(host, d = { entries: new Map(), sources: new Map() }) + } + return d +} + +const setSpec = (n: NativeNode, value: unknown, host: Native.ViewHost) => { + const spec = value as Spec | undefined + const d = driverOf(host) + if (d === undefined) { + // Without a native driver, the view shows its targets. + for (const key in plain.get(n)) { + if (spec?.[key] === undefined) host.set(n, key, undefined) + } + for (const key in spec) host.set(n, key, resolve(spec[key]!.value, true)) + if (spec === undefined) plain.delete(n) + else plain.set(n, spec) + return + } + const entry = d.entries.get(n) + if (entry !== undefined) { + let released = false + for (const key in entry.spec) { + if (spec?.[key] !== undefined) continue + host.set(n, key, undefined) + released = true + } + // Native keeps showing the driver's last value for a key the graph no + // longer drives, on both platforms, until the view is deleted. + if (released && entry.graph?.props.some((c) => c.view !== 0)) { + host.recreate(n.outer ?? n) + } + entry.spec = spec + return + } + if (spec === undefined) return + d.entries.set(n, { + node: n, + spec, + built: undefined, + shape: undefined, + outer: undefined, + graph: undefined, + targets: new Map() + }) + // Fabric flattens a view with no visual props, leaving the driver nothing + // to update. + host.set(n, "collapsable", false) + for (const key in spec) { + const layer = spec[key]! + host.set(n, key, resolve(layer.from ?? layer.value, true)) + } +} + +const setSource = (n: NativeNode, name: unknown, host: Native.ViewHost) => { + const d = driverOf(host) + if (d === undefined) return + for (const s of d.sources.values()) if (s.node === n) s.node = undefined + if (typeof name === "string") sourceOf(d, name).node = n +} + +const sourceOf = (d: Driver, name: string): Source => { + let s = d.sources.get(name) + if (s === undefined) { + d.sources.set(name, s = { node: undefined, bound: 0, users: 0 }) + } + return s +} + +// A style key's value, with scrolls at offset 0 when `at0`, or else +// `undefined` if it holds an expression. +const resolve = (value: Layer["value"], at0: boolean): unknown => { + if (typeof value === "number") return value + if (!Array.isArray(value)) { + return at0 ? evaluate(value as Expression) : undefined + } + const out: Array = [] + for (const item of value as Transforms) { + for (const key in item) { + const v = item[key as TransformKey]! + if (typeof v !== "number" && !at0) return undefined + out.push({ [key]: evaluate(v) }) + } + } + return out +} + +const evaluate = (v: Value): number => { + if (typeof v === "number") return v + switch (v._tag) { + case "Scroll": + return 0 + case "Add": + return evaluate(v.left) + evaluate(v.right) + case "Multiply": + return evaluate(v.left) * evaluate(v.right) + case "DiffClamp": + return Math.min(Math.max(evaluate(v.input), v.min), v.max) + case "Interpolate": { + const x = evaluate(v.input) + const at = v.inputRange + const to = v.outputRange + const last = at.length - 1 + if (v.extrapolate === "identity" && (x < at[0]! || x > at[last]!)) { + return x + } + let k = 1 + while (k < last && x > at[k]!) k++ + let t = (x - at[k - 1]!) / (at[k]! - at[k - 1]!) + if (v.extrapolate === "clamp") t = Math.min(Math.max(t, 0), 1) + return to[k - 1]! + t * (to[k]! - to[k - 1]!) + } + } +} + +// Paths identify numeric targets across rebuilds: `opacity`, `transform.0.scale`. +const leaves = ( + spec: Spec, + f: (path: string, value: Value, layer: Layer, from?: number) => void +) => { + for (const key in spec) { + const layer = spec[key]! + if (!Array.isArray(layer.value)) { + f(key, layer.value as Value, layer, layer.from as number | undefined) + continue + } + const items = layer.value as Transforms + const from = layer.from as Style["transform"] + for (let i = 0; i < items.length; i++) { + for (const name in items[i]) { + const k = name as TransformKey + f(key + "." + i + "." + name, items[i]![k]!, layer, from?.[i]?.[k]) + } + } + } +} + +// Two specs of one shape share a graph: they differ only in targets. +const shapeOf = (spec: Spec): string => { + let out = "" + leaves(spec, (path, value) => { + out += path + (typeof value === "number" ? ";" : JSON.stringify(value)) + }) + return out +} + +// Android runs the operations of a batch together, in one frame. +const native = (): AnimatedModule => { + if (!batching) { + batching = true + animated!.startOperationBatch?.() + } + return animated! +} + +const flush = (host: Native.ViewHost) => { + const d = drivers.get(host) + if (d === undefined) return + for (const [n, e] of d.entries) { + const top = rootOf(n).kind + // A node outside a surface or a kept child's container has been dropped. + if (e.spec === undefined || (top !== surface && top !== container)) { + release(e) + for (const t of e.targets.values()) drop(t) + d.entries.delete(n) + continue + } + // As React Native's `AnimatedScrollView`, the driver splits the keys + // between the view and its wrapper as the host splits the props. + const outer = n.outer?.kind.attach!(host)!.outer + if (e.spec !== e.built || outer !== e.outer) update(d, e, e.spec, outer) + // The host gives a recreated view a new tag, and native drops the view + // of a kept child that is out of the tree. + for (const c of e.graph!.props) { + const view = top === surface ? (c.outer ? n.outer! : n).tag : 0 + if (view === c.view) continue + const m = native() + if (c.view !== 0) m.disconnectAnimatedNodeFromView(c.tag, c.view) + if (view !== 0) m.connectAnimatedNodeToView(c.tag, view) + c.view = view + } + } + for (const [name, s] of d.sources) { + const top = s.node === undefined ? undefined : rootOf(s.node).kind + if (top !== undefined && top !== surface && top !== container) { + s.node = undefined + } + bind(s, top === surface && s.users > 0 ? s.node!.tag : 0, host.os) + if (s.users === 0) { + if (s.x !== undefined) native().dropAnimatedNode(s.x) + if (s.y !== undefined) native().dropAnimatedNode(s.y) + s.x = s.y = undefined + if (s.node === undefined) d.sources.delete(name) + } + } + if (!batching) return + batching = false + // iOS runs graph operations at the next mount, which a commit that only + // changes the graph doesn't make. Stopping an animation that doesn't + // exist runs them now. + if (host.os === "ios") animated!.stopAnimation(0) + animated!.finishOperationBatch?.() +} + +const mapping = (axis: "x" | "y", tag: number) => ({ + nativeEventPath: ["contentOffset", axis], + animatedValueTag: tag +}) + +const bind = (s: Source, view: number, os: string) => { + if (view === s.bound) return + const m = native() + for (const axis of ["x", "y"] as const) { + const tag = s[axis] + if (tag === undefined) continue + if (s.bound !== 0) { + m.removeAnimatedEventFromView(s.bound, "onScroll", tag) + // Both platforms bind `onScrollEnded` with `onScroll`, but only + // Android removes it with `onScroll`. + if (os === "ios") { + m.removeAnimatedEventFromView(s.bound, "onScrollEnded", tag) + } + } + if (view !== 0) { + m.addAnimatedEventToView(view, "onScroll", mapping(axis, tag)) + } + } + s.bound = view +} + +const update = ( + d: Driver, + e: Entry, + spec: Spec, + outer: RegExp | undefined +) => { + e.built = spec + const shape = shapeOf(spec) + if (shape !== e.shape || outer !== e.outer) { + e.shape = shape + e.outer = outer + rebuild(d, e, spec, outer) + } + let changed = false + leaves(spec, (path, value, layer) => { + const target = e.targets.get(path) + if (target === undefined || target.to === value) return + changed = true + go(e, target, value as number, layer.transition ?? (fallback ??= timing())) + }) + // An immediate change ends at once. Report it after the commit. + if (changed && idle(e)) { + Promise.resolve().then(() => { + if (e.graph !== undefined && idle(e)) settle(e) + }) + } +} + +// Replaces the graph, keeping the targets that are still numeric leaves and +// their running animations. +const rebuild = ( + d: Driver, + e: Entry, + spec: Spec, + outer: RegExp | undefined +) => { + const m = native() + release(e) + const kept = new Set() + const nodes: Array = [] + const edges: Array = [] + const sources: Array = [] + const make = (config: object, inputs: ReadonlyArray) => { + const tag = lastTag += 1 + m.createAnimatedNode(tag, config) + nodes.push(tag) + for (const input of inputs) { + m.connectAnimatedNodes(input, tag) + edges.push(input, tag) + } + return tag + } + const lower = (v: Value, path?: string, from?: number): number => { + if (typeof v === "number") { + if (path === undefined) { + return make({ type: "value", value: v, offset: 0 }, []) + } + kept.add(path) + let t = e.targets.get(path) + if (t === undefined) { + const value = from ?? v + const tag = lastTag += 1 + m.createAnimatedNode(tag, { type: "value", value, offset: 0 }) + e.targets.set(path, t = { tag, to: value, anim: 0 }) + } + return t.tag + } + switch (v._tag) { + case "Scroll": { + const s = sourceOf(d, v.source) + s.users++ + sources.push(s) + let tag = s[v.axis] + if (tag === undefined) { + tag = s[v.axis] = lastTag += 1 + m.createAnimatedNode(tag, { type: "value", value: 0, offset: 0 }) + if (s.bound !== 0) { + m.addAnimatedEventToView(s.bound, "onScroll", mapping(v.axis, tag)) + } + } + return tag + } + case "Interpolate": { + const input = lower(v.input) + return make({ + type: "interpolation", + inputRange: v.inputRange, + outputRange: v.outputRange, + outputType: null, + extrapolateLeft: v.extrapolate, + extrapolateRight: v.extrapolate + }, [input]) + } + case "DiffClamp": { + const input = lower(v.input) + return make( + { type: "diffclamp", input, min: v.min, max: v.max }, + [input] + ) + } + default: { + const input = [lower(v.left), lower(v.right)] + const type = v._tag === "Add" ? "addition" : "multiplication" + return make({ type, input }, input) + } + } + } + // The view's style, and its wrapper's. + const styles: [Record, Record] = [{}, {}] + const transforms: Array = [] + const moved: Array = [] + leaves(spec, (path, value, _, from) => { + const tag = lower(value, path, from) + const dot = path.lastIndexOf(".") + if (dot === -1) return styles[outer?.test(path) ? 1 : 0][path] = tag + transforms.push({ + type: "animated", + property: path.slice(dot + 1), + nodeTag: tag + }) + moved.push(tag) + }) + if (moved.length > 0) { + styles[outer?.test("transform") ? 1 : 0].transform = make( + { type: "transform", transforms }, + moved + ) + } + const props: Array = [] + for (let i = 0; i < 2; i++) { + const style = styles[i]! + const inputs = Object.values(style) + if (inputs.length === 0) continue + const tag = make({ type: "style", style }, inputs) + props.push({ + tag: make({ type: "props", props: { style: tag } }, [tag]), + outer: i === 1, + view: 0 + }) + } + e.graph = { props, nodes, edges, sources } + for (const [path, t] of e.targets) { + if (kept.has(path)) continue + drop(t) + e.targets.delete(path) + } +} + +const go = (e: Entry, t: Target, to: number, transition: Transition) => { + const m = native() + if (t.anim !== 0) m.stopAnimation(t.anim) + t.to = to + t.anim = 0 + const config = transition.config + if (config === undefined) return m.setAnimatedNodeValue(t.tag, to) + const id = t.anim = lastTag += 1 + m.startAnimatingNode(id, t.tag, { ...config, toValue: to }, (result) => { + if (t.anim !== id) return + t.anim = 0 + if (result.finished && idle(e)) settle(e) + }) +} + +const idle = (e: Entry): boolean => { + for (const t of e.targets.values()) if (t.anim !== 0) return false + return true +} + +// Commits the end values, so Fabric's shadow tree, and a view it recreates, +// show what the driver shows. +const settle = (e: Entry) => { + const n = e.node + const spec = e.built! + for (const key in spec) { + const value = resolve(spec[key]!.value, false) + if (value !== undefined) n.host.set(n, key, value) + } + n.host.commit() + n.host.fire(n, "animationEnd", {}) +} + +// Disconnects the graph and drops its nodes, but not the targets. +const release = (e: Entry) => { + const g = e.graph + if (g === undefined) return + const m = native() + e.graph = undefined + for (const c of g.props) { + if (c.view !== 0) m.disconnectAnimatedNodeFromView(c.tag, c.view) + } + for (let i = 0; i < g.edges.length; i += 2) { + m.disconnectAnimatedNodes(g.edges[i]!, g.edges[i + 1]!) + } + for (const tag of g.nodes) m.dropAnimatedNode(tag) + for (const s of g.sources) s.users-- +} + +const drop = (t: Target) => { + const m = native() + if (t.anim !== 0) m.stopAnimation(t.anim) + t.anim = 0 + m.dropAnimatedNode(t.tag) +} diff --git a/packages/ui-native/src/kit/LayoutAnimation.ts b/packages/ui-native/src/kit/LayoutAnimation.ts new file mode 100644 index 000000000..d6f631318 --- /dev/null +++ b/packages/ui-native/src/kit/LayoutAnimation.ts @@ -0,0 +1,130 @@ +/** + * Animates the next layout change with React Native's `LayoutAnimation`: + * views that a step adds, moves, resizes or removes animate into place. + * + * Name a config with `define`, or use a preset, and ask for it from the + * step whose render changes the layout. + * + * The host configures the animation just before it commits the render, and + * only if the render changes the tree. When a step asks for several, the + * last one it names wins. + * + * React Native 0.88 animates layout on Android only when the app turns on + * the `enableLayoutAnimationsOnAndroid` feature flag natively. Without it, + * the layout changes at once. + * + * **Example** (Expanding a row) + * + * ```ts + * import { LayoutAnimation } from "@effect/ui-native/kit" + * + * ClickedExpand: ($) => + * $.evolve({ expanded: true }).viewTransition([LayoutAnimation.spring]) + * ``` + * + * @stability experimental + * @since 0.1.0 + */ +import { layouts } from "../internal/kinds.ts" + +/** + * How views animate when they are created, updated or deleted. + * `springDamping` applies to the `"spring"` type. + * + * @stability experimental + * @category models + * @since 0.1.0 + */ +export interface Animation { + readonly type?: + | "spring" + | "linear" + | "easeInEaseOut" + | "easeIn" + | "easeOut" + | "keyboard" + | undefined + readonly property?: + | "opacity" + | "scaleX" + | "scaleY" + | "scaleXY" + | undefined + readonly duration?: number | undefined + readonly delay?: number | undefined + readonly springDamping?: number | undefined + readonly initialVelocity?: number | undefined +} + +/** + * A layout animation: its `duration` in milliseconds, and how views that are + * created, updated and deleted animate. + * + * @stability experimental + * @category models + * @since 0.1.0 + */ +export interface Config { + readonly duration: number + readonly create?: Animation | undefined + readonly update?: Animation | undefined + readonly delete?: Animation | undefined +} + +/** + * Registers `config` as the view transition type `name`, and returns + * `name` to pass to `$.viewTransition`. + * + * @stability experimental + * @category constructors + * @since 0.1.0 + */ +export const define = /* @__NO_SIDE_EFFECTS__ */ ( + name: string, + config: Config +): string => { + layouts.set(name, config) + return name +} + +/** + * Fades views in and out, and eases moves, over 300 ms. + * + * @stability experimental + * @category presets + * @since 0.1.0 + */ +export const easeInEaseOut: string = define("easeInEaseOut", { + duration: 300, + create: { type: "easeInEaseOut", property: "opacity" }, + update: { type: "easeInEaseOut" }, + delete: { type: "easeInEaseOut", property: "opacity" } +}) + +/** + * Fades views in and out, and moves them linearly, over 500 ms. + * + * @stability experimental + * @category presets + * @since 0.1.0 + */ +export const linear: string = define("linear", { + duration: 500, + create: { type: "linear", property: "opacity" }, + update: { type: "linear" }, + delete: { type: "linear", property: "opacity" } +}) + +/** + * Fades views in and out, and springs moves into place, over 700 ms. + * + * @stability experimental + * @category presets + * @since 0.1.0 + */ +export const spring: string = define("spring", { + duration: 700, + create: { type: "linear", property: "opacity" }, + update: { type: "spring", springDamping: 0.4 }, + delete: { type: "linear", property: "opacity" } +}) diff --git a/packages/ui-native/src/kit/index.ts b/packages/ui-native/src/kit/index.ts index a52581d3b..b020f9a26 100644 --- a/packages/ui-native/src/kit/index.ts +++ b/packages/ui-native/src/kit/index.ts @@ -15,11 +15,13 @@ // with `export * as`, in alphabetical order. export * from "./ActivityIndicator.ts" +export * as Animation from "./Animation.ts" export * as Css from "./Css.ts" export * from "./Drawer.ts" export * from "./Image.ts" export * from "./ImageBackground.ts" export * from "./InputAccessory.ts" +export * as LayoutAnimation from "./LayoutAnimation.ts" export * from "./Modal.ts" export * from "./Pan.ts" export * from "./Pressable.ts" diff --git a/packages/ui-native/test/Animation.test.ts b/packages/ui-native/test/Animation.test.ts new file mode 100644 index 000000000..353a131a1 --- /dev/null +++ b/packages/ui-native/test/Animation.test.ts @@ -0,0 +1,371 @@ +import * as Animation from "@effect/ui-native/kit/Animation" +import * as LayoutAnimation from "@effect/ui-native/kit/LayoutAnimation" +import { RefreshControl } from "@effect/ui-native/kit/RefreshControl" +import * as Native from "@effect/ui-native/Native" +import * as Renderer from "@effect/ui/Renderer" +import * as UiSchema from "@effect/ui/UiSchema" +import { pipe } from "effect/Function" +import * as Schema from "effect/Schema" +import { assert, describe, it, vi } from "vitest" +import * as FakeAnimated from "./utils/FakeAnimated.ts" +import * as FakeFabric from "./utils/FakeFabric.ts" + +const native = vi.hoisted(() => ({ animated: undefined as any })) +vi.mock( + "react-native/Libraries/TurboModule/TurboModuleRegistry", + () => ({ + get: (name: string) => + name === "NativeAnimatedModule" ? native.animated.module : null + }) +) +native.animated = FakeAnimated.make() +const animated: ReturnType = native.animated + +const Sticky = Native.component({ + name: "Sticky", + model: Schema.Struct({ shown: Schema.Boolean, horizontal: Schema.Boolean }), + message: UiSchema.TaggedEnum({ Flip: {}, Hide: {} }) +}).make({ + init: () => ({ shown: true, horizontal: false }), + update: { + Flip: ($) => $.evolve({ horizontal: (h) => !h }), + Hide: ($) => $.evolve({ shown: () => false }) + }, + view: (h, model) => { + const list = h.id("list") + const y = Animation.scroll(list, "y") + return h.view( + model.shown && pipe( + h.view.style({ height: 80 }), + Animation.style({ + transform: [{ + translateY: Animation.interpolate(y, [0, 80], [0, -80], "clamp") + }] + }) + ), + model.shown && + pipe(h.scroll.horizontal(model.horizontal), Animation.source(list)) + .children( + pipe( + h.view.style({ height: 400 }), + Animation.style({ + opacity: Animation.interpolate(y, [0, 200], [1, 0], "clamp") + }) + ) + ), + h.view.style({ width: 1 }) + ) + } +}) + +const Fade = Native.component({ + name: "Fade", + model: Schema.Struct({ open: Schema.Boolean, ended: Schema.Number }), + message: UiSchema.TaggedEnum({ Toggled: {}, Ended: {} }) +}).make({ + init: () => ({ open: true, ended: 0 }), + update: { + Toggled: ($) => $.evolve({ open: (open) => !open }), + Ended: ($) => $.evolve({ ended: (n) => n + 1 }) + }, + view: (h, model) => + h.view( + pipe( + h.view.style({ height: 10 }).on("animationEnd", { _tag: "Ended" }), + Animation.style( + { + opacity: model.open ? 1 : 0, + transform: model.open ? [] : [{ scale: 0.5 }] + }, + model.open + ? Animation.timing({ duration: 100 }) + : Animation.immediate, + { opacity: 0 } + ) + ), + pipe(h.text("ended " + model.ended), Animation.style({})) + ) +}) + +const Follow = Native.component({ + name: "Follow", + model: Schema.Struct({ axis: Schema.Literals(["x", "y"]) }), + message: UiSchema.TaggedEnum({ Switched: {} }) +}).make({ + init: () => ({ axis: "y" as const }), + update: { + Switched: ($) => $.evolve({ axis: (axis) => axis === "y" ? "x" : "y" }) + }, + view: (h, model) => { + const list = h.id("list") + const offset = Animation.scroll(list, model.axis) + return h.view( + pipe( + h.view.style({ height: 80 }), + Animation.style( + { + opacity: 1, + transform: [{ + translateY: Animation.interpolate(offset, [0, 100], [0, -100]) + }] + }, + Animation.timing({ duration: 100 }), + { opacity: 0 } + ) + ), + pipe(h.scroll, Animation.source(list)) + ) + } +}) + +const List = Native.component({ + name: "List", + model: Schema.Struct({ rows: Schema.Number, tick: Schema.Number }), + message: UiSchema.TaggedEnum({ Added: {}, Ticked: {} }) +}).make({ + init: () => ({ rows: 1, tick: 0 }), + update: { + Added: ($) => + $.evolve({ rows: (n) => n + 1 }).viewTransition([LayoutAnimation.spring]), + // Renders nothing new, so nothing is committed or animated. + Ticked: ($) => + $.evolve({ tick: (n) => n + 1 }).viewTransition([LayoutAnimation.spring]) + }, + view: (h, model) => + h.view( + Array.from({ length: model.rows }, (_, i) => + h.view.key(String(i)).style({ height: 20 })) + ) +}) + +const Pull = Native.component({ + name: "Pull", + model: Schema.Struct({ refreshable: Schema.Boolean }), + message: UiSchema.TaggedEnum({ Toggled: {} }) +}).make({ + init: () => ({ refreshable: true }), + update: { Toggled: ($) => $.evolve({ refreshable: (on) => !on }) }, + view: (h, model) => { + const list = h.id("list") + return h.view( + pipe( + h.view.style({ height: 80 }), + Animation.style({ + opacity: Animation.interpolate( + Animation.scroll(list, "y"), + [0, 100], + [1, 0] + ) + }) + ), + pipe( + h.scroll, + Animation.source(list), + Animation.style({ opacity: 0.5, transform: [{ translateY: 20 }] }) + ).children(model.refreshable && RefreshControl(h)) + ) + } +}) + +// Like React Native's, the fake animated module is shared by every surface, +// so tests that count its nodes run one at a time. +describe("Animation", { concurrent: false }, () => { + it("drives a sticky header from scroll events, across recreated views, until removed", async () => { + const before = { nodes: animated.nodes(), events: animated.events() } + const { close, find, root, settle } = await FakeFabric.mount((root) => + Renderer.mount(Sticky, {}, root) + ) + const header = () => find((n) => n.props.height === 80) + const hero = () => find((n) => n.props.height === 400) + const scroller = () => find((n) => n.viewName.endsWith("ScrollView")) + // The first frame shows each expression at offset 0. + assert.deepStrictEqual(header().props.transform, [{ translateY: 0 }]) + assert.strictEqual(header().props.collapsable, false) + assert.strictEqual(hero().props.opacity, 1) + + animated.scroll(scroller().tag, { y: 40 }) + assert.deepStrictEqual(animated.view(header().tag), { + transform: [{ translateY: -40 }] + }) + assert.deepStrictEqual(animated.view(hero().tag), { opacity: 0.8 }) + + // A horizontal scroll view on Android is another native view, so it + // and the hero inside it get new tags. + const old = { scroller: scroller().tag, hero: hero().tag } + root.send({ _tag: "Flip" }) + await settle() + assert.notStrictEqual(scroller().tag, old.scroller) + assert.notStrictEqual(hero().tag, old.hero) + animated.scroll(old.scroller, { y: 200 }) + assert.deepStrictEqual(animated.view(hero().tag), { opacity: 0.8 }) + animated.scroll(scroller().tag, { y: 200 }) + assert.deepStrictEqual(animated.view(header().tag), { + transform: [{ translateY: -80 }] + }) + assert.deepStrictEqual(animated.view(hero().tag), { opacity: 0 }) + + root.send({ _tag: "Hide" }) + await settle() + assert.deepStrictEqual( + { nodes: animated.nodes(), events: animated.events() }, + before + ) + // The renderer reused the header's node. Native keeps the driver's last + // values on a view, so the node gets a new one. + const reused = find((n) => n.props.width === 1) + assert.isUndefined(reused.props.transform) + assert.isUndefined(animated.view(reused.tag)) + await close() + }) + + it("animates to each target from where the value is, and reports the end", async () => { + const before = animated.nodes() + const { close, find, printed, root, settle } = await FakeFabric.mount(( + root + ) => Renderer.mount(Fade, {}, root)) + const panel = () => find((n) => n.props.height === 10) + assert.strictEqual(panel().props.opacity, 0) + assert.strictEqual(animated.running(), 1) + assert.isUndefined(find((n) => n.viewName === "RCTText").props.collapsable) + + // An immediate target interrupts the fade, and ends at once. + root.send({ _tag: "Toggled" }) + await settle() + await settle() + assert.strictEqual(animated.running(), 0) + assert.deepStrictEqual(animated.view(panel().tag), { + opacity: 0, + transform: [{ scale: 0.5 }] + }) + assert.include(printed(), "ended 1") + + root.send({ _tag: "Toggled" }) + await settle() + assert.strictEqual(animated.running(), 1) + animated.finish() + await settle() + assert.deepStrictEqual(animated.view(panel().tag), { opacity: 1 }) + assert.include(printed(), "ended 2") + // The end value is committed, so Fabric's shadow tree agrees. + assert.strictEqual(panel().props.opacity, 1) + + await close() + assert.strictEqual(animated.nodes(), before) + }) + + it("changes a graph without a mount on iOS, keeping a running fade", async () => { + animated.ios(true) + const before = { nodes: animated.nodes(), events: animated.events() } + try { + const { close, fabric, find, root, settle } = await FakeFabric.mount( + (root) => Renderer.mount(Follow, {}, root), + undefined, + "ios" + ) + const header = () => find((n) => n.props.height === 80) + const scroller = () => find((n) => n.viewName.endsWith("ScrollView")) + animated.progress(0.5) + // Following the other axis changes nothing Fabric commits. + const commits = fabric.calls.completeRoot + root.send({ _tag: "Switched" }) + await settle() + assert.strictEqual(fabric.calls.completeRoot, commits) + animated.scroll(scroller().tag, { x: 30, y: 60 }) + assert.deepStrictEqual(animated.view(header().tag), { + opacity: 0.5, + transform: [{ translateY: -30 }] + }) + assert.strictEqual(animated.running(), 1) + await close() + assert.deepStrictEqual( + { nodes: animated.nodes(), events: animated.events() }, + before + ) + } finally { + animated.ios(false) + } + }) + + it("follows each surface's own scroll view", async () => { + const before = animated.nodes() + const a = await FakeFabric.mount((root) => Renderer.mount(Follow, {}, root)) + const b = await FakeFabric.mount((root) => Renderer.mount(Follow, {}, root)) + const header = (s: typeof a) => s.find((n) => n.props.height === 80).tag + const scroller = (s: typeof a) => + s.find((n) => n.viewName.endsWith("ScrollView")).tag + animated.finish() + animated.scroll(scroller(a), { y: 40 }) + animated.scroll(scroller(b), { y: 10 }) + assert.deepStrictEqual(animated.view(header(a)), { + opacity: 1, + transform: [{ translateY: -40 }] + }) + await a.close() + animated.scroll(scroller(b), { y: 20 }) + assert.deepStrictEqual(animated.view(header(b)), { + opacity: 1, + transform: [{ translateY: -20 }] + }) + await b.close() + assert.strictEqual(animated.nodes(), before) + }) + + it("splits a wrapped scroll view's style between it and its refresh control, as Fabric does", async () => { + const before = { nodes: animated.nodes(), events: animated.events() } + const { close, find, root, settle } = await FakeFabric.mount((root) => + Renderer.mount(Pull, {}, root) + ) + const scroller = () => find(FakeFabric.byName("RCTScrollView")) + const views = () => + [scroller(), find(FakeFabric.byName("AndroidSwipeRefreshLayout"))] + .filter((n) => n !== undefined) + // What each view shows: the driver's value, or else Fabric's. + const shown = (key: string) => + views().map((n) => (animated.view(n.tag)?.[key] ?? n.props[key]) as any) + .filter((v) => v !== undefined) + const check = () => { + assert.deepStrictEqual(shown("transform"), [[{ translateY: 20 }]]) + assert.deepStrictEqual(shown("opacity"), [0.5]) + // Scroll events still come from the scroll view. + animated.scroll(scroller().tag, { y: 50 }) + assert.deepStrictEqual( + animated.view(find((n) => n.props.height === 80).tag), + { opacity: 0.5 } + ) + animated.scroll(scroller().tag, { y: 0 }) + } + check() + root.send({ _tag: "Toggled" }) + await settle() + assert.strictEqual(views().length, 1) + check() + root.send({ _tag: "Toggled" }) + await settle() + assert.strictEqual(views().length, 2) + check() + await close() + assert.deepStrictEqual( + { nodes: animated.nodes(), events: animated.events() }, + before + ) + }) +}) + +describe("LayoutAnimation", () => { + it("animates the commit of a step that asks for it and changes the tree", async () => { + const { fabric, root, settle } = await FakeFabric.mount((root) => + Renderer.mount(List, {}, root) + ) + root.send({ _tag: "Added" }) + await settle() + assert.deepStrictEqual(fabric.layouts, [undefined, { + duration: 700, + create: { type: "linear", property: "opacity" }, + update: { type: "spring", springDamping: 0.4 }, + delete: { type: "linear", property: "opacity" } + }]) + root.send({ _tag: "Ticked" }) + await settle() + assert.strictEqual(fabric.calls.configureNextLayoutAnimation, 1) + }) +}) diff --git a/packages/ui-native/test/AnimationFallback.test.ts b/packages/ui-native/test/AnimationFallback.test.ts new file mode 100644 index 000000000..900fb057a --- /dev/null +++ b/packages/ui-native/test/AnimationFallback.test.ts @@ -0,0 +1,41 @@ +import * as Animation from "@effect/ui-native/kit/Animation" +import * as Native from "@effect/ui-native/Native" +import * as Renderer from "@effect/ui/Renderer" +import * as UiSchema from "@effect/ui/UiSchema" +import { pipe } from "effect/Function" +import * as Schema from "effect/Schema" +import { assert, describe, it, vi } from "vitest" +import * as FakeFabric from "./utils/FakeFabric.ts" + +vi.mock( + "react-native/Libraries/TurboModule/TurboModuleRegistry", + () => ({ get: () => null }) +) + +const Panel = Native.component({ + name: "Panel", + model: Schema.Struct({ hidden: Schema.Boolean }), + message: UiSchema.TaggedEnum({ Toggled: {} }) +}).make({ + init: () => ({ hidden: true }), + update: { Toggled: ($) => $.evolve({ hidden: (hidden) => !hidden }) }, + view: (h, model) => { + const panel = h.view.style({ height: 10 }) + return h.view( + model.hidden ? pipe(panel, Animation.style({ opacity: 0 })) : panel + ) + } +}) + +describe("Animation without a native driver", () => { + it("shows the targets, and clears them when the element stops animating", async () => { + const { find, root, settle } = await FakeFabric.mount((root) => + Renderer.mount(Panel, {}, root) + ) + const panel = () => find((n) => n.props.height === 10) + assert.strictEqual(panel().props.opacity, 0) + root.send({ _tag: "Toggled" }) + await settle() + assert.isUndefined(panel().props.opacity) + }) +}) diff --git a/packages/ui-native/test/NativeHost.test.ts b/packages/ui-native/test/NativeHost.test.ts index bfae96415..8428ec1ed 100644 --- a/packages/ui-native/test/NativeHost.test.ts +++ b/packages/ui-native/test/NativeHost.test.ts @@ -73,15 +73,7 @@ const setup = async () => { return { ...mounted, colors } } -const touch = ( - fabric: ReturnType, - node: FakeFabric.ShadowNode, - end: "topTouchEnd" | "topTouchCancel" = "topTouchEnd", - at = { pageX: 10, pageY: 10 } -) => { - fabric.emit(node, "topTouchStart", {}) - fabric.emit(node, end, { changedTouches: [at] }) -} +const touch = FakeFabric.touch describe("NativeHost", () => { it("presses the nearest view with a press handler, unless cancelled or outside it", async () => { diff --git a/packages/ui-native/test/utils/FakeAnimated.ts b/packages/ui-native/test/utils/FakeAnimated.ts new file mode 100644 index 000000000..f1e6dcaff --- /dev/null +++ b/packages/ui-native/test/utils/FakeAnimated.ts @@ -0,0 +1,228 @@ +/** + * A stand-in for React Native's `NativeAnimatedModule` that evaluates the + * node graph as native does, so tests read what a view shows. It throws + * where native would fail or leak: a node created twice, an edge or a view + * connection to a missing node, or a node dropped while still connected + * or bound to an event. Like native, binding `onScroll` also binds + * `onScrollEnded`, which removing `onScroll` removes only on Android. + * + * Like native, a view keeps the values the driver last showed for its keys + * after the driver disconnects. With `ios` on, it holds graph operations + * until an operation iOS flushes: starting, stopping or setting a value. + */ +type Config = Record + +export const make = () => { + const nodes = new Map() + const parents = new Map>() + const views = new Map() + const events = new Map() + const running = new Map< + number, + { + node: number + from: number + toValue: number + end: (r: { finished: boolean }) => void + } + >() + const kept = new Map>() + const queued: Array<() => void> = [] + let ios = false + let open = false + const need = (tag: number) => { + const node = nodes.get(tag) + if (node === undefined) throw new Error("no animated node " + tag) + return node + } + const stop = (id: number) => { + const animation = running.get(id) + if (animation === undefined) return + running.delete(id) + animation.end({ finished: false }) + } + const value = (tag: number): number => { + const node = need(tag) + switch (node.type) { + case "value": + return node.value! + case "addition": + return value(node.input[0]) + value(node.input[1]) + case "multiplication": + return value(node.input[0]) * value(node.input[1]) + case "diffclamp": + return Math.min(Math.max(value(node.input), node.min), node.max) + case "interpolation": { + const x = value(parents.get(tag)![0]!) + const at = node.inputRange + const to = node.outputRange + const last = at.length - 1 + let k = 1 + while (k < last && x > at[k]) k++ + let t = (x - at[k - 1]) / (at[k] - at[k - 1]) + if (node.extrapolateLeft === "clamp") t = Math.max(t, 0) + if (node.extrapolateRight === "clamp") t = Math.min(t, 1) + return to[k - 1] + t * (to[k] - to[k - 1]) + } + } + throw new Error("not a value node " + tag) + } + const style = (tag: number) => { + const out: Record = {} + for (const [key, at] of Object.entries(need(tag).style as object)) { + out[key] = key === "transform" + ? need(at).transforms.map((t: Config) => ({ + [t.property]: value(t.nodeTag) + })) + : value(at) + } + return out + } + const module = { + startOperationBatch() { + if (open) throw new Error("batch started twice") + open = true + }, + finishOperationBatch() { + if (!open) throw new Error("no batch to finish") + open = false + }, + createAnimatedNode(tag: number, config: Config) { + if (nodes.has(tag)) throw new Error("node " + tag + " exists") + nodes.set(tag, { ...config }) + }, + connectAnimatedNodes(parent: number, child: number) { + need(parent) + need(child) + parents.set(child, [...(parents.get(child) ?? []), parent]) + }, + disconnectAnimatedNodes(parent: number, child: number) { + const list = parents.get(child) ?? [] + if (!list.includes(parent)) { + throw new Error("no edge " + parent + "->" + child) + } + parents.set(child, list.filter((p) => p !== parent)) + }, + connectAnimatedNodeToView(tag: number, view: number) { + if (need(tag).type !== "props") throw new Error("not a props node") + views.set(view, tag) + }, + disconnectAnimatedNodeFromView(tag: number, view: number) { + if (views.get(view) !== tag) throw new Error("not connected " + tag) + kept.set(view, shown(view)!) + views.delete(view) + }, + dropAnimatedNode(tag: number) { + need(tag) + for (const at of [...views.values(), ...events.values()]) { + if (at === tag) throw new Error("dropped connected node " + tag) + } + for (const [child, list] of parents) { + if (list.includes(tag) && nodes.has(child)) { + throw new Error("dropped node " + tag + " still feeds " + child) + } + } + nodes.delete(tag) + parents.delete(tag) + }, + startAnimatingNode( + id: number, + tag: number, + config: Config, + end: (r: { finished: boolean }) => void + ) { + if (need(tag).type !== "value") throw new Error("not a value node") + running.set(id, { + node: tag, + from: value(tag), + toValue: config.toValue, + end + }) + }, + stopAnimation: stop, + setAnimatedNodeValue(tag: number, to: number) { + for (const [id, a] of running) if (a.node === tag) stop(id) + need(tag).value = to + }, + addAnimatedEventToView(view: number, event: string, mapping: Config) { + need(mapping.animatedValueTag) + const key = view + ":" + event + ":" + mapping.nativeEventPath.join(".") + if (events.has(key)) throw new Error("event bound twice " + key) + events.set(key, mapping.animatedValueTag) + if (event === "onScroll") { + module.addAnimatedEventToView(view, "onScrollEnded", mapping) + } + }, + removeAnimatedEventFromView(view: number, event: string, tag: number) { + if (event === "onScroll" && !ios) { + module.removeAnimatedEventFromView(view, "onScrollEnded", tag) + } + for (const [key, at] of events) { + if (at === tag && key.startsWith(view + ":" + event + ":")) { + return void events.delete(key) + } + } + throw new Error("no event " + view + event) + } + } + const shown = (view: number) => { + const props = views.get(view) + const live = props === undefined + ? undefined + : style(need(props).props.style) + return live === undefined ? kept.get(view) : { ...kept.get(view), ...live } + } + const flushed = [ + "startAnimatingNode", + "stopAnimation", + "setAnimatedNodeValue" + ] + const deferred = Object.fromEntries( + Object.entries(module).map(([name, op]) => [ + name, + (...args: Array) => { + if (!ios || name.endsWith("OperationBatch")) return (op as any)(...args) + queued.push(() => (op as any)(...args)) + if (flushed.includes(name)) { + for (const run of queued.splice(0)) run() + } + } + ]) + ) as typeof module + return { + module: deferred, + /** Holds graph operations as iOS does, until one it flushes. */ + ios: (on: boolean) => { + ios = on + }, + /** The animated props view `tag` shows, live or kept from the driver. */ + view: shown, + /** Delivers a scroll event from view `tag` to the values bound to it. */ + scroll: ( + tag: number, + offset: { readonly x?: number; readonly y?: number } + ) => { + for (const axis of ["x", "y"] as const) { + const at = events.get(tag + ":onScroll:contentOffset." + axis) + if (at !== undefined) need(at).value = offset[axis] ?? 0 + } + }, + /** Moves every animation `t` of the way from its start to its end. */ + progress: (t: number) => { + for (const a of running.values()) { + need(a.node).value = a.from + (a.toValue - a.from) * t + } + }, + /** Runs every animation to its end. */ + finish: () => { + for (const [id, a] of running) { + running.delete(id) + need(a.node).value = a.toValue + a.end({ finished: true }) + } + }, + running: () => running.size, + nodes: () => nodes.size, + events: () => events.size + } +} diff --git a/packages/ui-native/test/utils/FakeFabric.ts b/packages/ui-native/test/utils/FakeFabric.ts index 81fdf982a..635675827 100644 --- a/packages/ui-native/test/utils/FakeFabric.ts +++ b/packages/ui-native/test/utils/FakeFabric.ts @@ -39,6 +39,9 @@ export const make = () => { parents.set(child.tag, parentTag) } let committed: ReadonlyArray = [] + // The LayoutAnimation configured for the next completeRoot, and each one's. + let layout: object | undefined + const layouts: Array = [] let handler: | ((handle: unknown, type: string, payload: unknown) => void) | undefined @@ -109,6 +112,8 @@ export const make = () => { count("completeRoot") set.forEach(seal) committed = set + layouts.push(layout) + layout = undefined }, registerEventHandler(h) { handler = h @@ -121,6 +126,10 @@ export const make = () => { }, setIsJSResponder(node: any, isResponder, block) { responders.push([node.tag, isResponder, block]) + }, + configureNextLayoutAnimation(config) { + count("configureNextLayoutAnimation") + layout = config } } return { @@ -128,6 +137,8 @@ export const make = () => { calls, commands, responders, + /** The LayoutAnimation config of each completeRoot, `undefined` for none. */ + layouts, /** Places the view with `tag` on screen, for hit tests and `measure`. */ place: (n: ShadowNode, rect: readonly [number, number, number, number]) => rects.set(n.tag, rect), @@ -163,6 +174,17 @@ export const find = ( export const byText = (s: string) => (n: ShadowNode) => n.viewName === "RCTRawText" && n.props.text === s +/** Presses `node`, or ends the touch with `end` at `at`. */ +export const touch = ( + fabric: ReturnType, + node: ShadowNode, + end: "topTouchEnd" | "topTouchCancel" = "topTouchEnd", + at = { pageX: 10, pageY: 10 } +) => { + fabric.emit(node, "topTouchStart", {}) + fabric.emit(node, end, { changedTouches: [at] }) +} + export const byName = (name: string) => (n: ShadowNode) => n.viewName === name /** From 776dedd3f98a0c3394696e7668710c1338ccf456 Mon Sep 17 00:00:00 2001 From: Effect Bot Date: Sat, 28 Nov 2026 06:34:16 +0000 Subject: [PATCH 2/2] Document scrollEventThrottle effect on Animation.source --- packages/ui-native/src/kit/Animation.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/ui-native/src/kit/Animation.ts b/packages/ui-native/src/kit/Animation.ts index 3227c672a..75277af3c 100644 --- a/packages/ui-native/src/kit/Animation.ts +++ b/packages/ui-native/src/kit/Animation.ts @@ -358,7 +358,10 @@ const hasKey = (o: object): boolean => { /** * Names a scroll view as the source of `scroll` expressions. Make the name * with `h.id`, which is unique to the component instance, and pass it to the - * elements that follow the scroll, in this component or another. + * elements that follow the scroll, in this component or another. Setting + * `scrollEventThrottle` to 17 ms or more (or a negative value on iOS) on the + * scroll view throttles the native driver too, because both platforms drop + * throttled events before delivering them to animated nodes. * * @stability experimental * @category combinators