# SwiftBrowser Native

A Swift package that draws the [render ops](https://swiftbrowser-docs.pages.dev/ops-protocol) with
real SwiftUI, for apps whose logic is JavaScript running in JavaScriptCore
inside an iOS app. With [`@swiftbrowser/native`](https://swiftbrowser-docs.pages.dev/native)
on the JavaScript side, a [`@swiftbrowser/react`](https://swiftbrowser-docs.pages.dev/react)
app runs as a native app: React Native for iOS only, with SwiftUI as the
native layer, the ops protocol as the bridge, and every call across it
synchronous. The design and its reasons are in [docs/native.md](https://swiftbrowser-docs.pages.dev/native-design).

```
React/TypeScript app (@swiftbrowser/react)    the app's logic
        │ react-reconciler host → ops
        ▼
@swiftbrowser/native                          run(<App/>), the web globals over the bridge
        │ __sbNative.applyOps(json), synchronous
        ▼
SwiftBrowserNative (this package)             OpTree → SwiftUI views; events back as __sbDispatch(json)
```

## The package

| Target | What it is | Builds on |
|---|---|---|
| `SwiftBrowserProtocol` | the ops, events and typed props of the protocol, read from JSON | Linux, Apple |
| `SwiftBrowserTree` | `OpTree`: the live element tree the ops mutate, one `@Observable` node per element | Linux, Apple |
| `SwiftBrowserNative` | the SwiftUI views per element kind, the JavaScriptCore host and its workers (a `JSContext` on a thread, or a hidden `WKWebView` with WebKit's JIT), `NativeApp` and `NativeRootView` | Apple (iOS 17, macOS 14) |

The package builds in the Swift 6 language mode (its tools version is 6.0,
so it needs Xcode 16 or later): everything runs on the main actor, and the
compiler checks it. `swift test` here runs the core's tests on Linux too: every op snapshot
under `Examples/*/__snapshots__` decodes and applies, the typed props read
what the protocol defines, and the tree's moves, updates and removes do
what the web renderer's do. On a Mac it also runs the workers' tests
(`Tests/SwiftBrowserNativeTests`: a worker echoes messages posted before
its script ran, fires a timer and instantiates a WebAssembly module
asynchronously on its own thread's run loop, and the same in a hidden web
view, whose `fetch` goes through the app's `URLSession`). The SwiftUI target compiles
only where SwiftUI is (`#if canImport(SwiftUI)`), so the package resolves
everywhere.

The repository's root package compiles the same three targets against the
SwiftUI shim as well (`swift build` at the root, natively on Linux), which
type-checks the views without a Mac, and builds `RoundTrip/` for
WebAssembly: the native views drawing a JavaScript app's ops with the host's
own JavaScript as the engine, which the shim turns back into ops for
`scripts/native-roundtrip.mjs` to compare with the app's (docs/native.md,
"The round trip").

## An app

`npx @swiftbrowser/cli native init MyApp` writes one: the Xcode project
(one app target, built for iOS and for macOS), `apple/` (the App file
below, an asset catalog, the bundle, the Mac build's entitlements), `src/`
(the app) and `web/` (the same app as a web page), with `npm run build`
bundling the JavaScript into `apple/app.js`. The project depends on this
package as `@swiftbrowser/native` ships it, under
`node_modules/@swiftbrowser/native/swift` (`--package <dir>` points it
at a checkout's `Native/` instead). The whole native side of an app is
three lines:

```swift
import SwiftBrowserNative
import SwiftUI

@main
struct MyApp: App {
    @State private var app = NativeApp()
    var body: some Scene {
        WindowGroup {
            NativeRootView(app: app).task { app.load() }   // app.js from the bundle
        }
    }
}
```

`NativeApp.load()` evaluates `app.js` (the bundle `swiftbrowser-native build`
writes from the JavaScript project) in a `JSContext`, and the app's `run(<App/>)`
renders its first pass into the tree before `load` returns. `NativeRootView`
draws the tree, presents its sheets and alerts, and sends the device
environment (color scheme, Dynamic Type size, size class) as it changes.

In a Debug build, `await app.watch(url:)` with the URL `swiftbrowser-native dev`
serves (`http://localhost:5173/`) loads the bundle from there and applies
every save as a React Fast Refresh: the app's modules are evaluated again
in the running engine and the mounted components update in place, keeping
their state where their hooks are unchanged (`@swiftbrowser/native`'s
README has the mechanics). The examples switch on it with the
`SB_DEV_SERVER` environment variable in their schemes.

## Examples

[`Examples/Counter`](https://github.com/noya-app/SwiftBrowser/tree/main/Native/Examples/Counter) and [`Examples/Todos`](https://github.com/noya-app/SwiftBrowser/tree/main/Native/Examples/Todos)
are the repository's Counter and Todos examples with their logic ported to
`@swiftbrowser/react` (`src/`), and [`Examples/Fidelity`](https://github.com/noya-app/SwiftBrowser/tree/main/Native/Examples/Fidelity)
is the React Fidelity app (`packages/react/demo/fidelity`), the reference
screens the renderer is measured by: `scripts/native-screenshots.sh`
screenshots each screen on the simulator (`-screen <name>`, as the Swift
app in `Examples/Fidelity` takes it) and the iOS fidelity workflow compares
them with the Swift app's, pixel for pixel (CONTRIBUTING.md, "Comparing with
iOS"). [`Examples/Showcase`](https://github.com/noya-app/SwiftBrowser/tree/main/Native/Examples/Showcase) is an app of whole
examples, each a clone of one of Apple's: a Freeform of boards with sticky
notes, shapes, text and ink on a canvas that pans and zooms
(`src/freeform`), Reminders, lists to check off with smart lists for
today, scheduled and flagged (`src/reminders`), Notes, notes in
folders written in place, pinned, by date and kept a while once deleted
(`src/notes`), Voice Memos, recordings from the microphone with a
live waveform and playback (`src/voicememos`), and Books, a library of
public-domain samples with a reader whose pages turn with a swipe and keep
your place (`src/books`), and the iWork apps: Keynote, themed decks edited on
the slide and played with transitions and Magic Move (`src/keynote`),
Numbers, tables with formulas, formats and charts (`src/numbers`),
and Pages, documents of styled, rich text paragraphs on paper pages
(`src/pages`), and Files, two locations of folders and files browsed as
lists or icons, sorted, searched, tagged and favorited, with Recents and
Recently Deleted, its Browse a sidebar list whose sections fold, and its
photos on a pushed Quick Look screen whose bars a tap hides, edited there
(Adjust, Filters and Crop, drawn by Core Image and kept beside the picture
until Revert) (`src/files`), and Life, Conway's game drawn as a live
bitmap, pixels the app changes in place and shows again at each generation
with no image file in between (`src/life`; on the web page only, as the
native renderer has no live sources yet), and Markdown, a document written
in `@swiftbrowser/code`'s `MarkdownEditor`: the text is Markdown and the
editor shows the document it makes, the syntax hidden until the caret
touches it, with its source beside it in the code editor (`src/markdown`;
natively the code editor's TextKit 2 view shows the document from
presentations the app sends it, not yet verified on a device:
docs/notes/markdown-editor.md), and Tower, a stacking game in 3D
whose scene the app builds in JavaScript (@swiftbrowser/reality), drawn by
three.js on the web page and by RealityKit in the app
(`Packages/SwiftBrowserReality`; built with Xcode, not yet run on a
device) (`src/tower`), their
models tested in `test/`. The Showcase is also a
web page (`web/`, `npm run dev:web`), the same React app drawn by the web
renderer, which `showcase.yml` deploys to Cloudflare Pages; `showcase-ios.yml`
builds it for iOS ad hoc and puts its install page on the same project's
`ios` alias. Each has an Xcode project
depending on this package. Build the bundle, then run the project:

```sh
npm ci && npm run build:packages          # once, at the repository root
cd Native/Examples/Todos && npm run build # writes apple/app.js
open Todos.xcodeproj                      # run on a simulator, or on this Mac
```

`npm run dev` instead serves the bundle with rebuild on save; enable the
`SB_DEV_SERVER` variable in the scheme's Run action and the app follows
every save. `node Native/Examples/generate-projects.mjs` rewrites the
Xcode projects with the CLI's `native init` template, pointed at this
package instead of the published copy.

## In a browser

`npx swiftbrowser-native site src/index.tsx --out dist` writes the same
app as a static site: this package compiled for WebAssembly against
SwiftBrowser's SwiftUI shim (`RoundTrip/`, the module `@swiftbrowser/native`
ships) draws the bundle's ops in the web renderer's page, with the page's
JavaScript as the engine. [docs/native.md](https://swiftbrowser-docs.pages.dev/native-design), "The round
trip", has the mechanics; the `Native` workflow opens the Fidelity example
this way in Chromium.

## How the renderer works

- **The tree.** `OpTree.apply` runs each pass (the ops up to a `commit`)
  inside `animate`, which `NativeApp` sets to `withAnimation`, so an animated
  commit animates every frame and style change of the pass and the children
  it inserts or removes transition. Each `ElementNode` is `@Observable`, so an
  `update` to one element re-evaluates one view.
- **The views.** `ElementView` switches on the kind; a `ForEach` keyed by the
  protocol's stable ids keeps view identity across passes. `styled` applies
  its `Style` as modifiers, inside out, which reproduces the app's modifier
  chain. Navigation derives the stack's path from the `navscreen` children;
  a native pop sends `tap` with the popped screen's id and the app removes
  it in the same call. Sheets and alerts are the root's `sheet` and `alert`
  children, presented by `PresentationHost`.
- **Controls are controlled.** A `TextField`'s binding setter sends `text`;
  because the dispatch is synchronous the getter already reads the app's
  new value when SwiftUI asks, so the field never shows a stale frame. Its
  `onSubmit` sends `submit` and reads the bound `focused` back: a field the
  app keeps focused keeps the keyboard through Return.
- **The bridge.** Two functions: `__sbNative.applyOps(json)` from JavaScript
  and `__sbDispatch(json)` from Swift, both synchronous. `HostBridge`
  installs the primitives the JavaScript runtime builds the web globals from:
  timers on the main run loop, a console, `fetch` over `URLSession`,
  `localStorage` over `UserDefaults`, random bytes, the locale.
- **Registered views.** `ViewRegistry.register("Name") { context in … }`
  gives the JavaScript app's `<RegisteredView name="Name" props={…}>` (from
  @swiftbrowser/react) a SwiftUI view of yours, with its props, its children
  and `context.send` for events back; a page registers its own element under
  the same name (@swiftbrowser/web's `ViewRegistry`).

## What is drawn

Text (plain and rich runs), images (SF Symbols by name, catalog images,
remote URLs, cached and decoded no larger than their box: ImageLoader.swift), stacks, spacers, dividers, `styled` (padding, font, foreground
and background styles, frames, corner radius, opacity, offset, rotation,
scale, shadow, blur and the other effects, transitions, `.animation`,
badges, list row insets and backgrounds, safe area), `decorated` (overlay
and background views), `geometry`, scroll views, lazy and regular grids,
buttons with styles and roles, toggles, text fields and editors, pickers,
sliders, steppers, tap gestures, menus and context menus, lists with
sections, edit mode, reordering, deletion and swipe actions, navigation
stacks with titles, toolbars and search, tab views, sheets, full-screen
covers and alerts, colors and shapes (built-in and custom paths, with
their size reported back), gauges and progress views, `ViewThatFits`, date
pickers, drag and long-press gestures, lazy rows, split navigation (a
`NavigationSplitView` in a regular width, its sidebar toggled by the bar
button), the inspector, charts (the marks, axes and legend as the protocol
resolves them, drawn with paths and texts), scroll targets (`snap`,
`scrollTargetLayout`, `.scrollPosition(id:)` and a reader's `scrollTo`) and
`containerRelativeFrame`, and video (an `AVPlayer` over the element's URL,
drawn by AVKit's `VideoPlayer` or a bare player layer, driven by the props
and reporting `video` events as the page does; an element at no size plays
audio with no view). Kinds not drawn yet (canvas, custom layouts, maps and
drag and drop) render their children with the kind named over them in
Debug builds.
