SwiftBrowser Native: JavaScript apps drawn by SwiftUI#
A proposal for a third renderer. SwiftBrowser today runs Swift in the
browser: the SwiftUI shim turns a view tree into render ops and the
TypeScript renderer in Web/ draws them. This project runs the arrows the
other way: the app's logic is JavaScript (React, through
@swiftbrowser/react) running in JavaScriptCore inside an iOS app, and a
Swift renderer turns the same ops into real SwiftUI views. Conceptually
React Native for iOS only, with SwiftUI as the native layer and the ops
protocol as the bridge, and with every call across the bridge synchronous.
today this proposal
Swift app (SwiftUI) React/TypeScript app (@swiftbrowser/react)
│ shim: view tree → ops │ react-reconciler host: fiber tree → ops
▼ ▼
docs/ops-protocol.md ───────────────── the same ops, as JSON
│ │ JSContext: one synchronous call per pass
▼ ▼
Web/ renderer (DOM + layout engine) Native/ renderer (ops → SwiftUI views)
Why this is mostly already here#
Three facts about the repository make the project smaller than it sounds.
The JavaScript side exists.
@swiftbrowser/reactis areact-reconcilerhost whose only output is ops.createSwiftUIRoot(sink)(packages/react/src/host/root.ts) renders a React tree and hands the ops of each pass tosink;root.dispatch(event)delivers a renderer event to the element's handler and flushes the resulting pass before it returns (flushSyncFromReconciler). Its tests already run it headless with no DOM (packages/react/test/*.test.tsx). The DOM only enters inmount.ts,island.tsxandcomponents/host.tsx, which the native bundle leaves out.The protocol was designed to be rendered by something else. Element ids are stable across passes,
insertdoubles as move, props are replaced whole onupdate, andcommitcloses a pass and carries its animation. Those are exactly the properties a SwiftUI renderer wants: a keyedForEachover children keeps view identity, and a pass can be applied inside onewithAnimation.docs/ops-protocol.mdandWeb/src/protocol.tsare the spec; the layout rules in them do not apply, because SwiftUI lays out.Conformance material exists. Every example has an op snapshot (
Examples/*/__snapshots__/*.jsonl, thirteen files) the native decoder must accept. The Fidelity app exists twice, in Swift (Examples/Fidelity) and in React (packages/react/demo/fidelity), and the React one is verified to emit the same ops as the Swift one (packages/react/test/fidelity.test.tsx).scripts/ios-screenshots.shalready screenshots the Swift one on the simulator. So the native renderer can be measured against the real thing screen by screen: render the React Fidelity app natively, screenshot, diff against SwiftUI running the same screen.
What is new is one Swift package and one small npm package, described next.
Status#
The first two milestones below are built: Native/
(the Swift package: protocol, tree, the SwiftUI views for the kinds the
Counter and Todos examples use and most of the common ones, the
JavaScriptCore host, NativeApp and NativeRootView),
packages/native (run, the runtime, the
bundler and the swiftbrowser-native CLI, and the Swift package itself,
copied in at publish time) and Native/Examples/Counter and
Native/Examples/Todos (the two examples ported to React, each with an
Xcode project). The protocol and tree targets build and test on Linux
against every example's op snapshot; the bundles of both examples run
headless in Node with only the bridge defined, replaying the Todos
snapshot's event script. The SwiftUI and JavaScriptCore code builds only on
a Mac (CI's Native workflow).
The Fidelity sweep and Fast Refresh followed. Native/Examples/Fidelity is
the React Fidelity app (packages/react/demo/fidelity) as a native app that
opens one screen from -screen <name>, and scripts/native-screenshots.sh
screenshots it on the simulator the way scripts/ios-screenshots.sh
screenshots the Swift app; the iOS fidelity workflow runs both and compares
them (fidelity-native-comparison). The renderer gained the kinds those
screens use (gauges and progress views, ViewThatFits, date pickers, drag
and long-press gestures, lazy rows, size reports for anchor preferences and
custom shapes). Fast Refresh runs as designed below: swiftbrowser-native dev
serves the bundle in two halves and NativeApp.watch(url:) evaluates the
app half again on every save, with the refresh runtime keeping component
state. Its test runs the loop in Node (packages/native/test/fastRefresh.test.ts).
Two rounds of the comparison (label icons and layout, weight-only fonts,
grid column alignment, Form, the link row's chevron, a real Label,
ProgressView and EditButton; the button op gained editMode for the
last) put every screen the two Fidelity apps share at 0.0% to 0.2% of
SwiftUI's pixels in both appearances, except form (3.6% light, 7.2% dark:
a bio field the React demo has and the Swift form does not). What is left
is below the renderer: a grid header a pixel off, and an email the Swift
shim's markdown does not autolink where iOS's does.
Pieces#
Native/: the Swift package#
A SwiftPM package for Apple platforms (iOS 17+, for @Observable). It cannot
live in the root Package.swift: that package has a target named SwiftUI
and is only ever built for Wasm and Linux (docs/architecture.md). Native/
mirrors Web/: the renderer for one host, with its own manifest and tests.
Native/
Package.swift library SwiftBrowserNative, iOS 17 / macOS 14
Sources/SwiftBrowserNative/
Protocol/ Codable mirror of Web/src/protocol.ts: Op, Style, Font, Frame,
Color, ShapeStyle, the per-kind props, RendererEvent
Tree/OpTree.swift the live element tree; applyOps, commit, event sink
Tree/ElementNode.swift @Observable node: id, kind, props, children
Views/ElementView.swift kind → SwiftUI view; recursion over children
Views/Kinds/*.swift one file per family: stacks, text, controls, lists,
navigation, presentation, shapes, images, charts…
Views/StyleModifier.swift `styled` → modifiers
Host/JSHost.swift the engine boundary (evaluate, call, install function)
Host/JavaScriptCoreHost.swift JSContext implementation
Host/Globals/*.swift timers, console, fetch, WebSocket, crypto, performance
Runtime/App.swift wires a bundle, a host and a tree into a SwiftUI root view
Tests/ snapshot decoding, tree application, ImageRenderer snapshots
The tree#
The web renderer keeps elements, nodes and parents maps by id
(Web/src/renderer.ts). The native tree is the same idea with SwiftUI's
observation doing the invalidation:
@Observable final class ElementNode: Identifiable {
let id: Int
let kind: String
var props: Props // decoded per kind; replaced whole on `update`
var children: [ElementNode] = []
}
@MainActor final class OpTree {
let root = ElementNode(id: 0, kind: "root")
private var nodes: [Int: ElementNode] = [0: root]
var send: (RendererEvent) -> Void = { _ in }
func apply(_ ops: [Op]) {
var pass: [Op] = []
for op in ops {
if case .commit(let animation) = op {
withAnimation(animation.map(Animation.init)) { applyPass(pass) }
pass.removeAll()
} else { pass.append(op) }
}
}
}
create makes a detached node, insert moves it under its parent at an
index (removing it from a previous parent first), update replaces props,
remove drops the subtree. Because each ElementView reads only its own
node, an update to one element re-evaluates one view body, which is the
granularity the protocol already works at. Applying the whole pass inside
withAnimation gives the protocol's animated commits for free: SwiftUI
animates every frame and style change of the pass, and inserted or removed
children transition with the transition field of their style, which is
what Web/src/animation.ts reimplements by hand.
Views#
struct ElementView: View {
let node: ElementNode
var body: some View {
switch node.kind {
case "text": Text(verbatim: node.props.text)
case "vstack": VStack(alignment: node.props.alignment, spacing: node.props.spacing) { children }
case "button": Button(role: node.props.role) { send(.tap(node.id)) } label: { children }
case "styled": children.modifier(StyleModifier(node.props.style))
case "image": node.props.systemName.map { Image(systemName: $0) } ?? RemoteImage(node.props)
case "list": List { ForEach(node.children) { ListContent($0) } }
case "navstack": NavigationStackView(node)
case "sheet": EmptyView() // presented by the root, see below
case "registered": ViewRegistry.view(node.props) // registered views, see below
default: Unsupported(kind: node.kind) // visible, like the web's placeholder
}
}
var children: some View { ForEach(node.children) { ElementView(node: $0) } }
// A `textfield` or `texteditor` with `deleteBackward` hears Backspace at the start of its
// text through the UIKit text input behind SwiftUI's (Views/Kinds/DeleteBackward.swift):
// a background finds it in the hierarchy and a swizzled `deleteBackward()` runs the handler.
}
Some kinds are not one-to-one and need a little state on the Swift side:
navstack/navscreen. The protocol expresses push and pop purely asnavscreenchildren appearing and disappearing. Natively the stack isNavigationStack(path: $path)withnavigationDestination(for: Int.self), wherepathis derived from the children withdepth > 0. A native pop (back button, edge swipe) sendstapwith thenavscreen's id, as the protocol says, and JavaScript removes the child; the next pass finds the path already matching and does nothing. SwiftUI sets the path as UIKit's pop begins (a back button's tap, a swipe's start), so the tap waits until the transition has finished, and a cancelled swipe sends none (Views/Kinds/PopTap.swift, from UIKit's transition coordinator): meanwhile the stack's path leaves the screen out, as SwiftUI's has, while the tree still has it, and the departing screen is drawn as it is, its large title riding the pop. A screen the app removes itself (a programmatic pop) is kept for a few seconds (OpTree.poppedScreen) and the destination still draws it as it was, so the pop slides it away rather than dropping its content in one frame.toolbarandsearchfieldchildren become.toolbar { }and.searchable(text:); eachtoolbarelement is aToolbarItemGroupof its children, the items of one placement run as the page lays them out (in oneToolbarItem, iOS 26 shows only the first). The screen'snavigationBarHidden,bottomBarHiddenandstatusBarHidden(docs/ops-protocol.md, "Bar visibility") are.toolbar(.hidden, for: .navigationBar),.toolbar(.hidden, for: .bottomBar)and.statusBarHidden(true), which SwiftUI animates in an animated commit.- Pinches. On iOS 18 a
gestureelement'smagnifyandrotateare read from the fingers (SpatialEventGesture, Views/Kinds/PinchTracker.swift), as the web renderer reads them from two pointers: the scale from the first two fingers' distance over their distance when the second landed, the rotation from the turn of the line between them, the location from their midpoint, beginning as soon as the thresholds pass (on the first move with none), as Photos does. SwiftUI'sMagnifyGesturebegins only once the system's pinch recognizer has made up its mind, well into the spread; it andRotateGestureremain before iOS 18 and on the Mac, where a trackpad pinch is no finger. touches. SwiftUI's own gestures hear one finger at a time across views, so the multi-touch element (docs/ops-protocol.md, "Multi-touch") usesSpatialEventGestureon iOS 18 and macOS 15, which reports every finger on the element with a phase; a tracker numbers the fingers and tells each report's phase (Views/Kinds/Touches.swift). Before iOS 18, and against the shim, aDragGesturewith no minimum distance reports the one finger it can.sheet/alert. Root-level children after the app's tree, as the protocol defines them; the root view presents them with.sheet(item:)keyed by node id, and dismissal sendstapwith the sheet's id.menu/contextmenu.Menu { } label: { }and.contextMenu { }over the children after the first. A lazy menu (docs/ops-protocol.md, "Lazy menus") has its label alone until it opens; SwiftUI on iOS builds a menu's items as it presents it, so the items' appearance is the menu's (Views/Kinds/Controls.swift,MenuPresence): a disabled row stands in for the items until they arrive, and its appearance sendsmenuwithopen: true, which the app answers inside the call; a second after the last item went,open: false, after the chosen item'stap. On macOS a deferred menu asks for its items as it comes on screen and keeps them.tabview/tab.TabView(selection:)with onetabItemper child; the selection binding's setter sendsselect.listwith selectable rows.List(selection:)with each selectablelistrowtagged by its id: the whole cell takes the tap, with the system's highlight, and the binding's setter sends the row'stap(in edit mode a row takes its own tap). Anavlinkthat is a list's row (onlystyledand the row wrappers between them) has the chevron (not on a Mac, whose link rows have none). On a Mac the default list (inset grouped, which the Mac has no style for) is the inset one; a list'sminRowHeight(.environment(\.defaultMinListRowHeight, _)) sets the environment on it, as the web renderer honors it; one inside a row's content (a stack, a scroll view) is a plain button. On a Mac, UIKit's system colors (systemBackground,secondarySystemGroupedBackground, the fills, the grays…) are their light and dark values, as the web renderer's Mac idiom draws them, so they follow the appearance.scrollviewwith a position..scrollPosition(id:)over the marked targets of the stack markedscrollTarget(only that stack gets.scrollTargetLayout(): a disabled one around a scroll view, as in a list row, turns off the layout inside it). On iOS 18 the reported position is the visible target at the anchor once the scroll phase is idle, after a drag or ascrollToalike; ascrollToon the view's own axes moves the view through its position, leaving the list around it in place. Astyledelement draws its one child as itself, not through aForEach, whose element would otherwise be the identity SwiftUI names a target by.Tests/SwiftBrowserNativeTests/ScrollTests.swiftchecks the snapping and the reports in the iOS Simulator (native.yml's iOS job).scrollviewwithreportsGeometryorscrollOffset. iOS 18'sonScrollGeometryChangesendsscrollgeometry(the offset, the content's and the view's sizes, the insets) after the pass that changed them; an offset command positions the view through aScrollPositionof its own (scrollTo(x:y:), once per serial, from the view's appearance on), and such a view does not report ids, SwiftUI taking one position per scroll view. Avstackorhstackwithpinnedis aLazyVStack/LazyHStack(pinnedViews:); the grids passpinnedViewsthrough.- A
commitwithcompletion. The pass is applied insidewithAnimation(_:completionCriteria:_:completion:)and the completion sendsanimationcompletewith the serial, a turn later (OpTree.animateWithCompletion); a commit with no animation answers right after the pass. - Controls (
textfield,toggle,picker,slider,stepper,datepicker,texteditor). Each is a native control with aBindingwhose getter reads the node's prop and whose setter sends the event. This is the place where synchronous calls matter most; see below. A field'sonSubmitdispatchessubmitand readsfocusedback: left true, the field holds the focus against the resign Return is followed by (docs/ops-protocol.md, "Focus across a submit"). A field's text input hints (keyboard,contentType,autocapitalization,autocorrectionDisabled) are SwiftUI's own modifiers again (TextInputHints.swift): an email field gets the email keyboard, the QuickType bar's addresses, no capitalization and no correction; macOS takes the content type and the correction. geometry. AGeometryReaderthat sendsgeometryevents, deferred to after the layout pass, so the tree is never mutated during SwiftUI's own update. An update's size reports go together, as onebatchonce it is over (NativeApp.report), as the web renderer sends a pass's; where the update drew the tree's last commit, the batch ends withlaidout(docs/ops-protocol.md), orlaidoutgoes alone where it reported nothing.layout(a customLayoutwritten in JavaScript). A SwiftUILayoutconformance (AppLayout, Views/Kinds/Drawing.swift) asks the app's rule from its ownsizeThatFits,placeSubviewsandexplicitAlignment, synchronously through the engine (__sbLayout, which @swiftbrowser/native'sruninstalls): each subview is measured by SwiftUI as the rule asks (a nativemeasureSubviewbound for the call), and the pass's container by a last, hidden subview in acontainerRelativeFrame. The app's React code runs while SwiftUI is mid-layout, so a pass it sends meanwhile (its jobs after the call) is held by the bridge (applyOps) and applied once the layout is over, where the tree may change. The element is laid out in the pass, with nothing reported for it (docs/ops-protocol.md, "layout(customLayout)").draggable/dropdestination. SwiftUI's.draggableand.dropDestination(for: String.self). What is dragged stays in the app, as on a page: the draggable's payload is a marker and its id as text (DragPayload), made as the drag begins (whendragstartgoes out), and the destination's drop names it assourceand sends itsdragend. Text dragged in from another app is offered asitemswhenacceptstakes text. SwiftUI says nothing when a drag ends on no destination, so that drag sends nodragend; the app's next lift replaces what it kept.chart,canvas,image. Swift Charts,Canvasreplaying the drawing commands (each with its clips, transform, opacity, blend mode and filters; an image command draws a symbol or a catalog image, not a URL's, which has no bytes to draw synchronously),Image(systemName:)with real SF Symbols (the web maps about 570 names to another icon set; here every name is right) and, for URLs, the package's own image loader (Views/Kinds/ImageLoader.swift): the bytes in a URL cache of its own (32 MB in memory, 256 MB on disk, kept across launches for as long as the server's cache headers allow) and the decodes in memory (up to an eighth of the device's memory, 256 MB at most), each decoded through ImageIO no larger than the box it is drawn in, so a row scrolled back on screen draws its images at once and a photo drawn as an avatar costs kilobytes;ImageCache.configure(_:)sizes the caches and sets the images' session (a header the pictures need) at launch,ImageCache.clear()empties them at a sign-out. An SVG, which the system's image decoding does not read, is parsed and drawn as vectors by SwiftDraw (zlib license), the package's one dependency, on Apple platforms only. A bitmap recipe (<Image bitmap>, docs/ops-protocol.md, "Bitmaps and Core Image") is drawn by Core Image itself (Views/Kinds/Bitmaps.swift): the tree keeps eachimagedataop's source for the run (OpTree.bitmapSources), each step becomes Core Image's own filter or transform (CIColorControls,CIPhotoEffectNoir,transformed(by:)…), and the latest 48 drawings are kept, so a thumbnail drawn again costs nothing.host(React DOM inside the tree) has no meaning natively and renders as the unsupported placeholder.
styled is a wrapper with exactly one child carrying a Style of 64
optional fields (Web/src/protocol.ts, interface Style). Each maps to a
modifier: padding to .padding, font to .font (text styles and
weights are already SwiftUI's names), foreground to .foregroundStyle,
background to .background, frame to .frame, cornerRadius to
.clipShape(RoundedRectangle), opacity, disabled, lineLimit,
offset, rotation, scale, shadow, blur, zIndex, transition,
matchedGeometry and the rest: symbolEffect is SF Symbols' own effect
(rotate, wiggle, breathe and a bounce that runs on from iOS 18),
pointerStyle the Mac's pointer (iOS has none of that kind), and hover
and scrollVisibility send their events from the box (.onHover, and
iOS 18's .onScrollVisibilityChange). The order the shim nests styled elements
is the order the app wrote its modifiers, so applying them inside out
reproduces the app's modifier chain.
The protocol in Swift#
Web/src/protocol.ts is the TypeScript mirror of the spec; the native
package needs a Swift one. Hand-written Codable types are fine to start,
decoding props per kind and keeping unknown fields. Two tests pin it down:
every line of every Examples/*/__snapshots__/*.jsonl decodes (skipping the
{"op":"event",…} echoes headless mode prints), and the React Fidelity
app's ops, which equal the Swift core's, apply to an OpTree and render
with ImageRenderer into snapshot images. Generating the Swift types from
protocol.ts is possible later if drift becomes a problem.
Native/Sources/.../Host: the JavaScript engine#
JavaScriptCore first: it ships in the OS, costs no binary size, and
JSContext is a synchronous API from Swift with no C++ in between. Hermes
has no Swift or Objective-C API (its JSI is C++, so it needs an
Objective-C++ shim and the engine as an XCFramework); it brings
ahead-of-time bytecode for faster startup, which is worth having once an
app is big enough to notice. Both run without a JIT in a third-party iOS
process, so the choice is startup and tooling, not steady-state speed.
The JSHost protocol stays narrow (evaluate a script, install a native
function under a name, call a global function with a JSON string) so Hermes
or QuickJS can slot in behind it.
Two native functions are the whole bridge (the rest of __sbNative, which
the runtime builds the web globals from, is tabled in HostBridge.swift; a
synchronous one of note is measureText(text, fontJSON, width), which
answers @swiftbrowser/react's measureText from NSAttributedString's
bounding rect within the call, TextMeasureBridge.swift):
// JavaScript → Swift, synchronous: the ops of one pass.
context.setObject({ (json: String) in tree.apply(decode(json)) } as @convention(block) (String) -> Void,
forKeyedSubscript: "__sbApplyOps")
// Swift → JavaScript, synchronous: one renderer event; returns after the
// handler ran and its pass reached __sbApplyOps.
tree.send = { event in context.objectForKeyedSubscript("__sbDispatch").call(withArguments: [encode(event)]) }
JSON strings cross the boundary, as they do between Wasm and the page.
JSValue bridging of arrays and dictionaries is an alternative to measure
later; the ops of a UI pass are small, and the web renderer takes the same
route.
Bare JavaScriptCore has Promises and queueMicrotask but no event loop
features. The host installs what React and an ordinary app expect, which is
the same list React Native provides for Hermes: setTimeout, setInterval,
clearTimeout, requestAnimationFrame (on the main RunLoop and a
CADisplayLink), console, performance.now, fetch with Headers,
Request, Response and AbortController over URLSession (with Blob,
File and FormData bodies, a form sent as multipart), WebSocket over
URLSessionWebSocketTask, TextEncoder/TextDecoder, URL (with
createObjectURL as a data: URL), crypto.getRandomValues, randomUUID
and crypto.subtle's digests and HMAC over CryptoKit, matchMedia for the
color scheme the host sends, navigator.vibrate as a haptic,
navigator.onLine with the online and offline events over
NWPathMonitor (Host/ReachabilityBridge.swift), navigator.wakeLock
over isIdleTimerDisabled (a power assertion on macOS),
navigator.geolocation over CLLocationManager (Host/GeolocationBridge.swift;
the app's Info.plist naming NSLocationWhenInUseUsageDescription), speechSynthesis
over AVSpeechSynthesizer and SpeechRecognition over SFSpeechRecognizer
(Host/SpeechBridge.swift, Host/SpeechRecognitionBridge.swift; the app's
Info.plist naming NSSpeechRecognitionUsageDescription), structuredClone, localStorage over UserDefaults and secureStorage
over the Keychain, the web renderer's share, pickFiles, exportFiles,
clipboard, pickColor, webAuth and appleSignIn (Sign in with Apple's sheet,
Host/AppleSignInBridge.swift) host requests over the share sheet,
the photo and document pickers (the latter saving an export to Files), the
pasteboard, the color picker, fileManager over the sandbox and the app's
iCloud Drive container (Host/FilesBridge.swift, Host/ICloudBridge.swift:
NSFileCoordinator around its files, placeholders downloaded before a read,
NSMetadataQuery for what another device changed, reported to
__sbFilesChanged; the entitlement from swiftbrowser native init --icloud) and
ASWebAuthenticationSession, the microphone recorder useAudioRecorder
asks over AVAudioRecorder (audioRecord: AAC into Documents/Recordings,
metered, the app's Info.plist naming NSMicrophoneUsageDescription; its
trim cuts a recording into a new file through an AVMutableComposition
and AVAssetExportSession; Host/AudioRecorderBridge.swift), the video
assets AVURLAsset, AVAssetImageGenerator, AVMutableComposition and
AVAssetExportSession read and write (avAsset: loads, stills and exports
on AVFoundation, into Caches/AVAssets unless the app names a file;
Host/AVAssetBridge.swift), the camera useVideoRecorder opens
(videoRecord: an AVCaptureSession and a movie file output into
Documents/Recordings, its live picture a preview layer under the stream
id a video element's stream names, the Info.plist naming
NSCameraUsageDescription and NSMicrophoneUsageDescription;
Host/VideoRecorderBridge.swift), the
AVAudioEngine an app builds in JavaScript (audioEngine: each command
performed as it arrives, on AVAudioEngine itself, players, samplers and
effects, and node kinds packages add, such as the program synthesizer of
the opt-in Native/Packages/SwiftBrowserDSP; Host/AudioEngineBridge.swift,
Host/AudioEngineNodes.swift), Apple Intelligence's on-device
model for LanguageModelSession (languageModel: FoundationModels on iOS
26, a stream read with next as it grows; Host/LanguageModelBridge.swift;
where Apple Intelligence cannot answer, the app's LanguageModels.fallback,
such as LocalLanguageModel.install(.llama3_2_1B) from the opt-in
Native/Packages/SwiftBrowserLocalModel, llama.cpp with an open model)
(Host/HostRequestBridge.swift; run fills
the environment @swiftbrowser/react asks with them), the window's
UndoManager for useUndoManager (undoState, Host/UndoBridge.swift:
the JavaScript stack is the truth and the window's manager mirrors it with
a proxy action per side, so the shake, the three-finger swipe, ⌘Z and the
Edit menu send __sbUndoCommand to the app), Image over the image loader's
probeImage (the size of a picture without drawing it, as React's
AsyncImage asks, which shows its placeholder meanwhile; the bytes stay
for the image element that follows), and navigator.mediaSession with
MediaMetadata over MediaPlayer's MPNowPlayingInfoCenter and
MPRemoteCommandCenter (the lock screen and the media keys; the update is
the web renderer's mediaSession request, so an audio app writes the same
code for the page and the native app). The JavaScript halves of these (the
classes) live in the npm package below; the Swift halves are the primitives
they call. react-reconciler's host config in packages/react/src/host/reconciler.ts
needs only setTimeout and queueMicrotask.
Microtasks drain when the JavaScript stack unwinds, that is when each
call returns to Swift, so a setState inside a Promise callback flushes
before the native side continues. Exceptions go to
context.exceptionHandler, which logs and, in Debug, shows the error over
the app like React Native's red box.
Workers#
A page keeps heavy work off its UI thread in a Web Worker; the host gives
a JavaScriptCore app the same. createWorker(name) from
@swiftbrowser/native runs the bundle swiftbrowser-native build --worker <name>=<entry> wrote beside app.js (<name>.worker.js, the runtime first
as in app.js) in a second JSContext in a JSVirtualMachine of its own on
a thread of its own (WorkerHost.swift), so it runs beside the app's
context rather than in its turns. Virtual machines are made and dropped one
at a time, under a lock of the host's (JavaScriptCoreHost.swift):
JavaScriptCore registers each in a process-wide list, and one made while
another was being made or dropped on another thread has crashed in that
list's lock (the test suites running in parallel on the simulator). The thread runs a run loop: the worker's
timers and fetch answers come through it, and so does the engine's own
deferred work. Each turn of the loop runs in an autorelease pool of its own,
so the values the engine hands Swift in a turn are released at the turn's
end and a terminated worker's context goes while its thread still runs. An
async WebAssembly.instantiate settles its promise from the run loop (a
command-line probe that only slept never saw it resolve), which is what an
emscripten module's glue awaits, so a module like satoru's (HTML to PNG,
7.6 MB, inlined in the worker bundle as base64) loads and draws there as it
does in a browser's worker.
The worker's __sbNative has the primitives the runtime builds its globals
from (log, now, timers, fetch, randomBytes, locale) minus the tree,
plus workerPostMessage; the runtime installs self, postMessage,
onmessage, addEventListener and __sbWorkerReceive over them. The
app's side has workerStart(id, name, engine), workerPost(id, text) and
workerTerminate(id), and receives __sbWorkerMessage(id, text) and
__sbWorkerError(id, message) on the main thread. Messages are text both
ways, as values cannot cross virtual machines: JSON, with typed arrays and
ArrayBuffers carried as base64 and Errors as their name and message
(encodeMessage, decodeMessage in worker.ts); what JSON drops does not
cross. A message posted before the worker's script ran waits for it, as in
a browser. callNative in a worker is two such messages: the worker's scope
posts the call ({ $sbCall }), the app's Worker makes it in the app's
context and posts what the function returned or why it did not
({ $sbAnswer }), and neither reaches the app's or the worker's own
listeners. So a worker reaches the Swift the app registered with nothing
more from either engine's host; the scope has the call as
__sbCallNative(name, params) too, for a worker's module that a page also
bundles and that imports none of the package. A worker has no
callNativeSync, and lists no functions. Drawn in a page (the round trip below), createWorker returns
the page's own Worker over the same bundle, published with the site at
bundle/<App>/<name>.worker.js, so an app's code is the same everywhere.
A third-party iOS app has no JIT, so the worker's WebAssembly runs in the
engine's interpreter; SIMD in it needs iOS 26.2 (.github/workflows/jsc-wasm.yml
probes a bare JSContext on the simulator's runtimes). No entitlement
changes that: only Apple's processes may map executable memory. WebKit's web
content process is one of them, so createWorker(name, { engine: 'webview' })
runs the same bundle in a hidden WKWebView instead (WebViewWorkerHost.swift),
where JavaScript and WebAssembly are compiled. The page's __sbNative is the
worker bridge written in JavaScript over the page's timers and crypto, run
before anything else; workerPostMessage, log and fetch reach the host
through a script message handler, and messages and fetch answers go in with
callAsyncJavaScript. The page's fetch family is cleared so the runtime
installs its own over the bridge: requests go through the app's
URLSession and its cookies, as a JSContext worker's do, and no CORS
applies. Its other globals (timers, TextDecoder, URL, crypto) are the
page's. On iOS the web view sits behind the key window's content, 1×1 and
clear, since WebKit suspends the process of a web view outside a window; if
the process ends (memory pressure), the worker reports an error and starts
over, losing what was in flight. The cost is a process and a web view's
memory, so the engine is for heavy work, such as satoru's WebAssembly.
URLs the app is opened with#
A universal link (an applinks: associated domain, with the site's
apple-app-site-association naming the paths) or a custom scheme opens the
app through SwiftUI's onOpenURL; the App file hands it to
NativeApp.open(url:), which calls the bundle's __sbOpenURL, and
onOpenURL from @swiftbrowser/native delivers it to the app's listeners.
A URL that launched the app arrives before the bundle loads and before any
listener is there: the host keeps it until the bundle is loaded, and the
runtime keeps it for the first listener. Amindia's sign-in link in the iOS
app is one: the email's link opens the app, which spends the token itself,
so the session is the app's rather than Safari's.
Notifications#
The browser's Notification and navigator.setAppBadge work in the native
app over UserNotifications (Host/NotificationBridge.swift), and
registerForPush / onNotification from @swiftbrowser/native are remote
notifications: the App file's @UIApplicationDelegateAdaptor(NativeAppDelegate.self)
hands the device token, a failure and the pushes delivered to the app to
NativeApp, whose NotificationRouter (the notification center's delegate,
shared by every app) reports what the viewer opened and what arrived while
the app is open as __sbNotification(json); what comes before the app
listens (a tap that launched it) waits. Against the shim (the round trip) the
bridge drives the shim's UserNotifications, which subscribes to Web Push
through the site's service worker (docs/ops-protocol.md, "Push
notifications"), so the same app code registers in the page; in a plain
browser @swiftbrowser/native subscribes with the browser's own APIs. The
README of packages/native has the API.
The first frame#
The bundle's first render happens inside NativeApp.load, as the bundle's
run(<App/>) evaluates, so whatever it renders with is what the first
frame shows. It used to render with @swiftbrowser/react's defaults (light,
a compact size class, no idea of the window) and hear the real environment
in an event right after: an iPad drew the phone layout for a moment and
then reflowed. Now the host tells the bundle first:
NativeRootViewmeasures the window (aGeometryReaderbehind the tree, safe area included) and sends its size with the color scheme, Dynamic Type size, size class and platform (NativeApp.setEnvironment,windowSize:).NativeAppkeeps them from the start, before any bundle loaded.- A load waits for it. While a root view shows the app and has not
measured yet,
load(script:)andload(scripts:)(the dev loop's) keep the scripts and run them once it has, at most a second later: one layout pass of delay rather than a wrong first frame. An app with no root view (a test) loads at once. - The global
__sbEnvironment. Before evaluating the scripts the host sets it to theenvironmentevent's fields ({ colorScheme, dynamicTypeSize, horizontalSizeClass, platform, windowSize: { width, height } }, each present when known), andruncreates its root with them (createSwiftUIRoot'senvironmentoption), so the first pass has the real environment. The event is still sent after the load, for a bundle that predates the global; a root renders nothing for values it already has. - The launch, measured. On a device,
NativeApplogs the launch's timeline to theswiftbrowsersubsystem,launchcategory (Console.app with the device attached, or Xcode's console; the shim's host, whose logger writes to stderr, logs none of it): each script's size and how long it took to evaluate and how much of that was the bundle's first render (runkeeps it in__sbLaunch; the rest is the parse), how long after the app started that was, how many root elements were drawn and whether the window size was known by then; and the first frame with the app's views, from the app's start. An app whose launch ends later for the person using it names that moment withmarkLaunch(name)(@swiftbrowser/native), logged once with the time since the start: Codon markspage shownwhen its page, unseen until its layout settles (useLayoutSettled), is first seen. Read these before tuning a launch: they say whether the time is the parser's, the first render's or the host's. useWindowSize()in@swiftbrowser/reactreads the size (null where the host has not said): a layout that picks its columns from the space it has reads it on the first render, where a view's own size (onGeometryChange,GeometryReader) only comes after the renderer laid the view out. Turning or resizing the window sends a new one. A page'smountgives it the root's box.- The launch itself.
NativeRootView(app:background:)fills the window with a color from its first frame, behind the tree, so the moment before the bundle has drawn shows the app's backdrop rather than black; Codon passes its asset catalog'sLaunchBackground(#121418, itstheme.backdrop).
packages/native/: @swiftbrowser/native#
A small npm package: the entry an app bundles, the polyfill classes, and a bundler preset.
// the app's index.tsx
import { run } from '@swiftbrowser/native';
import { App } from './App';
run(<App />);
run does what mount does in packages/react/src/mount.ts without the
DOM: creates a createSwiftUIRoot whose sink is __sbApplyOps, exposes
__sbDispatch as root.dispatch (the color scheme, Dynamic Type size,
size class, platform and window size arrive from Swift through the
protocol's environment event, as they do from the page), starts the root
from the global __sbEnvironment the host set before the bundle ran (see
"The first frame"), and renders. The preset is an esbuild or Vite library
config that emits one app.js for the Xcode target's resources, with
react, react-reconciler and @swiftbrowser/react bundled in and
react-dom absent. @swiftbrowser/react itself needs no change for this,
with one exception: ShareLink calls the web's performHostRequest
directly (components/system.tsx), which should go through a host hook the
native package can provide over UIActivityViewController.
Registered views#
React Native's native components have an analogue in the protocol: the
registered kind, with name: string and arbitrary props, which each
renderer resolves through its own ViewRegistry. The Swift app or a
package registers a SwiftUI view under the name; a page registers its own
element under the same name (@swiftbrowser/web's ViewRegistry,
docs/ops-protocol.md, "Registered views"). One component,
RegisteredView in @swiftbrowser/react, is then a SwiftUI view in the app
and the package's DOM on a page, with no platform check in the app.
ViewRegistry.register("MapView") { context in MapView(region: context.props["region"]) }
<RegisteredView name="MapView" props={{ region }} onEvent={(value) => …} />
Events from the view flow back as a generic { type: "registered", id, name, value } event to the element's on handlers. This is how an app
reaches MapKit, camera, StoreKit or anything else without waiting for the
protocol to cover it, how a team mixes screens (a registered view can hold
an entire SwiftUI feature written in Swift, its children the app's views
inside it), and how a package draws what never crosses the bridge: the
DSP package's ScopeView reads an audio node's frames on the audio
thread's side, natively and on a page. A name a renderer has nothing
registered under draws as a visible placeholder (its children natively).
Not everything is a view. The function half of the hatch is NativeFunctions
(Runtime/NativeFunctions.swift): the Swift app registers functions before the
bundle loads, and the JavaScript calls them.
NativeFunctions.register("purchase") { call in // async: callNative
let product = try await Product.products(for: [call["id"].string ?? ""]).first
...
return ["state": "purchased"]
}
NativeFunctions.registerSync("deviceName") { _ in .string(UIDevice.current.name) }
NativeFunctions.send("transaction", ["id": "pro"]) // Swift reporting unasked
import { callNative, callNativeSync, onNativeEvent, hasNativeFunction } from '@swiftbrowser/native';
const { state } = await callNative<{ state: string }>('purchase', { id: 'pro' });
const name = callNativeSync<string>('deviceName');
const stop = onNativeEvent('transaction', (value) => { ... });
An async function rides the host request path as app:<name>
(HostRequestBridge.swift answers it with the registry before saying
unsupported), so it gets structured concurrency, errors as messages and
cancelled: as an AbortError for free; a sync one runs inline over the
bridge's callNativeSync(name, json); nativeFunctions() lists them. What
Swift sends comes to __sbNativeEvent(name, json) and reaches
onNativeEvent(name)'s listeners. Values cross as JSON (call.decode() reads
the params as a Decodable); everything runs on the main actor, as the rest
of the bridge does, so a function doing heavy work hops off it itself. On the
web build of the same app callNative rejects unsupported: and
nativeFunctions() is empty, so an app checks hasNativeFunction and falls
back to the web's way. swiftbrowser native init writes an
apple/NativeFunctions.swift with a registerNativeFunctions() the App calls
from its init, where these go.
The Showcase's Piano is the worked example: apple/PianoSynth.swift registers
piano.noteOn, piano.noteOff, piano.allNotesOff, piano.sustain and
piano.program, synthesized on an AVAudioSourceNode, and
src/piano/sound.ts calls them with callNativeSync where
hasNativeFunction says so, else plays the same synthesis with the page's
Web Audio API.
Synchronous calls, and what they buy#
Everything runs on the main thread: SwiftUI, the tree, and the
JSContext. A tap is one call chain that returns before the next frame:
Button action (SwiftUI)
→ tree.send(.tap(id)) Swift
→ __sbDispatch('{"type":"tap","id":12}') into JavaScript
→ root.dispatch → handler → setState → React sync flush
→ __sbApplyOps('[…ops…, {"op":"commit"}]') back into Swift
→ tree.apply: nodes mutate inside withAnimation
← returns
← returns
SwiftUI renders the next frame from the mutated nodes
The concrete payoffs:
- Controlled inputs do not flicker. A
TextField's binding setter sendstextwhen the text changed (SwiftUI also writes the binding on a focus and a commit with the text the field has, which sends nothing, as the page sendstextonly for input); when it returns, the node'stextprop already holds the JavaScript state's new value, so the getter SwiftUI calls next reads the truth and the caret stays put (the protocol's rule fortextfieldupdates). React Native's controlledTextInputis the well-known case of what happens when this is asynchronous. - Native-driven state stays consistent. A back swipe or a sheet dismissal that the system performs sends its event and, in the same call, JavaScript's own state catches up, so the next pass agrees with what is on screen.
- Custom layouts become possible.
Layout.sizeThatFitscan ask JavaScript and get an answer within the pass. - Nothing to reason about. No message queue, no batching, no ordering between events and passes, no "state from two frames ago".
The cost is the usual one: JavaScript work blocks the UI thread, as it does
in a web page. For UI logic that is fine. Heavy work goes to a Task on the
Swift side or to a second JSContext on another thread later; the first
version does not need either.
Two rules keep SwiftUI happy. The tree is only mutated from an event or a
timer, never from inside a view body or layout pass (geometry events are
deferred past the pass, as the web does). And dispatch is re-entrant only
through those same paths: a handler that sends another event is fine, a
view body that does is a bug the tree asserts against in Debug.
Development loop#
- Debug builds load
app.jsfrom a dev server (http://localhost:5173/app.jsfrom the Vite or esbuild watcher) instead of the bundle resource, and re-evaluate on change: tear the context down, build a fresh one, render into a fresh tree. That is a full reload, which is whatswiftbrowser devdoes for Wasm today, minus the state snapshot. - Fast Refresh. The dev server (
packages/native/src/build.ts,serve) builds the bundle in two halves (devBuild.ts):vendor.jsholds the runtime,react-refresh's runtime (which installs the DevTools hook before React loads, and the reconciler registers with it throughinjectIntoDevTools), React and@swiftbrowser/react;app.jsholds the app's own modules, each run throughreact-refresh/babelso its components register with the refresh runtime, and importing React and the packages through shims that read__sbVendor. The server'smanifest.jsoncarries a hash per half.NativeApp.watch(url:)polls it: a new vendor half starts the app over; a new app half is evaluated in the running engine, andrun, called again at its end, performs the refresh and renders the new tree into the same root. State survives where a component's hooks are unchanged and resets where they changed, as the signatures decide; no WebSocket or module loader is involved, which bare JavaScriptCore lacks. - Release builds bundle
app.jsinto the app. JavaScriptCore has no bytecode cache for third-party apps; Hermes's.hbcis the answer when startup matters. swiftbrowser native initlays out the Xcode project the wayswiftbrowser initdoes (packages/cli/src/nativeTemplate.ts): one app target, built for iOS and for macOS (SUPPORTED_PLATFORMS, the SDK following the destination; the Mac build has its own entitlements, the App Sandbox with the network and the JIT, and the hardened runtime notarization asks for; docs/notes/macos.md), overapple/(anApp.swiftof three lines, the asset catalog, the bundle) and, at the project's root, the npm project whosenpm run buildwritesapple/app.jsfromsrc/and whosenpm run build:web(Vite,web/) builds the same app as a web page drawn by@swiftbrowser/web's renderer (the iPhone frame on a desktop, full screen on a phone, named withmount'sappoption so its files have a database from day one), laid out as React Native lays its shells out, and a local package dependency on the Swift package@swiftbrowser/nativeships underswift/(sync-swift.mjscopiesNative/Package.swiftandNative/Sourcesin at pack time, without the test target), so the renderer and the JavaScript it runs come at one version from npm; the examples' projects come from the same template, pointed atNative/.--import-type <identifier>=<.ext>[,<.ext>…][:<description>](repeatable; an example'simportedTypesinNative/Examples/projects.json) declares a file type the app opens that the system does not know, inapple/Info.plist'sUTImportedTypeDeclarations, conforming topublic.data: an extension nothing declares is a dynamic type, which the document picker of afileImportermatches to no file, so it would offer any file in its place (docs/ops-protocol.md, "The types, natively"). Codon declares the VST 2 preset and bank (.fxp,.fxb, Serum's and Sylenth1's) and Serum 2's.SerumPresetthis way.- The optional packages (
Native/Packages: SwiftBrowserLocalModel, SwiftBrowserDSP, SwiftBrowserShader, SwiftBrowserCode, SwiftBrowserReality) ship in the same folder, underswift/Packages, laid out as in the repository so their.package(path: "../..")still reaches the core; the copy renames the core in their.product(package:)fromNativetoswift, a path dependency's identity being its folder's name. An app links one withswiftbrowser native init --with <name>or, later,swiftbrowser native add <name>(local-model,dsp,shader,code,reality; packages/cli/src/nativePackages.ts), which adds the package reference and the product to every target that links SwiftBrowserNative, editing project.pbxproj in place and reading it back, and says the line the App'sinitinstalls it with (--withwrites it). SwiftPM resolves only the packages a project references, so the others cost an app nothing but their source innode_modules.swiftbrowser native buildanddevare the bundler under the one CLI;swiftbrowser-nativestays as the thin entry the project's scripts call.
Building and deploying from GitHub Actions#
Three reusable workflows in this repository build and deploy an app, for the Showcase and for an app in another repository of the organization alike (this repository's Actions access setting has to allow the organization's repositories, as it is private):
sb-web.ymlinstalls the app's dependencies (npm, Bun, pnpm or Yarn, by its lockfile), runs itstypecheckandtest:unitscripts where it has them, builds the page (build:web, intodist-web) and deploys it to a Cloudflare Pages project, made if missing: the default branch to production, any other branch or pull request to its alias, whose address it comments on the pull request.sb-ios-adhoc.ymlbundles the app's JavaScript (itsbuildscript), archives the Xcode project with the newest Xcode, signs it with the team's Apple Distribution certificate and an ad hoc profile made fresh through the App Store Connect API with every registered device, exports the IPA, and writes the over-the-air install page around it.deploy: pagesputs the page on theiosalias of the same Pages project (https://ios.<project>.pages.dev, which the web build sees asVITE_IOS_INSTALL_URL);deploy: noneleaves it in the run's artifact for the caller's own upload, to theinstall-urlit names.sb-macos.ymlbundles the app's JavaScript, archives the same project for macOS, signs it with the team's Developer ID Application certificate under the hardened runtime, exports the app, submits it to Apple's notary service through the App Store Connect API (notarytool), waits for the ticket and staples it, zips the app and writes a download page around it.deploy: pagesputs the page on themacalias of the Pages project (https://mac.<project>.pages.dev);deploy: noneleaves it in the run's artifact, for thedownload-urlthe caller names. Without the Developer ID secrets the app is still built, signed ad hoc and kept as the artifact (not notarized or deployed), so a fork or a new repository tries its Mac build on every run; native.yml builds the examples and a new app for macOS, unsigned, the same way.
The profile and the page are swiftbrowser-native ios-profile and
swiftbrowser-native ios-install-page (packages/native/src/ios.ts), run
from the app's own node_modules, so they come at the version of the app's
@swiftbrowser packages, as the workflows do when a caller pins them to the
same release:
jobs:
web:
uses: noya-app/SwiftBrowser/.github/workflows/sb-web.yml@v0.19.0
with: { pages-project: my-app }
secrets: inherit
ios:
uses: noya-app/SwiftBrowser/.github/workflows/sb-ios-adhoc.yml@v0.19.0
with: { app: MyApp, bundle-id: com.example.MyApp, pages-project: my-app }
secrets: inherit
macos:
uses: noya-app/SwiftBrowser/.github/workflows/sb-macos.yml@v0.27.0
with: { app: MyApp, bundle-id: com.example.MyApp, pages-project: my-app }
secrets: inherit
swiftbrowser native init --github writes those callers
(packages/cli/src/nativeWorkflows.ts): web.yml on pushes and pull
requests, ios.yml and macos.yml by hand, in the repository's .github/workflows,
named for the app and limited to its folder's paths when the app is in a
folder of a larger repository. The Showcase's showcase.yml,
showcase-ios.yml and showcase-macos.yml call the same workflows from this
checkout, so a change to them runs on the Showcase first. The secrets are
the repository's (or the organization's, passed with secrets: inherit):
CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID; for the iOS build
APPLE_TEAM_ID, APPLE_DIST_P12_BASE64, APPLE_DIST_P12_PASSWORD, ASC_KEY_ID,
ASC_ISSUER_ID and ASC_KEY_P8; for the Mac build the same team and App
Store Connect key, and APPLE_DEVID_P12_BASE64 and APPLE_DEVID_P12_PASSWORD
(a Developer ID Application certificate, exported from Keychain Access as
a .p12 and base64 encoded, as the distribution one is). Notarizing needs
the key to have at least the Developer role.
The round trip#
The native views compile against the shim too: the root Package.swift
declares the Native package's three targets a second time over
Sources/SwiftUI (SwiftBrowserProtocol, SwiftBrowserTree and
SwiftBrowserNative with FoundationBridge, UIKit and os, in the
Native package's Swift 6 mode), and Native/RoundTrip is an executable over
them: a WindowGroup showing NativeRootView for a NativeApp whose engine
is the host's own JavaScript. Built for WebAssembly, it is the renderer run
backwards: a JavaScript app's ops go in, the native views draw them with the
shim's SwiftUI, and the shim emits ops again. Where the views map an element
right, what comes out builds the tree that went in; where they do not, the
difference is a line in a diff, found headless on Linux in the time it takes
to run the module.
- The engine is the host.
WebHost(Host/WebHost.swift) implementsJSHostover one WebAssembly import,sb_native.request, which carrieseval,call,has,installandreset; the host answers in a buffer it takes fromsb_alloc, and the installed native functions (applyOps,log,now, …) come back through the module'ssb_native_invokeexport, each a function on__sbNative.Web/src/nativeHost.ts(@swiftbrowser/native/wasm-hostre-exports it) is the JavaScript half, the same for Node and a page;scripts/run-wasi.mjsattaches it to any module that importssb_native, andSB_ARGSadds the launch arguments. The calls are synchronous in both directions, as WebAssembly's are. - Built against the shim means
canImport(FoundationBridge):Host/ShimAliases.swiftsettles the names the shim and Foundation both declare (geometry is the shim's;Timer,UserDefaults,URLSessionandDispatchQueuethe bridge's, as the CLI's staging does for an app), the iOS-only modifiers the shim implements (EditButton,editMode,fullScreenCover, the title display mode) are gatedos(iOS) || canImport(FoundationBridge), and the two things the shim lacks draw nothing there: an SVG path for a custom shape, andnavigationBarBackButtonHidden. Natively on Linux the same targets build in the root package'sswift build, so the views type-check without a Mac. - The comparison.
scripts/native-roundtrip.mjsruns the Fidelity bundle (Native/Examples/Fidelity) twice per screen: in Node over a recording__sbNative, for the app's own ops, and as the module's app underrun-wasi.mjs, headless, for the shim's. Both op streams are replayed into trees and listed one element per line without ids, and the listings are diffed;summary.mdcounts the differing lines per screen. TheNativeworkflow'sroundtripjob runs it and uploads the listings. The bundle runs in a realm of its own with a microtask queue of its own, drained after each call the module makes into it, and the module installs the host executor before the load: React's effects and the renders they start (anonAppearpresenting a sheet) run on the module's clock inside one headless run, as they do in an app, rather than wait for a turn of Node's event loop the run never takes. The root view's window (the frame the tree fills and the background that measures it) is the host's and is left out of the listing. It checks the mapping against the shim's definition of SwiftUI, so it catches structural mistakes (an icon drawn outside aLabel, a text button where iOS drawsEditButton, a spinner drawn as a symbol); the simulator comparison above still owns anything the shim itself has wrong. - What it found. The first run drew 150 elements for the list screen's
- The differences were mapping bugs the simulator had let through, each
now fixed in the views: a string section header built as a view header,
a background in an
if(a conditional decoration to SwiftUI), every toolbar placement declared whether or not it had items, a field's submit action, submit label and focus binding applied unasked, a slider with an empty label,.headlinegiven a weight it already has, rich text begun from an empty run, atintforeground drawn as the accent color, a padding naming edges the app did not,.tabItemwhere iOS 18 hasTab(which is what the protocol'stabcarries), a list row of one child wrapped in a stack,strokeBorderpadded instead of inset, and the protocol's spinner and current-value-label encodings drawn twice. With those, every screen the two Fidelity apps share round-trips to the same tree, the sheet and alert included. Three things the comparison settles on both sides rather than compares, because the shim and@swiftbrowser/reactencode them differently: text-baseline stack alignment (the shim names itcenter), a text's flattenedtextwhen it has runs, and alistrow's false flags and a padding's zero edges, which the shim writes out; alazyspacer'sremainingis the shim's own batching of the rows it is given, so a list past its batch of 12 rows compares its first batch. The one structure the native views draw themselves, anavlinkrow's button and chevron, is read back as thenavlinkit stands for.
- The differences were mapping bugs the simulator had let through, each
now fixed in the views: a string section header built as a view header,
a background in an
- In a page the same module runs the native app in the browser.
swiftbrowser-native site <entry> --out <dir>(swiftbrowser native site;packages/native/src/site.ts) writes the app as a static site in the layoutswiftbrowser buildwrites for a Swift app: the page, the module (the one@swiftbrowser/nativeships underwasm/, built and optimized by the release workflow;--modulefor another) and the app's bundle as its one resource,/bundle/app.js, which the module reads at launch. The page's loader (Web/src/wasm.ts) sees the module importsb_nativeand gives it the host (Web/src/nativeHost.ts, the same code Node runs): the bundle is evaluated at the page's global scope, where the runtime finds the browser's ownfetch, timers and storage and installs nothing over them, so the app's requests are the page's, same origin and cookies included; the shim's ops reach the web renderer as any app's do, and its events go back through the native views into__sbDispatch.--base /path/builds the site for a path inside another site. TheNativeworkflow'sroundtripjob builds the Fidelity example this way and opens it in Chromium (scripts/native-site-check.mjs).
Testing#
- Protocol decoding: every example's snapshot decodes.
- Tree application: snapshots apply to an
OpTreeand the resulting tree matchespackages/react/test/opsTree.ts's reading of the same ops. - Rendering:
ImageRenderersnapshots of the Fidelity screens, built from the React Fidelity app's ops, in a macOS or simulator test. - Fidelity against SwiftUI:
scripts/ios-screenshots.shalready screenshotsExamples/Fidelityon the simulator. A sibling script screenshots the native renderer drawing the React Fidelity app on the same simulator and diffs them, like.github/workflows/ios-fidelity.ymldoes for the browser. The target here is zero, since both sides are SwiftUI with SF Pro; every differing pixel is a mapping bug. - CI: a macOS job beside
ios-source-compatbuildsNative/and runs its tests; the Linux jobs never see it.
Milestones#
- Counter.
Native/Package.swift, the protocol types for the kindsExamples/Counteruses (text,vstack,hstack,spacer,button,styledwith padding, font, foreground, background, frame and cornerRadius), the tree, the JavaScriptCore host with timers and console,@swiftbrowser/native'srun, andExamples/NativeCounter: an Xcode project whoseCounter.tsxis the Swift Counter ported to@swiftbrowser/react.counter.jsonlapplied to the tree is the first test. - Todos.
list,section,navstack,navscreen,navlink,textfield,toggle,sheet, theenvironmentevent, animated commits.Examples/Todosported to@swiftbrowser/reactis the app, andExamples/Todos/__snapshots__the op stream to apply. - Fidelity. The rest of the kinds, screen by screen against the
simulator screenshots, plus
fetchand the other globals;tabview,picker,alert,toolbar,searchfield, gestures, swipe actions, context menus, charts, canvas. - Developer experience. Dev-server reload, Fast Refresh, the
nativeescape hatch andswiftbrowser native init(done: the Swift package ships inside@swiftbrowser/native), and a look at Hermes for startup time.
Open questions#
- Name and placement.
Native/besideWeb/withpackages/nativefor the npm side follows the repository's pattern (a renderer directory per host, a package per npm artifact). It could also bepackages/nativealone, holding both manifests. - Lazy content. The protocol's
lazyevents andlazyspacerexist because the web renderer asks Swift for rows as they scroll into view.LazyVStackandListdo that natively; whether the React components' lazy mode can simply be off natively, or should driveonAppear, needs a look atpackages/react/src/lazy.tsx. - Interop with Swift apps. A SwiftUI app could host a JavaScript screen
(
NativeHostView(bundle:)as one view in an otherwise Swift app), which is the incremental-adoption story React Native has and this design gets almost for free: the root view is just a view. - Running the Swift examples natively. Nothing stops the Swift Wasm
module from being the producer instead of JavaScript: the same
OpTreecould render a Wasm module's ops through a Wasm runtime on iOS. Not a goal, but it shows the renderer is independent of who emits the ops.