# `@effect/ui-native` React Native vocabulary and Fabric host for `effect/ui`. Apps render native views through Fabric without React, and run in Expo or any React Native app on the New Architecture. ## Requirements - Peer dependencies: `effect`, `effect/ui`, `react-native` (`>=0.88.0`), `vite` (`^8`) for pre-bundled release builds, and `flow-remove-types` and `sucrase` for tests - The New Architecture (Fabric) and Hermes ## Modules - `Native`: `Native.component`, `Native.H`, the element vocabulary (`view`, `text`, `scroll`, `input`), style, prop and event types, `Native.Host`, `Native.Device`, `Native.clear`, `Native.setSelection`, `Native.defineView` for custom native views, and `Native.hostedView` for views the app registers in Swift - `@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. `KeyboardAvoidingView` keeps content above the keyboard. `Stack` draws a `NativeRouter` stack of screens, `StackTransition` and `StackSwipe` add its push and pop transition and iOS swipe-back, and `Link` navigates on press. The device APIs come as namespaces (`AccessibilityInfo`, `Alert`, `AppState`, `Appearance`, `BackHandler`, `Dimensions`, `I18nManager`, `Keyboard`, `Linking`, `PermissionsAndroid`, `PlatformColor`, `Share`, `StatusBar`, `Vibration`) - `@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, whose `props` follow the surface's props as native updates them - `NativeRouter`: `layer`, which provides `effect/ui`'s `Router` on a history in memory, with Android Back and deep links. A root holds its screens with `effect/ui`'s `RouterStack` - `NativeHttpClient`: `layer`, an `HttpClient` with incremental text responses; `ResponseType` selects text or buffered binary responses - `@effect/ui-native/networking`: opt-in side-effect entry that installs React Native's networking globals (`fetch`, `XMLHttpRequest`, `WebSocket`, `URL`, `AbortController`) - `@effect/ui-native/node`: `NativeMetro.withEffectUi`, the Metro configuration, and `NativeVitest.plugin`, the Vitest configuration - `@effect/ui-native/testing`: `TestDevice`, a fake `Native.Device` for Play tests ## Setup The module the bundle starts at registers the app: ```ts // src/main.ts import * as NativeApp from "@effect/ui-native/NativeApp" import { App } from "./App.ts" NativeApp.register(NativeApp.mount(App, {})) ``` Point `main` in `package.json` at it, and wrap the Metro configuration: ```ts // metro.config.ts import { NativeMetro } from "@effect/ui-native/node" import ExpoMetro from "expo/metro-config" export default NativeMetro.withEffectUi( ExpoMetro.getDefaultConfig(import.meta.dirname) ) ``` A release build (`NODE_ENV=production`, as `expo export` and Gradle's release tasks set it) is pre-bundled with Vite, which tree-shakes `effect` and `effect/ui`, and Metro bundles the result with React Native. Static `import`s of assets (`resolver.assetExts`) are left to Metro automatically so scale variants and files are preserved; use `import` rather than `require`, which pre-bundling rejects. Packages with native code are left to Metro: `react-native`, `expo`, and their scoped and prefixed packages by default, and any others named in the `external` option. Each platform in `platforms` (`["android", "ios"]` by default) gets a pre-bundle using Metro's `sourceExts` and `resolverMainFields`. For each source extension, resolution tries the platform suffix, then `.native`, then no suffix. Platforms without a pre-bundle, such as web, use the sources. An app's `resolver.resolveRequest` also runs for non-external imports in the pre-bundle: - Return a source file, asset files, or an empty module. - Delegate to `context.resolveRequest` to let Vite resolve an import, including a renamed import or a changed origin. - Do not read the delegated result's `filePath` or request another platform. Either fails the release build: Vite resolves asynchronously and only for the build's platform. In development Metro serves the sources. Editing a module that exports only components swaps them in place and keeps their state; editing any other module reloads the app. To inspect an app with DevTools, see [React Native](../devtools/README.md#react-native) in the `@effect/ui-devtools` README. The package has one native view, `EffectUIStickyHeader`, which `VirtualList` uses to pin `sticky` headers, and on iOS and macOS a host for views the app registers (see [Native views](#native-views)). Autolinking adds them as a pod on iOS and macOS and as a Gradle module on Android, so they are in any build made after `pod install` or `expo prebuild`. Expo Go doesn't have them, and lists there show headers that scroll with their rows. ## macOS On macOS (`react-native-macos`), the `EffectUINative` pod also ships an opt-in Swift helper, `EffectUIWindow`, for configuring window chrome, backdrops, transparent React roots, and text field blur. Nothing runs when the pod loads; each app opts in from Swift. In a SwiftUI `App`: ```swift import EffectUINative import React import React_RCTAppDelegate import SwiftUI @main struct MyApp: App { @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene { Window("MyApp", id: "main") { ReactNativeView(factory: appDelegate.reactNativeFactory) .effectUIWindow(backdrop: .glass, toolbar: .unifiedInset) } .windowStyle(.hiddenTitleBar) } } class ReactNativeDelegate: RCTDefaultReactNativeFactoryDelegate { override func customize(_ rootView: RCTRootView) { EffectUIWindow.transparentRoot(rootView) } } ``` Or configure an AppKit `NSWindow` directly: ```swift EffectUIWindow.configure( window, backdrop: .glass, toolbar: .unifiedInset, blurOnOutsideClick: true ) ``` Options: - `backdrop`: `.glass` (`NSGlassEffectView` on macOS 26, `NSVisualEffectView` with `.hudWindow` and `.behindWindow` before it), `.material(...)` (an `NSVisualEffectView` with `.behindWindow` blending), or `.none` (default). Whenever a backdrop is set, the window is made non-opaque with a clear background; call `EffectUIWindow.transparentRoot(rootView)` in `customize(_:)` so the backdrop shows where views draw no background. - `toolbar`: `.unifiedInset` adds an empty unified `NSToolbar` and hides the title so the traffic lights align with a 52pt top row. `.none` (default) leaves the title bar alone. - `blurOnOutsideClick` (default `true`): ends editing on a left click outside any `NSText` or `NSTextField`, or on Escape. One shared local `NSEvent` monitor serves every opted-in window and is removed while none remain. Without `blurOnOutsideClick`, AppKit keeps text fields focused through clicks on React views because React views cannot take first responder. Resigning first responder causes native to emit `topBlur`, firing the input's `blur` handler and keeping focus tracking in sync. ## Native views ### Overview Render an app's `UIView` (iOS), `NSView` (macOS) or SwiftUI view from JS without writing Fabric code. Register a factory and its prop names in Swift, then use a typed builder in JS to create elements and handle native events. ### Register a view in Swift Register each name once, before React Native starts, in `application(_:didFinishLaunchingWithOptions:)` on iOS or `applicationDidFinishLaunching(_:)` on macOS. Names must not start with `RCT`, which Fabric strips. For example, this macOS checkbox receives `checked` and `label` props and emits a `change` event: ```swift import AppKit import EffectUINative final class CheckboxView: NSButton, EffectUIHostedView { private let ctx: EffectUIContext init(_ ctx: EffectUIContext) { self.ctx = ctx super.init(frame: .zero) setButtonType(.switch) target = self action = #selector(toggled) } required init?(coder: NSCoder) { nil } func update(_ changed: [String: Any]) { if let checked = changed["checked"] as? Bool { state = checked ? .on : .off } if let label = changed["label"] as? String { title = label } } @objc private func toggled() { ctx.emit("change", ["checked": state == .on]) } } EffectUI.register("AppCheckbox", props: ["checked", "label"]) { ctx in CheckboxView(ctx) } ``` ### Create elements in JS Call `Native.hostedView` once per name at module scope. Its type parameters describe the custom props and event payloads. Pass `h` to the returned function to get a builder: ```ts import { Native } from "@effect/ui-native" const Checkbox = Native.hostedView< { readonly checked: boolean; readonly label: string }, { readonly change: { readonly checked: boolean } } >("AppCheckbox") Checkbox(h) .props({ checked: model.done, label: "Done" }) .on("change", ({ checked }) => Msg.Toggled({ checked })) ``` The builder also accepts view styles, props and events. Custom event names cannot overlap with `ViewEvents` (such as `layout`, `click` and `press`) or the reserved gesture names `pressIn` and `pan`. ### Update props, size and children - `update(_:)` receives only changed registered props, on the main thread. Removed props arrive as `NSNull`; props named `color` or ending in `Color` arrive as `NSColor` or `UIColor`. - The native view fills its element. Each axis left `auto` uses the view's `intrinsicContentSize`; an explicit `width` or `height` takes precedence. The host reads the size after each `update(_:)`. Call `ctx.invalidateSize()` if the size changes outside a prop update. - React children mount in `contentView`. This view should fill the hosted view and contain only React children. On macOS it must return `true` from `isFlipped`. The default is `nil`, which mounts children above the hosted view. ### Register a SwiftUI view Use `EffectUI.register(name, props:) { props, ctx in ... }` for SwiftUI content. The closure receives all current props whenever a prop changes. The host uses SwiftUI's ideal size for axes left `auto`. ### Handle the activating click on macOS AppKit asks the view under the pointer whether it accepts the click that activates an inactive window. Hosted views retain their `acceptsFirstMouse(for:)` behavior: the `NSButton` checkbox above toggles on that click. Override the method to change this behavior. For React content, set `acceptsFirstMouse` on the pressable view to accept the activating click. The hit view can inherit the prop from an enclosing React view, so a text child also accepts it. The prop defaults to `false`. ## Device APIs The kit's device APIs use native modules and device events directly rather than React Native's JavaScript wrappers. `NativeApp.register` provides their `Native.Device` service. Tests can provide `TestDevice` (see Testing); without a device, defaults include a 0×0 window at scale 1, the `"active"` app state, and a hidden keyboard. They come in three forms: - Effects, such as `Linking.openURL(url)` and `Dimensions.get`. Fallible calls report `Native.DeviceError`. - Commands for `update`, such as `Keyboard.Dismiss` and `Alert.Alert`. Commands for fallible calls return a `Result`. - Subscriptions and Streams of device events, such as `Dimensions.onChange` and `Keyboard.changes`. ```ts import { Linking } from "@effect/ui-native/kit" import { Command } from "effect/ui" // In update: $.run(Linking.Open.make({ url: "https://effect.website" }).pipe(Command.asNoop)) ``` On Android, Back closes the app when nothing handles it. The kit's `BackHandler.onPress` handles it while its Subscription runs, and React Native's `BackHandler` takes over that default as it does in a React app. Use one of them: each closes the app when its own handlers pass on a press. Under `NativeRouter`, Back goes back one screen before it closes the app. React Native doesn't load the `expo` package itself: an app that doesn't import it saves about 1 MB of Hermes bytecode. Use `NativeHttpClient.layer` for HTTP requests, including NDJSON RPC. React Native's `fetch` has no response body stream. To use `fetch`, `XMLHttpRequest` or `WebSocket`, add `import "@effect/ui-native/networking"` to the entry module. ## Storage and third-party native modules The kit's device APIs and `TestDevice` cover React Native's own native modules. A capability from another package, such as storage, haptics or biometrics, goes in a service the app defines: a `Context.Service` with a Layer that calls the package, provided at mount. A test provides a fake Layer for that service beside `TestDevice.layer(...)`. `QueryPersistence.layerKvs` saves `persist: true` queries to the existing `KeyValueStore` service from `effect/persistence`. Provide a Layer that adapts the store. For example: ```ts // src/storage.ts import { Effect, Layer } from "effect" import { KeyValueStore } from "effect/persistence" import { createMMKV } from "react-native-mmkv" const attempt = (method: string, f: () => A) => Effect.try({ try: f, catch: (cause) => new KeyValueStore.KeyValueStoreError({ method, message: `MMKV ${method} failed`, cause }) }) export const layerMmkv = Layer.sync(KeyValueStore.KeyValueStore, () => { const storage = createMMKV() return KeyValueStore.makeStringOnly({ get: (key) => attempt("get", () => storage.getString(key)), set: (key, value) => attempt("set", () => storage.set(key, value)), remove: (key) => attempt("remove", () => void storage.remove(key)), clear: attempt("clear", () => storage.clearAll()), size: attempt("size", () => storage.length), keys: attempt("keys", () => storage.getAllKeys()) }) }) ``` For an async store such as AsyncStorage, use `Effect.tryPromise` in place of `Effect.try`. For SQLite, `KeyValueStore.layerSql` builds the store on a `SqlClient`. `layerKvs` restores from the store's list of keys, which `expo-secure-store` cannot provide. Provide persistence beside `AppState.layerVisibility` at mount: ```ts // src/main.ts import { AppState } from "@effect/ui-native/kit" import * as NativeApp from "@effect/ui-native/NativeApp" import { Layer } from "effect" import { QueryPersistence } from "effect/ui" import { App } from "./App.ts" import { layerMmkv } from "./storage.ts" const persistence = QueryPersistence.layerKvs({ prefix: "app", maxAge: "7 days" }).pipe(Layer.provide(layerMmkv)) NativeApp.register( NativeApp.mount(App, {}).pipe( Layer.provide(Layer.merge(AppState.layerVisibility, persistence)) ) ) ``` Saved results show on the first frame, and `AppState.layerVisibility` refetches stale queries when the app returns to the foreground. To test a restore, run two sessions over one `KeyValueStore.layerMemory`, each building its own `layerKvs`, as the [`QueryPersistence` module example](../../effect/src/ui/QueryPersistence.ts) does. In a Play, provide `TestDevice.layer(...)` beside them. Tests that don't check persistence need no store. Metro doesn't tree-shake the packages left to it (see [Setup](#setup)), so a release carries every module they import. A package that imports from `react-native`, rather than from a file inside it, brings in React and most of React Native's JavaScript. One such import takes the release JavaScript of `examples/native` from about 410 KB to 1.2 MB. `react-native-mmkv` 4.3 imports `react-native`, and its entry also exports React hooks. To check a release, export it with source maps and search them for React: ```sh npx expo export --platform android --no-bytecode --source-maps --output-dir dist/js grep -lF 'node_modules/react/' dist/js/_expo/static/js/android/*.map ``` No output means no React. For iOS, replace `android` with `ios` in both commands. The search covers both bundlers: the map lists the files Metro bundled, and it embeds the pre-bundle, whose comments name each file Vite put in it. When `grep` names a map, React is in the release, but the map doesn't say what imports it. Search the pre-bundle to narrow that down: ```sh grep -lF 'node_modules/react/' node_modules/.cache/@effect/ui-native/main.android.js ``` If this names the file, the app's code or a package Vite bundles imports React. Otherwise, follow the imports of the packages left to Metro. Use a package path that skips its React code if one exists. If its JavaScript only wraps a TurboModule, the app's Layer can call it through `Native.Device`'s `module(name)`. That ties the Layer to the module's native method names. ## Routing `NativeRouter.layer({ routes, prefixes })` provides the `Router` and its Commands, as `BrowserRouter` does in the browser, on a history kept in memory. The root holds the stack of entries up to the current one and draws it with the kit's `Stack`: ```ts import { Stack } from "@effect/ui-native/kit" import * as Native from "@effect/ui-native/Native" import * as NativeApp from "@effect/ui-native/NativeApp" import * as NativeRouter from "@effect/ui-native/NativeRouter" import * as Layer from "effect/Layer" import * as Schema from "effect/Schema" import * as RouterStack from "effect/ui/RouterStack" import * as UiSchema from "effect/ui/UiSchema" import { AppRoute } from "./routes.ts" import { About, Home } from "./screens.ts" const Message = UiSchema.TaggedEnum({ Navigated: { navigation: RouterStack.Navigation(AppRoute) } }) export const App = Native.component({ name: "App", props: Schema.Struct({ stack: RouterStack.Stack(AppRoute) }), model: RouterStack.Stack(AppRoute), message: Message }).make({ init: ($) => $.props.stack, update: { Navigated: ($, { navigation }) => $.set(RouterStack.follow(AppRoute, $.model, navigation)) }, subscriptions: ({ model }) => [ RouterStack.subscription( AppRoute, model, (navigation) => Message.Navigated({ navigation }) ) ], view: (h, stack) => Stack(h, { entries: stack, screen: (s, { route }) => AppRoute.match(route, { Home: () => Home(s, { key: "home" }), About: () => About(s, { key: "about" }) }) }) }) NativeApp.register( NativeApp.mount(App, RouterStack.props(AppRoute)).pipe( Layer.provide( NativeRouter.layer({ routes: AppRoute, prefixes: ["myapp://"] }) ) ) ) ``` - **Screens.** Covered screens stay mounted, hidden from touches and the screen reader, so Back shows a screen as it was left, scroll position included. The Router saves no snapshots. - **Transitions.** Screens switch at once by default. `transition: StackTransition.slide()` slides them on the native driver, and `StackTransition.slide({ swipeBack: StackSwipe.swipeBack() })` adds a swipe from the left edge on iOS that runs Back, or springs back when it ends short or a block is held. Each move of the swipe runs on the JS thread, so a busy thread makes the screen lag the finger. A stack without a transition bundles neither `Animation` nor `Pan`. - **Links.** `Link(h, { href })` is a `Pressable` with the link role that navigates on press and reports `Router.intent` when a touch starts, for prefetch. An href the routes don't parse opens with `Linking.openURL`. - **Back.** A `BackHandler.onPress` on the top screen gets the press first. Handlers on covered screens get none. Then the router goes back one entry, and at the first it closes the app. While a `Router.blocked` block is held, Back does nothing. - **Deep links.** A URL that starts with one of `prefixes` opens the rest as its path: with `"myapp://"`, `myapp://people/1` opens `/people/1`. The app starts at the URL that launched it, or else at the routes' base root, and a URL that arrives while it runs is pushed. Pass a function for other schemes. - **Accessibility.** The screen reader's focus moves to a screen that comes to the top, which reads it. Nothing is announced; a screen with more to say runs `AccessibilityInfo.announce`. ## Testing Use `NativeVitest.plugin()` to import `@effect/ui-native/kit` in Node tests without mocking React Native imports. The plugin compiles the Flow sources used by `Css` and `Image`. Use Node 22.15 or later and install `flow-remove-types` and `sucrase` as dev dependencies. Then add the plugin to your Vitest configuration: ```ts // vitest.config.ts import { NativeVitest } from "@effect/ui-native/node" import { defineConfig } from "vitest/config" export default defineConfig({ plugins: [NativeVitest.plugin()] }) ``` The loader runs before your test setup files, so those files can import the kit too. It supports the non-React modules the kit uses, not React Native's React components. - `NativeVitest.plugin({ platform: "android" })` selects React Native's Android files; the default is `"ios"`. This affects values such as `Css.color("red")`, not the OS that kit components read from `Native.Device`. - Compiled files are cached in `node_modules/.cache/@effect/ui-native/vitest` under the project root. Write tests with `effect/ui/testing`. The examples test `Draft`, a screen with an `input`. While it holds text, Back shows an alert, and its `"discard"` button clears the text. Start with a Scene. Commands and Subscriptions stay data there, so a screen needs no device: the test sends a Subscription's message and resolves a Command. ```ts import * as Alert from "@effect/ui-native/kit/Alert" import { Effect, Result } from "effect" import { Locator, Scene } from "effect/ui/testing" Effect.gen(function*() { const s = yield* Scene.make(Draft, {}) s.fire(Locator.tag("input"), "input", { value: "Hello" }) .subscription("@effect/ui-native/kit/BackHandler", Message.PressedBack()) .resolve(Alert.Alert, Result.succeed("discard")) .expect(Locator.text("Empty")).toExist() }).pipe(Effect.scoped, Effect.runSync) ``` A Play runs the kit's Effects, so it needs a device. `TestDevice.layer("android")` or `TestDevice.layer("ios")` provides one that acts as that platform, with controls in the kit's terms: `pressBack`, `setColorScheme`, `setAppState`, `showKeyboard`, `resize`, `receiveURL`, `answerAlert`, `answerShare`, `setPermission`, `setAccessibility` and more. A control sends its event at once, so settle before reading the result. ```ts import { TestDevice } from "@effect/ui-native/testing" import { Effect, Layer } from "effect" import { Locator, Play, TestHost } from "effect/ui/testing" Effect.gen(function*() { const device = yield* TestDevice.TestDevice const play = yield* Play.make(Draft, {}) yield* play.fire(Locator.tag("input"), "input", { value: "Hello" }) device.pressBack() yield* TestHost.settle device.answerAlert("Discard") yield* play.expect(Locator.text("Empty")).toExist() }).pipe( Effect.scoped, Effect.provide(Layer.merge(TestHost.layer(), TestDevice.layer("android"))), Effect.runPromise ) ``` The layer also provides `Native.Host` for Commands that measure, scroll or focus a view. Measurements return `undefined` by default; use `device.setMeasure(node => ...)` to return a rect for a node. `device.log()` records view commands and accessibility events. Focus and blur commands do not fire events or show the keyboard: fire those events explicitly and call `device.showKeyboard(height)` when needed. An alert, prompt or iOS share sheet stays open until the test answers it; Android reports a share as soon as the sheet opens. Pick a button by its text or, when two share a text, by `id` with the `buttons` the app showed: `device.answerAlert({ buttons, id: "discard" })`. `device.log()` lists what the app asked the device to do, such as the URLs it opened, the alerts it showed and its status bar style. Apps never import `@effect/ui-native/testing`, so it adds nothing to the bundle. ## Touches The core host recognizes one touch at a time, from the first finger down to the last one lifted. Without the kit it sends `press` to the nearest element with a `press` handler, when the touch ends on that element or within 20 points of it. A scroll view takes the touch when it starts dragging under it, or when the touch starts while the scroll view is still moving. Either way no `press` is sent. Importing `Pressable` or `Pan` from the kit replaces this recognizer with one that also handles press timing and pans. A plain `.on("press")` keeps working with it. Views support W3C pointer events (`pointerDown`, `pointerUp`, `pointerMove`, `pointerCancel`, `pointerEnter`, `pointerLeave` and `click`) for touch, mouse and stylus input. `Pressable` adds `onHoverIn` and `onHoverOut`. Enable W3C pointer events at app launch: `RCTSetDispatchW3CPointerEvents(YES)` on iOS and `ReactFeatureFlags.dispatchPointerEvents = true` on Android. `examples/native/plugins/withPointerEvents.cjs` does this for an Expo app. Native sends a pointer event to the deepest view under the pointer, and the host passes it to the nearest element that handles it. `pointerEnter` and `pointerLeave` fire only on the element entered or left. ## Styles and props `.style()` takes React Native's style names and `.prop()` its other props, such as `testID`, `role`, `accessibilityLabel` or a `text`'s `numberOfLines`. Both are typed, and `.prop()` takes any value for a name without a type. Styles take structured values: `transform` is `[{ rotate: "45deg" }]` rather than `"rotate(45deg)"`. To parse CSS strings, use `Css` from `@effect/ui-native/kit`. Nested colours, such as a `boxShadow`'s `color`, must be processed with `Css.color` or another `Css` helper. `Css.color` returns an `Option` that is `None` for a colour React Native can't process, such as `oklch()`, and `Css.boxShadow`, `Css.filter` and `Css.backgroundImage` return `[]` for an invalid value. These forms target React Native 0.88.1's default `enableNativeCSSParsing: false`. Enabling the flag changes how native reads `filter` drop shadows and `backgroundImage`; keep it off when using those forms or their `Css` helpers. Use native prop names and plain style objects. React Native's `aria-*` and `id` aliases and `StyleSheet` aren't provided. ## Example See `examples/native` and its README, which covers the development client, release builds and measuring the bundle. It is an Expo app with two screens: a Link opens the second, and the `effect-ui://about` deep link opens it directly. The first has 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.