Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/native-animation.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion examples/native/README.md
Original file line number Diff line number Diff line change
@@ -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.

Expand Down
32 changes: 29 additions & 3 deletions examples/native/src/App.ts
Original file line number Diff line number Diff line change
@@ -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"
Expand Down Expand Up @@ -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: (
Expand All @@ -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 }),
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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 }),
Expand Down
4 changes: 2 additions & 2 deletions packages/ui-native/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
10 changes: 9 additions & 1 deletion packages/ui-native/src/Native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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: {}
Expand Down Expand Up @@ -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
}

/**
Expand Down
45 changes: 39 additions & 6 deletions packages/ui-native/src/NativeHost.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -67,6 +79,11 @@ export interface UIManager {
isJSResponder: boolean,
blockNativeResponder: boolean
): void
configureNextLayoutAnimation(
config: object,
onEnd: () => void,
onFail: () => void
): void
}

/**
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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) {
Expand All @@ -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 = {
Expand All @@ -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)

Expand Down Expand Up @@ -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<typeof Native.Host> = {
command,
Expand Down Expand Up @@ -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)
}
Expand Down
17 changes: 17 additions & 0 deletions packages/ui-native/src/internal/kinds.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, object>()

/**
* Seeded with core vocabulary kinds here so `NativeHost` keeps them even when
* `Native.tags` is tree-shaken.
Expand Down
7 changes: 7 additions & 0 deletions packages/ui-native/src/internal/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
Loading
Loading