@swiftbrowser/react#
SwiftUI's components for React. A pure React/TypeScript web app writes its
screens with List, NavigationStack, Toggle, Picker and the rest, and
gets the same iOS UI a SwiftUI app gets in SwiftBrowser: the components emit
the render ops the Swift shim emits, and the
web renderer draws them with its iOS layout engine,
typography, animations, navigation bars, tab bars, sheets and alerts. No
Swift, no WebAssembly: the package is React components and a renderer host.
It works in both directions with ordinary React, and the two nest: a
SwiftUI tree can live inside a react-dom page, and ordinary React DOM can
live inside a SwiftUI element (see Mixing with ordinary React).
The package is experimental.
npm install @swiftbrowser/react @swiftbrowser/web react react-dom react-reconciler
react-reconciler is a peer dependency, so the app picks the release that
matches its React: 0.31 for React 19.0, 0.32 for 19.1, 0.33 for 19.2, 0.34
for 19.3 (npm install react-reconciler@0.33 on React 19.2, say); the
package works with all four.
It is built for a bundler (Vite, or any that compiles TypeScript in
dependencies): the renderer it drives comes from @swiftbrowser/web's
TypeScript sources, as does the stylesheet the page imports. The stylesheet
is the renderer's alone (the device's tokens, the frame, the elements): it
leaves the page's own body, classes and box model as they are, and an
island is as wide and as tall as the page's CSS makes it. With Vite, list
@swiftbrowser/web in optimizeDeps.exclude so the renderer's bitmap
worker resolves from its sources.
Getting started#
A new app#
One command lays out an app that runs the same code on iOS and the web:
npx @swiftbrowser/cli native init MyApp
cd MyApp && npm install
npm run dev:web # the app as a web page, at http://localhost:5175/
npm run build # apple/app.js, the bundle MyApp.xcodeproj runs natively (iOS and macOS)
The app is src/App.tsx, beside apple/ (the Xcode target's folder: the
App file, the asset catalog and the bundle), web/ and MyApp.xcodeproj,
as React Native lays its shells out. src/index.tsx is the iOS entry (run(<App />)
in a SwiftBrowser Native
app, where the views are real SwiftUI) and web/main.tsx the web entry
(mount(...) in a Vite page, where this package's renderer draws them);
neither holds app code. The rest of this section is what those entries do.
A whole page#
The simplest app is a page whose root is a SwiftUI tree. The page provides
the renderer's stylesheet and a root element, and mount draws the tree in
it. In the device frame (the markup of index.html here, with the iPhone
bezel, status bar and the theme controls) the root is the #screen element;
on a phone the renderer can also draw full screen.
import '@swiftbrowser/web/src/styles.css';
import { useState } from 'react';
import { mount, Label, List, NavigationLink, NavigationStack, Section, Text, Toggle } from '@swiftbrowser/react';
function Library() {
const [downloads, setDownloads] = useState(true);
return (
<List navigationTitle="Library">
<Section header="Reading">
<NavigationLink destination={<Text>Detail</Text>}>
<Text>The Swift Programming Language</Text>
</NavigationLink>
</Section>
<Section header="Settings">
<Toggle isOn={[downloads, setDownloads]}>
<Label title="Automatic Downloads" systemImage="arrow.down.circle" />
</Toggle>
</Section>
</List>
);
}
mount(document.getElementById('screen')!, <NavigationStack><Library /></NavigationStack>);
mount returns the root and the renderer; setEnvironment({ colorScheme, dynamicTypeSize }) on it switches dark mode and the Dynamic Type size, as
the demo page's controls do.
Inside an existing React app#
In a react-dom app, SwiftUIView is a normal component that draws its
children with the renderer in a box of the page's own layout, with the
device's design tokens and none of its frame:
import '@swiftbrowser/web/src/styles.css';
import { SwiftUIView, List, Section, Toggle } from '@swiftbrowser/react';
function Settings({ dark, setDark }) {
return (
<SwiftUIView fit="content" colorScheme={dark ? 'dark' : 'light'} className="settings">
<List>
<Section header="Appearance">
<Toggle title="Dark Mode" isOn={[dark, setDark]} />
</Section>
</List>
</SwiftUIView>
);
}
fit="content" makes the island as tall as its content, like a block in
the page's flow; fit="fill" (the default) draws in the box the page sizes
with CSS, which is what navigation stacks and tab views want, since they fill
their screen. colorScheme and dynamicTypeSize are props. The island is
a React root of its own: the page's React state reaches it through props as
usual, and its contexts through contexts={[…]} (see
Contexts across roots).
There is no status bar in a page, so an island's views start at its top.
The bars SwiftBrowser draws keep off the edge on their own: a fill
island's navigation bars and sheets keep 10 points clear at the top
(barClearance), the way SwiftUI keeps a window's bars off its edge, with
their background reaching up into it; a content island's keep none.
barClearance={0} puts the bars flush with the edge. safeArea stands in
for a status bar and a home indicator that are there (an app installed to
the home screen): a number for the top inset, or an object such as
safeArea={{ top: 24, bottom: 34 }}, which the views and the bars both
keep clear of.
Try the demos#
npm install
cd packages/react
npm run dev # http://localhost:5174/ — Examples/Fidelity, in React
# http://localhost:5174/island.html — islands in a react-dom page
# http://localhost:5174/wide.html — a regular-width app: split view, table, inspector
npm run test:unit # the React Fidelity tabs emit the same tree as the Swift app
?screen=<name> on the first page opens one of the Fidelity screens alone
(list, detail, form, controls, typography, shapes, layout,
tabs, sheet, alert, search, post, settings, reorder), like the
Swift app's -screen argument; extras, more and web show the
components beyond it.
Writing views#
Components#
The components are named as in SwiftUI and take the same arguments as
props: <VStack alignment="leading" spacing={8}>, <Text font="headline">,
<Image systemName="heart.fill" />, <Button title="Save" action={save} />,
<Picker label="Plan" selection={[plan, setPlan]} options={plans} />,
<Section header="Reading" footer="…">. Children are the content closure.
ForEach takes data and a render function, with id, onDelete and
onMove as in SwiftUI; Group applies its modifiers to each child.
Text is plain strings and numbers inside <Text>; nested <Text>s and
inline <Image>s make a rich text (Text + Text), and italic,
underline, strikethrough, tracking and monospacedDigit (tabular
digits, also a modifier on any view) are its own props. A nested <Text>'s
font, bold, foregroundStyle and background (a colour behind its
glyphs, as AttributedString's backgroundColor) style its own run.
Modifiers as props#
Every component takes SwiftUI's modifiers as props, and applies them in the order they are written, innermost first, so a chain reads the same:
<Image
systemName="swift"
font={system(17, 'semibold')}
foregroundStyle="white"
frame={{ width: 32, height: 32 }}
background={{ fill: 'orange', in: <RoundedRectangle cornerRadius={8} /> }}
/>
is Image(systemName: "swift").font(.system(size: 17, weight: .semibold)) .foregroundStyle(.white).frame(width: 32, height: 32).background(.orange, in: RoundedRectangle(cornerRadius: 8)). Each modifier wraps the view in the same
styled element the Swift shim emits, so the renderer lays it out
identically; neighbouring modifiers that one styled draws alike share one
element (padding={8} background="red" is one, background="red" padding={8} two). The order matters as it does in SwiftUI:
aspectRatio={{ ratio: 1, contentMode: 'fit' }} frame={{ maxWidth: 420 }}
is a square of at most 420 (the frame offers at most 420, and the square
fits in it), while frame written first offers the square the full width
and then only narrows it. A modifier that must apply twice goes in
modifiers={[…]}, an ordered list. A layered style is an array: foregroundStyle={['white', 'indigo']} is .foregroundStyle(.white, .indigo), whose second style a
symbolRenderingMode="palette" symbol draws its disc in. The environment
modifiers (buttonStyle, controlSize, pickerStyle, toggleStyle, labelsHidden,
symbolRenderingMode) are React contexts the views below read, and
navigationTitle, navigationSubtitle (the Mac idiom's title bar draws it; iOS
ignores it), toolbar, toolbarRole, toolbarVisibility (the
navigation bar or the bottom bar hidden, as .toolbar(.hidden, for:)),
statusBarHidden, searchable, sheet, alert,
presentationDetents and preferredColorScheme attach to the enclosing
screen, sheet or page, as the SwiftUI preferences do; where views nested
in each other set the same one, the innermost wins (a List's
navigationTitle over the one on the VStack around it).
navigationBackGestureDisabled, which SwiftUI does not have, is one more
of them: the pushed screen it is on takes no swipe back from its leading
edge, so a drag that starts there reaches the content (a canvas drawn on to
the edge of the screen); the back button still pops. It reaches the host's
screen from an app drawn in a RemoteTree as the title does. Effects (blur,
grayscale, saturation, brightness, contrast, hueRotation,
colorInvert, colorMultiply, blendMode, mask, rotation3DEffect),
layout hints (aspectRatio, scaledToFit, position, zIndex,
alignmentGuide, ignoresSafeArea, allowsHitTesting, lineLimit ranges)
and the lifecycle (onAppear, task with an AbortSignal for
cancellation, onChangeOf) are modifiers too, as are draggable and
dropDestination (what another draggable lifted, and from outside the
app what accepts takes: text, links, and files as Files, a dropped
folder as its files named by their paths in it, the folder's name first,
as fileImporter names a picked folder's; natively the files stay on disk
and are read when asked).
Values are plain data: colors by name ("red", "secondary",
"secondarySystemBackground") or through Color (Color.opacity('black', 0.2), Color.gradient('teal'), Color.hex('#336699')); fonts by text
style ("title2") or { textStyle: 'title2', weight: 'bold' } and
system(size, weight, design); frames as { width, height, maxWidth: Infinity, alignment }; padding as true, a number, ['vertical', 6] or
insets; gradients through LinearGradient, RadialGradient and
AngularGradient.
Bindings#
A binding is a useState pair, so isOn={[downloads, setDownloads]} reads
like isOn: $downloads. Everything that takes one (Toggle, Picker,
Slider, Stepper, TextField, TextEditor, DatePicker, TabView's
selection, List's selection and editing, NavigationStack's path,
the sheet and alert modifiers' isPresented) also takes a plain value
with an onChange handler. The setter can be anything with that signature.
When the renderer sends an event (a tap, a switch, a selection), the handler's state updates render synchronously and the renderer gets the next pass inside the event, the way the Swift core answers one.
TextEditor also edits AttributedText, SwiftUI's AttributedString in
TextEditor(text:selection:): runs of { text, bold, italic, underline, strikethrough, foregroundColor, backgroundColor, font } (backgroundColor
a highlight behind the run, font its own { size, weight, design } over
the editor's). What the viewer types takes the
attributes of what it replaced, else of the character before it, and the
formatting the native editor's own edit menu applies (iOS 26's Bold,
Italic, Underline) comes back into the text. A selection binding, on a
plain or an attributed editor, gets the viewer's selection in UTF-16
offsets, so a Bold button can set AttributedText.settingAttributes(text, start, end, { bold: true }) on it; a selection the app sets moves the
caret (when the app focuses the editor, if it is not focused). A text the
app sets that is not the echo of what the viewer typed (another person's
edit) keeps the caret in place: the app's selection is applied even when
its numbers did not change, and without one the caret is moved past the
change.
.scrollDisabled makes an editor as tall as its lines, for one in a
scrolling page:
const [text, setText] = useState<AttributedText>([{ text: 'Hello ' }, { text: 'world', bold: true }]);
const [selection, setSelection] = useState<TextSelection>({ start: 0, end: 0 });
<TextEditor text={[text, setText]} selection={[selection, setSelection]} scrollDisabled />
TextField and TextEditor take onDeleteBackward, which SwiftUI has no
modifier for: Backspace with nothing selected and the caret at the start of
the text (an empty field included) deletes nothing and runs it, so a
paragraph editor can merge the paragraph into the one before it.
measureText(text, font, width) is the size a Text of text in font
(a text style name or system(size, weight, design)) takes wrapped to
width points: { width, height, lines }, answered synchronously by the
renderer's typography on the web and by the host's text system natively
(canMeasureText() says whether something answers yet), for an app that
paginates or sizes from its text.
A field's focused is .focused($isFocused): a boolean binding the field
follows and sets. With focusedValue it is .focused($field, equals:):
one binding of the focused field's value (null for none) shared by the
fields, each naming its own. What a handler for onSubmit sets wins over
the keyboard's dismissal (the same field again keeps it, another takes it),
and a field that takes the focus is scrolled into view:
const [field, setField] = useState<'username' | 'password' | null>('username');
<TextField placeholder="Username" text={[name, setName]} focused={[field, setField]} focusedValue="username" onSubmit={() => setField('password')} />
<SecureField placeholder="Password" text={[password, setPassword]} focused={[field, setField]} focusedValue="password" onSubmit={signIn} />
Navigation and presentation#
NavigationStack holds the pushed values (or takes a path binding).
NavigationLink pushes a value, which the enclosing screen's
navigationDestination builds a screen for, or a destination view
directly. A pushed screen's title takes the display mode of the screen below
it unless it sets its own (large below a large title), as on iOS. TabView
holds Tabs, each with a systemImage or an asset catalog image (a custom
symbol) for its bar item. .sheet and .alert are modifiers whose
content and actions render as root-level elements while presented (an
alert's actions take a TextField beside the Buttons, drawn in the
card above them: alert={{ title: 'Rename', isPresented, actions: <><TextField text={[name, setName]} /><Button title="Cancel" role="cancel" /><Button title="Rename" action={rename} /></> }});
presentationDetents inside a sheet sets its detents. useDismiss() inside
a pushed screen or a sheet pops or dismisses it.
A sheet, a full-screen cover or a popover inherits the environment of the
view that presents it, as SwiftUI's presentations do, though it is drawn at
the root: a defaultMinListRowHeight, font, fontWeight, bold,
monospacedDigit, tint, lineLimit, multilineTextAlignment or
imageScale set around the presenter reaches the sheet's lists and text,
and so does one set on the presenting view itself when written after the
sheet (around it, as SwiftUI orders modifiers). An app drawn through
RemoteTree has its sheets inherit the host's environment around the tree
too.
Navigation is mirrored in the browser's history by default: pushing a
screen or presenting a sheet adds an entry, and the browser's back (a
phone's edge swipe, Android's back gesture, the toolbar button) pops or
dismisses it exactly as the bar's back button would, through the app's own
state. The renderer's own swipe back ignores touch meanwhile, so the
browser's edge swipe is the swipe back (a mouse drag from the edge still
pops, since no browser navigates on one). The app popping on its own takes the history back
with it, and forward returns to the entry that matches rather than
re-pushing. In a wide window a NavigationSplitView pushes nothing when
its sidebar's selection moves, so that is an entry of its own: choosing
another sidebar row adds one (the first choice does not), and back or
forward selects the row the entry recorded, through the row's own tap. The
URL is left alone: an app that maps screens to paths sets them with
history.replaceState on the entry the renderer made (a pushState of its
own would add a second entry for the same screen). When the app pops on its
own (the bar's back button), the renderer's step back is asynchronous and
the app's replaceState for what it shows now runs before it lands; the
renderer sets that URL again on the entry it arrives at, so the address bar
follows either back button. A reload keeps the entry it was on, and its URL,
while the app restores the screens it shows (ten seconds at most), rather
than stepping back to an older entry at the first commit.
On a phone, a fill island follows the on-screen keyboard (keyboard,
on by default for fill, or mount(..., { keyboard: true })): its height
becomes a bottom inset, so a field, a bottom search field or a chat's
composer rises above it and a list stops above it, as on iOS, instead of
the browser panning the page to the field. A content island leaves the
page to the browser.
<SwiftUIView history={false}> (or mount(..., { history: false })) leaves
the history untouched, for an island in a page whose own router owns it.
Toolbars#
ToolbarItem's placement takes SwiftUI's names. secondaryAction items
collapse into the bar's More menu (an ellipsis at the trailing end), as on
an iPhone; with toolbarRole="editor" on the screen, a regular width shows
them in the bar before the trailing items, and only those that do not fit
go into More. Items float in Liquid Glass capsules, as iOS 26's do:
consecutive items of one placement share a capsule (in the navigation bar
too, so two trailing ToolbarItems are one capsule, not two circles), and
a ToolbarSpacer of that placement ends it. In the bar the capsules sit
12 apart; at the foot of the screen a flexible spacer (the default)
pushes the groups apart and a fixed one keeps them centered, 8 apart. A
swapped item ({playing ? <ToolbarItem>…stop…</ToolbarItem> : <ToolbarItem>…play…</ToolbarItem>}) changes on a capsule that stays.
<ToolbarItem placement="bottomBar">{undoButton}{redoButton}</ToolbarItem>
<ToolbarSpacer sizing="fixed" placement="bottomBar" />
<ToolbarItem placement="bottomBar">{toolButtons}</ToolbarItem>
placement="largeTitle" (iOS 26) puts a view in the large title row in
place of the title's text, a logo beside the screen's name say; it scrolls
away with the content and the bar shows navigationTitle once it has.
placement="keyboard" is the bar above the keyboard while a text input of
the screen is being edited (a formatting bar, a Done button), its items in
a row from the leading edge, a Spacer pushing the rest to the trailing
edge; it is hidden while nothing in the screen is being edited. A Label
in a bar shows its icon alone, its title the icon's accessible name, as iOS
draws a bar's labels; labelStyle="titleAndIcon" on it shows both, and a
Menu's items keep their labels' title and icon. A Menu among a menu's
items is a submenu, as on iOS: a row with its label (a second Text in it
is a subtitle, where iOS shows the current choice) and a chevron, which
opens a panel of its own over the menu, headed by the label, with the menu
pushed back behind it until the header or the menu is tapped (a Section
is inline instead, its header a caption). A Menu's items, and a
contextMenu's, are built when it opens and dropped when it closes, as on
iOS (docs/ops-protocol.md, "Lazy menus"): a closed menu is its label alone,
however many choices it has. lazy={false} builds them from the start; a
submenu's are built with its menu's, and every menu's in a headless host
(swiftbrowser-shot), whose scripts tap them without opening the menu.
Keep a bar's items the
same from the push's first frame: iOS sizes their glass as the push starts
and lays it out again only once the push ends, so an item that arrives with
fetched data (an Edit button once the rows are in) sits clipped in the
bar until then. Render it from the start and disable it instead.
<List
navigationTitle="Notes"
toolbarRole="editor"
toolbar={
<>
<ToolbarItem placement="primaryAction">
<Button action={compose}>
<Image systemName="square.and.pencil" />
</Button>
</ToolbarItem>
<ToolbarItem placement="secondaryAction">
<Button title="Export" action={exportNotes} />
</ToolbarItem>
<ToolbarItem placement="secondaryAction">
<Button title="Archive" action={archive} />
</ToolbarItem>
</>
}
>
{/* … */}
</List>
Lists#
List and Form hold Sections and rows. selection={[…]} makes rows with
a tag (or a NavigationLink value) selectable, one value or a Set;
editing is the edit mode, which EditButton flips. ForEach's onDelete
makes its rows deletable (a swipe, or edit mode's minus) and onMove makes
them reorder with a grip, with moveItems to apply the move to an array.
swipeActions, contextMenu and listRowBackground are modifiers on a row.
defaultMinListRowHeight is .environment(\.defaultMinListRowHeight, _):
set on any view, every list below spaces its rows at least that tall,
including the lists of an app drawn through RemoteTree. A Mac content
list's rows are 24 by default, where Apple's Mac apps space them like the
sidebar's, 32: one modifier at an app's top gives them all that. A list's
own minRowHeight overrides it for that list, and a Mac grouped form keeps
its form rows.
const mac = usePlatform() === 'macos';
<NavigationSplitView defaultMinListRowHeight={mac ? 32 : undefined} sidebar={…} detail={…} />
Size classes#
useHorizontalSizeClass() is compact below 700 points of width (a phone)
and regular from it (a tablet, a desktop window); mount and
SwiftUIView follow the root's width as it changes. The views that adapt do
it as on iOS: NavigationSplitView is two columns when regular (the
sidebar's toggle button hides and shows the sidebar) and one stack when
compact, which pushes the detail while a List(selection:) in the sidebar
has a selection and clears it on back (lists without a selection, and
anything a sheet, popover or inspector presents, have no say). A detail
that is a NavigationStack with a path binding keeps what it pushes in
that binding in both widths, so an app that mirrors the path in the URL
sees the same path on a phone as in a wide window, and a path it starts
with (a reload onto a deep link) is shown over the detail; .inspector is a trailing panel when
regular and a sheet when compact (inside a NavigationStack's screen the
panel is a column beside the screen, the whole height, and the screen's bar
and content keep to the rest, as on iPadOS; through RemoteTree an app's
inspector becomes such a column of the host's screen); Table shows every column under sortable
titles when regular and the first column when compact.
<NavigationSplitView
sidebar={<List selection={[team, setTeam]}>{/* rows with a tag */}</List>}
detail={<Table data={people} columns={columns} sortOrder={[order, setOrder]} />}
/>
sidebarWidth is SwiftUI's .navigationSplitViewColumnWidth on the sidebar:
a number fixes the column's width; { min, ideal, max } starts it at ideal
and, on a Mac, lets the user drag it between min and max. Without it the
sidebar is the platform's default (140 on a Mac, 320 on an iPad); Apple's Mac
apps use about 200. onSidebarWidthChange(width) hears the width the user
dragged the sidebar to on a Mac, once the drag ends; keep it (in
useAppStorage, say) and pass it back as ideal to start there next time, as
a Mac app restores its columns.
On a Mac the sidebar panel's top 44 points are the window's color, where
macOS draws the title bar behind the window's buttons. A page has no window
buttons there; <SwiftUIView sidebarTitleBar={false}> (or mount(..., { sidebarTitleBar: false }), renderer.sidebarTitleBar = false) keeps the
panel's sidebar fill to its top. Web only: a native app is in a real window.
Platform#
usePlatform() is ios or macos: the platform the app is drawn as. A
page decides it from the browser unless mount's platform option says
(auto, the default, is macos for a fine pointer that can hover at the
regular width, iOS otherwise); a preview page's device picker sets it from
the device chosen (a Mac window is macos); the native app sends the OS it
runs on. The views adapt on their own as SwiftUI's do; read it for a layout
that differs between a phone and a Mac beyond what the size class says. The
Mac idiom the web renderer draws is being built (docs/notes/macos.md).
Scene phase#
useScenePhase() is @Environment(\.scenePhase): active while the app is
in front and takes input, inactive while it shows but does not, and
background while it is not shown. A page follows the document's visibility
(hidden is background) and the window's focus (mount and SwiftUIView
watch them); the native app follows its scene. Refresh what time moved on
when it turns active: timers may not have run in the background.
const phase = useScenePhase();
useEffect(() => {
if (phase === 'active') setToday(dayKey(new Date()));
}, [phase]);
Wake lock#
useWakeLock(active) keeps the screen awake while active (a recording
under way, a recipe being followed), through the Screen Wake Lock API: the
browser's on a page, the runtime's navigator.wakeLock over the idle timer
in a native app. It returns whether a lock is held, and takes the lock
again when the browser let it go as the document hid and it shows again.
Where there is no navigator.wakeLock, nothing happens.
useWakeLock(recorder.status !== 'idle');
Location#
useGeolocation(options) is the viewer's position through the Geolocation
API: the browser's on a page, the runtime's navigator.geolocation over
CLLocationManager in a native app (the app's Info.plist names
NSLocationWhenInUseUsageDescription). Nothing is asked until request()
(the first ask prompts the viewer) unless immediate is set; watch keeps
following the position until stop() or the view goes. The state carries
available, status (idle, locating, located, denied, failed),
the latest position (latitude, longitude, accuracy, altitude,
heading, speed, timestamp) and error.
const location = useGeolocation({ enableHighAccuracy: true });
<Button title="Use My Location" action={location.request} />
{location.position && <Text>{`${location.position.latitude}, ${location.position.longitude}`}</Text>}
Speech#
useSpeechSynthesis() reads text aloud through the Web Speech API (the
browser's voices on a page, AVSpeechSynthesizer in a native app):
speak(text, { lang, rate, pitch, volume }) queues an utterance, cancel()
stops and empties the queue, pause() and resume() hold it, and
speaking and paused follow; what a view was reading stops when it goes.
useSpeechRecognition({ lang, continuous, interimResults }) turns the
viewer's speech into text (the browser's recognizer, SFSpeechRecognizer
natively; the app's Info.plist names NSSpeechRecognitionUsageDescription
and NSMicrophoneUsageDescription): start() listens, transcript is the
final words of the session so far and interim what is being heard,
stop() lets the last words arrive and abort() does not; error names
not-allowed, audio-capture, no-speech or network. Both read
available where the environment lacks the API, and the Showcase's Books
reads a chapter aloud and its Notes takes dictation with them.
const speech = useSpeechSynthesis();
<Button title={speech.speaking ? 'Stop' : 'Read Aloud'} action={() => (speech.speaking ? speech.cancel() : speech.speak(chapterText))} />
Scrolling#
List, LazyVStack and LazyHStack build a long ForEach a batch of
rows at a time as they scroll into view. ScrollViewReader hands a proxy
whose scrollTo(id, anchor) scrolls to the view marked scrollID={id},
building lazy rows up to it first. refreshable (on a List or
ScrollView, or above one) runs an async action on a pull, with the
spinner while it runs. defaultScrollAnchor="bottom" on a ScrollView
opens it at its end and keeps the end in view as content is added while
the viewer is there (a chat); a viewer who scrolled up is left where they
are. scrollTargetBehavior="paging" or "viewAligned" on
a ScrollView snaps, with scrollTargetLayout on the stack inside.
scrollPosition={[id, setId]} on a ScrollView is .scrollPosition(id:):
when scrolling settles it is set to the scrollID of the view at the
scroll view's leading edge (or scrollPositionAnchor), and setting it
scrolls there, on that scroll view's axes only. proxy.scrollTo(id, anchor, { axes: 'horizontal' }) limits a reader's scroll the same way, so a pager
inside a list leaves the list where it is.
onScrollVisibilityChange={(visible) => …} (or { threshold, action },
0.5 by default) is .onScrollVisibilityChange: it hears when that share
of the view comes into its scroll view's visible area, below a bar the
view scrolls under, or leaves it.
Name a coordinate space with coordinateSpace="page" on the ScrollView
(or any view), and a GeometryReader inside reads its frame there with
proxy.frame({ named: 'page' }), updated as the page scrolls.
onGeometryChange={{ of: (proxy) => proxy.size, action: setSize }} is
.onGeometryChange(for:of:action:): the action hears the transform's
answer when it changes, after the render and before anything is painted
(state it sets lays out in the same frame, so a view sized from its own
measurement settles at once), without a reader or a child
that reports in an effect.
A view that measures itself in rounds (rows that stretch to the window
once their heights are reported, drawings redrawn for the sizes they
took) can wait unseen until the rounds end: const settled = useLayoutSettled(active) turns true once the host has laid the tree out
and reported nothing new since its last layout (every host ends a layout
with a laidout event, after what it reported, and reports a size only
when it changed: docs/ops-protocol.md), or after limit milliseconds
(1500 by default) whatever it said. Show the content with
opacity={settled ? 1 : 0}: it is laid out and reports all the while. It
settles once; active false is settled from the start. Put the hook and
the opacity in a component of their own around the content, so showing
it renders that component alone.
onScrollGeometryChange on a ScrollView is .onScrollGeometryChange:
a function hears the scroll view's ScrollGeometry (contentOffset,
contentSize, containerSize, contentInsets, visibleRect) on every
change, once per frame as it scrolls; { of, action } calls action(value, oldValue) only when of(geometry) answers differently, so an app that
watches the content size alone is not rendered per frame. A
scrollPosition binding set to a point ({ x, y }, an axis left out
keeping its offset) scrolls there, as ScrollPosition.scrollTo(x:y:)
does, smoothly inside withAnimation; so does proxy.scrollTo({ x, y })
for the scroll views inside a reader. The binding reads back as ids, never
as a point. pinnedViews={['sectionHeaders']} on a LazyVStack,
LazyHStack, LazyVGrid or LazyHGrid keeps each Section's header at
the scroll view's edge while its section passes ('sectionFooters' too);
a string header pins as a text. The Showcase's Numbers lays a
spreadsheet's frozen letters, numbers and header cells over a
ScrollView axes="both" this way, moved by the offset it reports.
scrollTransition draws effects as a view leaves the visible area of its
scroll view and comes back. The closure gets the effect to build on and the
phase (topLeading, identity or bottomTrailing, with value -1, 0 or
1); it runs once per phase, and the renderer draws the three effects as the
view scrolls (natively, SwiftUI's own .scrollTransition), so they follow
the finger without a round trip to the app. By default the effect follows
the scrolling, drawn partway while the view is partly out;
configuration: 'animated' switches phases with an animation instead.
scrollIndicators="hidden" hides a scroll view's indicators (a pager's). containerRelativeFrame sizes a view against the scroll
view's visible area, so a carousel of cards is:
<ScrollView axes="horizontal" contentMargins={['horizontal', 20]} scrollEdgeEffectStyle="hard">
<HStack spacing={12}>
{cards.map((card) => (
<CardView
key={card.id}
card={card}
containerRelativeFrame={{ axes: 'horizontal', count: 5, span: 2, spacing: 12 }}
scrollTransition={(effect, phase) => effect.scaleEffect(phase.isIdentity ? 1 : 0.85).opacity(phase.isIdentity ? 1 : 0.4)}
/>
))}
</HStack>
</ScrollView>
contentMargins pads the content inside the scroll views below (it scrolls
under the margin). scrollEdgeEffectStyle (hard, soft, automatic, or
["hard", "top"] for one edge) and scrollEdgeEffectHidden set the iOS 26
edge effect where a list or scroll view runs under a bar. All three apply to
the scroll view they are written on and pass down to the ones inside, as
SwiftUI's environment does. LazyHGrid lays its cells into rows column by
column, for a horizontal ScrollView.
Drawing and media#
Shape takes a path function of the rectangle it is laid out in and
draws a Path (move, addLine, addCurve, addArc, addRoundedRect…);
UnevenRoundedRectangle and ContainerRelativeShape are built on it.
Canvas hands its renderer a GraphicsContext (fill, stroke, text, images,
transforms, opacity, clips, filters, gradients in its own coordinates); it
draws once the host reports its size, or at once for a size the app gives
it (a knob's dial, a meter), with no reader to wait for. TimelineView
re-renders on a schedule, so a clock is a TimelineView around a Canvas. Views passed in the symbols prop ({ star: <Image systemName="star.fill" /> }) come back from resolveSymbol and draw with
drawSymbol at a point, under the context's transform and opacity; they are
real views laid over the canvas, so they draw above its other commands. useAVPlayer(url) is an AVPlayer (play, pause, seek,
mute, volume, rate) that VideoPlayer shows in the page's <video>; the
position is read or observed without re-rendering, four times a second or
as often as { report: 1 / 60 } asks (a scrubber moving with the sound). A player shown by no
view plays nothing, so an audio app (a playlist, a podcast) puts an
<AudioPlayer player={…} /> somewhere that stays mounted: the player at
no size, out of the way of taps, playing on wherever the screens go.
new AVQueuePlayer(urls) plays its items one after another (items(),
advanceToNextItem, insert, remove), at the same rate, and pauses
after the last. What plays goes on the lock screen and the media keys
through the browser's own navigator.mediaSession, which the native app
has too (@swiftbrowser/native, "Now playing"). Slider's onEditingChanged says when a drag begins and
ends, so a scrubber bound to the position can stop following it while the
thumb is held.
useAudioRecorder() records from the microphone as AVAudioRecorder does:
record() asks for the microphone and starts, pause(), resume(),
stop() (resolving with the recording's url and duration) and
cancel(); while recording, time counts the seconds and levels holds
the input's level at each tick (0…1, twenty a second), for a waveform. A
refused microphone sets error (permission: …). A recording is a file in
the app's Documents/Recordings (fileManager, below), on both sides: the
page records with MediaRecorder into its IndexedDB home, the native app
AAC with AVAudioRecorder into its sandbox, and discard(url) deletes the
file. The URL plays with useAVPlayer. trim(url, keep) makes a new
recording out of the parts of one in keep ([{ start, end }] in seconds,
in order: one range trims to it, two around a range delete it), resolving
with the new recording and leaving the original for the app to discard; the
page cuts with the Web Audio API and writes WAV, the native app exports AAC
with AVAssetExportSession. (A page that keeps no files answers data:
URLs instead.)
useVideoRecorder() records from the camera, as an app does with an
AVCaptureSession and a movie file output: open() asks for the camera
and the microphone (facing user, the front, or environment) and
starts the live picture, which <CameraPreview recorder={recorder} />
shows (filling its frame, the front camera mirrored); record(), pause(),
resume(), stop() (resolving with the recording's url, duration,
type, width and height, the camera left open for the next), cancel()
and close(), which lets the camera go (as leaving the view does);
flip() turns to the other camera, and time counts the seconds
recorded. A refused camera sets error (permission: …). The page
records with MediaRecorder (MP4 where the browser can, else WebM) into a
blob: URL that plays with useAVPlayer and a VideoPlayer, until
discard(url) lets it go. The native app records with an
AVCaptureSession and a movie file output into a QuickTime file in
Documents/Recordings (a file: URL the app can keep where it is),
upright as the phone is held when recording starts (sideways, a
landscape movie), and draws CameraPreview with the session's preview
layer, upright however the phone turns; its Info.plist names NSCameraUsageDescription
and NSMicrophoneUsageDescription, and pause() needs iOS 18.
AVFoundation's assets edit video, as an iOS app's do. new AVURLAsset(url)
reads a file (await asset.load('duration'), load('tracks'),
loadTracks(AVMediaType.video), load('naturalSize')); times are CMTime
(CMTime.seconds(1.5)) and ranges CMTimeRange.
new AVAssetImageGenerator(asset) draws stills for a thumbnail or a trim
editor's filmstrip (maximumSize, await image(at), images(for)), each a
URL an Image shows. AVMutableComposition places parts of assets one after
another (insertTimeRange(range, asset, at), removeTimeRange(range)), and
new AVAssetExportSession(asset, preset) writes an asset or a composition as
one file: timeRange trims it, outputFileType (AVFileType.mp4, .mov,
and .webm on a page) and outputURL (a file of the app's; without one the
host makes a URL) say where, progress and onProgress follow it,
cancelExport() stops it, and await export() answers the URL.
AVAssetExportPresetPassthrough copies the media, its cuts landing on key
frames; the other presets (HighestQuality, MediumQuality, LowQuality,
640x480 … 3840x2160) re-encode, cutting exactly, fitted to the preset's
size and never scaled up. The page reads and writes MP4, MOV and WebM with
WebCodecs (through mediabunny, loaded the first time); parts joined without
re-encoding must share their codecs. The native app does it all with
AVFoundation itself, into MP4 or MOV.
AVAudioEngine makes sound from the app, as an iOS app's does: attach
nodes, connect them toward mainMixerNode, await engine.start(), then
play. AVAudioPlayerNode plays files (await AVAudioFile.open(url)) and
buffers on a timeline (scheduleFile, scheduleSegment, scheduleBuffer
with loops and interruptsAtLoop, each at an AVAudioTime sample time or
after the last, resolving once played); a buffer is read from a file or
written from the app's own samples (new AVAudioPCMBuffer(format, frames).write([Float32Array])). AVAudioUnitSampler plays notes
(startNote, stopNote, sendController, sendPitchBend) from
loadAudioFiles(urls), each file placed on the keyboard by the note in its
name (Piano C4.wav, C4 = 60) or rootNotes, pitched across the keys up
to halfway to the next. AVAudioUnitReverb, AVAudioUnitDelay,
AVAudioUnitDistortion, AVAudioUnitEQ and AVAudioUnitTimePitch shape
what passes through them, inputNode is the microphone, and meter()
reads a node's level. useAudioEngine(build) gives a view an engine for
its life. The page plays through the Web Audio API, the native app through
AVAudioEngine itself; per-sample work never runs in JavaScript. A page
cannot load sound banks or shift pitch apart from speed (time-pitch passes
its input through there). For synthesis, @swiftbrowser/dsp adds DSPNode:
a program in a small JavaScript-like language, compiled at build time and
rendered on the audio thread, played with the sampler's note calls.
LanguageModelSession talks to Apple Intelligence's on-device model, as
FoundationModels does. Check SystemLanguageModel.default.availability()
(or useSystemLanguageModel()) and say why when it is unavailable
(deviceNotEligible, appleIntelligenceNotEnabled, modelNotReady); make a
session with instructions, then await session.respond(prompt) for the
whole answer or for await (const { content } of session.streamResponse(prompt)) for the answer so far as it grows
(cancel() stops it). The session keeps the conversation. Failures are
GenerationErrors with a kind (exceededContextWindowSize,
guardrailViolation, …). Natively the model is FoundationModels' (iOS 26);
on a page it is Chrome's built-in model where the browser has one.
An image is inert, as a SwiftUI image is. <AsyncImage url={…} webInteractions /> gives a remote picture the browser's own image
interactions back: a long press's Save / Share / Copy on iOS, dragging it
out of the page, the right-click menu. Use it on an image with no tap,
gesture or context menu of its own. placeholder shows until the image
loaded, failure when it could not, and loadingIndicator goes over the
placeholder once a load has run for loadingIndicatorDelay ms (300 by
default): a <ProgressView /> for a big picture on a slow connection,
nothing for one that comes quickly or from the cache. The image's
modifiers apply in every phase, as a SwiftUI AsyncImage's do: a
thumbnail with frame={{ width: 72, height: 48 }} keeps its box while it
loads (with no placeholder, an empty one), so the text beside it does not
move when the picture arrives; a placeholder at the picture's aspect
ratio does the same for a picture drawn at its own shape. All three show
in a SwiftBrowser Native app too.
keyboardType, textContentType, textInputAutocapitalization and
autocorrectionDisabled are SwiftUI's text input hints, for the field they
are written on or the fields below: <TextField text={[email, setEmail]} keyboardType="emailAddress" textContentType="emailAddress" textInputAutocapitalization="never" /> asks for the email keyboard and
autofill, without capitals.
fileImporter is the browser's file chooser, opened when isPresented
turns true; set it from a button's action, since a browser opens a chooser
only within a tap. onCompletion gets the chosen Files, and a dismissed
chooser calls onCancellation. With 'public.folder' among the types it
is the folder chooser, and the files come named by their paths in the
folder, the folder's name first (Photos/2025/a.jpg). A File is what
the browser holds, not its bytes: a native app's picked files stay on disk
too, read through arrayBuffer() or a slice when asked, so a folder of
large files costs no memory until a file is read, and fileManager.write
copies one on disk rather than through memory:
<Button title="Upload Logo" action={() => setImporting(true)}
fileImporter={{ isPresented: [importing, setImporting], allowedContentTypes: ['image/png', 'image/jpeg', '.svg'],
onCompletion: ([file]) => upload(file) }} />
A native app's picker offers the types as UTTypes: an extension the
system does not know (.fxp) is declared in the app's Info.plist
(swiftbrowser native init --import-type), else the picker offers any file
in its place.
fileExporter is the other way: the document goes where the viewer chooses,
a save dialog where the browser has one (Chromium's File System Access API),
a download elsewhere, and the Files app in a native app. The document is
text, bytes or a Blob, named by defaultFilename (the type's extension
added when it has none); onCompletion gets where it went (saved or
downloaded), and a dismissed dialog calls onCancellation. The Showcase's
Pages exports a document as text and Numbers a sheet as CSV with it.
<VStack fileExporter={{ isPresented: [exporting, setExporting], document: csv, contentType: 'text/csv', defaultFilename: `${title}.csv` }}>
<Button title="Export as CSV" action={() => setExporting(true)} />
</VStack>
Bitmaps and Core Image#
A picture can be drawn through Core Image's filters, as Image(uiImage:) of
a CIImage is. bitmapSource(file) registers a PNG, JPEG, GIF or WebP file
(bytes or a data URL) and reads its size from the header; <Image bitmap={{ source, steps }} /> draws it with the steps applied in order, in Core
Image's space (source pixels, origin at the bottom left): crop,
transform (a quarter turn, a flip), colorControls (saturation,
brightness, contrast), exposureAdjust, vibrance,
highlightShadowAdjust, colorMatrix, photoEffect (Mono, Noir, Chrome,
Fade…), sepiaTone, vignette, gaussianBlur, unsharpMask,
pixellate and the rest of docs/ops-protocol.md, "Steps". The pixels never
pass through JavaScript: the page runs the steps on a canvas at the size the
image is shown, a native app with Core Image itself, so a slider can drive
them as it moves. The image is the size of the recipe's extent
(bitmapExtent) over its scale, and resizable as any image; the root
sends each source once, before the first image that draws it. The
Showcase's Files edits photos this way, keeping the edits beside the file
so Revert gives the original back.
const source = bitmapSource(photo.dataURL);
<Image
bitmap={{ source, steps: [{ op: 'colorControls', saturation: 1.2, brightness: 0.05, contrast: 1.1 }, { op: 'photoEffect', effect: 'chrome' }] }}
resizable
aspectRatio={{ contentMode: 'fit' }}
/>
Pixels the app holds can be a source too: liveBitmapSource(pixels, width, height) registers RGBA memory the app changes in place (a frame a worker or
a WebAssembly module wrote, a simulation's cells), and <Image bitmap={{ source, version }} /> shows it, drawn again each time version rises,
with no image file in between. Over a SharedArrayBuffer the drawing reads
the memory itself; over plain memory each version is copied once to the
drawing worker. The Showcase's Life runs Conway's game this way, scaled up
with interpolation="none" so the cells stay square. A native app has no
live sources yet, so liveBitmapSource answers null there.
Sign in with Apple#
SignInWithAppleButton is SwiftUI's button (label: signIn, signUp or
continue; style: black, white or whiteOutline); onCompletion gets
the credential (user, the stable identifier; email and fullName, shared
the first time only; identityToken and authorizationCode for your server)
or the error (cancelled: … when the viewer dismissed the sheet).
signInWithApple({ scopes, nonce, state }) is the same without the button,
appleCredentialState(user) asks what the credential is now (unknown on a
page), and canSignInWithApple() says whether it works here. Natively the
system sheet answers, in an app with the entitlement (swiftbrowser native init --sign-in-with-apple). On a page Apple's JS does, once the app named
the Services ID and return URL it registered with Apple for the domain:
configureSignInWithApple({ clientId: 'com.example.app.web', redirectURI: 'https://example.com/app/' });
<SignInWithAppleButton onCompletion={({ credential, error }) => credential && signedIn(credential)} padding={16} />
Gestures#
onTapGesture, dragGesture, magnifyGesture, rotateGesture and
onLongPressGesture are the gestures as modifiers, and they compose as
SwiftUI's do: the innermost gesture whose motion matches wins, so a draggable
item inside a tappable canvas keeps its drag. simultaneousGesture={{ dragGesture: { … } }} runs a gesture beside the others instead (it begins
when its own minimumDistance is met and ends when the pointer lifts,
whoever owns the pointer), and highPriorityGesture={{ … }} asks one before
the gestures of the views inside it; both take the gesture as the modifier
it would otherwise be. A drag's location and startLocation are in the
view's own space unless the gesture names another: coordinateSpace: 'global', or { named: 'canvas' } for a space an ancestor set with
coordinateSpace="canvas", which is what moves an item under the finger
without the item's own space moving along. onTapGesture={{ count: 2, action }} is a double tap; with a single tap on the same view (in modifiers, so
the double tap is inside), the single tap waits for the double-tap interval
to pass, as on iOS. contentShape="rectangle" makes the whole frame take
taps and gestures, which, as in SwiftUI, only what a view draws does
otherwise: a 44 pt box around a 14 pt handle, a clear slide. onTouches={(touches, phase) => …} is a SwiftBrowser
addition for chords and glissandi: every pointer down on the view, in its
coordinates, with began, changed, ended or cancelled; the view owns
its pointers, so nothing above it scrolls or swipes with them.
Mouse, keyboard and effects#
A web app may have a mouse and a keyboard, so the modifiers SwiftUI keeps
for iPad and Mac work here: onHover (a mouse entering and leaving the
view's frame), onContinuousHover (where the mouse is as it moves over
the view, { kind: 'active', location } once per frame, then
{ kind: 'ended' }; { coordinateSpace: 'global' | { named }, action }
for a location in another space, as dragGesture takes), help (a tooltip), pointerStyle (link, text,
grabIdle… or any CSS cursor), keyboardShortcut on a Button (⌘ is
Ctrl off Apple platforms) and onKeyPress (keys pressed while no text field
has the focus). symbolEffect draws SF Symbols' effects (bounce, pulse,
variableColor, rotate, wiggle, breathe, scale, appear), running
while active or once per change of a value. visualEffect={(effect, proxy) => …} draws effects (offset, scale, rotation, opacity, blur, color
adjustments) from the view's geometry without changing its layout; the
proxy's frame('global') and bounds('scrollView') stay current as the page
scrolls, so a parallax or a fade by position is one closure. matchedGeometryEffect with a
namespace from useNamespace() moves a view into the frame of the one it
replaces in an animated change. contentTransition="numericText" rolls a
text's old value out and the new one in when it changes in an animated pass,
upward or downward as the number grows or shrinks ({ numericText: { countsDown } } fixes the direction); the whole text rolls, not each digit.
opacity and interpolate crossfade. sensoryFeedback vibrates where the
device can.
Undo#
useUndoManager() is @Environment(\.undoManager): the window's manager,
with NSUndoManager's rules. After a change, registerUndo(name, undo)
registers what takes it back; run by undo(), the closure registers its own
inverse the same way, which lands on the redo stack because the manager is
undoing. A new registration drops what could be redone. canUndo,
canRedo, undoActionName and redoActionName re-render the view as they
change, so a toolbar's buttons follow the stack. Registrations in one event
undo as one (groupsByEvent); beginGrouping(name)/endGrouping(), or
group(name, () => …), make several events one step; a registration with a
key joins the group before it when it has the same key, so a run of
keystrokes into one field (key: \text:${id}`) undoes at once, until an undo or a change with another key. removeAllActions(target)forgets what atargetregistered (a document that closed);levelsOfUndo` caps the stack.
const undo = useUndoManager();
const rename = (title: string) => {
const before = doc.title;
undo.registerUndo('Rename', () => rename(before)); // run as an undo, this registers the redo
setDoc({ ...doc, title });
};
<Button title="Undo" action={() => undo.undo()} disabled={!undo.canUndo} />
The stack lives in JavaScript, since its closures do and canUndo must
change in the pass that registered them, and the system is told what it
can do and sends its undo and redo to it: on a page, ⌘Z and ⇧⌘Z (Ctrl-Z,
Ctrl-Shift-Z and Ctrl-Y off Apple platforms) while no text input has the
focus (a focused field keeps the browser's own undo of its text); in a
SwiftBrowser Native app, the window's UndoManager mirrors the stack, so
the shake, the three-finger swipe, a keyboard's ⌘Z and the Edit menu reach
it. UndoManagerContext gives an island a manager of its own.
App storage#
useAppStorage(key, default) is @AppStorage: a value kept under a key
in the app's storage as JSON (localStorage: the browser's on a page, the
device's in a SwiftBrowser Native app), read back at the next launch, and
shared by every view that reads the key, so a write through any of them
re-renders them all. It returns the value and a setter with useState's
shape; the default (a value, or a function making one) stands in while
nothing is stored, and setting undefined removes the key. decode
migrates what an older version saved; onError hears of a write the
storage refused (a page's storage is full), which the app still keeps for
the session; store swaps the storage for anything with localStorage's
shape.
const [settings, setSettings] = useAppStorage('settings', { theme: 'system', size: 1 });
<Picker title="Theme" selection={settings.theme} onChange={(theme) => setSettings({ ...settings, theme })}>…</Picker>
Files#
fileManager is FileManager.default, with URL.documentsDirectory and
its siblings: the app's own files, kept across launches. On a page they
live in the app's IndexedDB database (the same iOS-like home a Swift app
has there: /data/Documents, /data/Library/Application Support,
/data/Library/Caches, and /tmp for the session); in a SwiftBrowser
Native app they are the app's sandbox. Paths are file: URLs, made with
url(directory, path). The calls are Swift's, asynchronous on both sides
since the page's storage is: contents (the whole file, or a range
{ start, end } of it, read without the rest: a Blob slice on a page,
FileHandle natively), text, write (bytes, a Blob or text; the
directory must exist; a Blob or File is kept as it is, so a picked or
dropped file is stored without passing through memory), contentsOfDirectory, createDirectory
(with its parents), fileExists, attributesOfItem (size, the modification
and creation times, the MIME type the extension names), moveItem,
copyItem, removeItem. Failures say what went wrong first: notFound:,
exists:, isDirectory:, notDirectory:, unsupported: (a URL outside
the app's directories, or a page that keeps no files: available).
const recordings = fileManager.url(fileManager.documentsDirectory, 'Recordings');
await fileManager.createDirectory(recordings);
const memo = fileManager.url(recordings, `${id}.m4a`);
await fileManager.write(memo, blob);
<AudioPlayer url={memo} /> // a VideoPlayer, AudioPlayer or Image loads a file: URL itself
A VideoPlayer, AudioPlayer or Image given a file: URL loads the file
(on a page through an object URL of its bytes, which loadURL also
answers; natively the URL as it is). mount's app option names the
database on a page (sb-files:<app>).
iCloudDirectory() is the app's folder in iCloud Drive, where the native
app has the iCloud entitlement (swiftbrowser native init --icloud) and the
viewer iCloud Drive: files there follow the viewer to their other devices
and show in the Files app, a file another device wrote is downloaded when
read, and watch(listener) reports the URLs that changed (what this app
wrote too, so two readers of a file agree). It is null on a page and in an
app without the entitlement, so an app keeps its documents in
iCloudDirectory() ?? documentsDirectory and is the same code everywhere.
useFileStorage(url, default) keeps a value as a JSON file the way
useAppStorage keeps one under a key, reading it again when it changes:
const [folder, setFolder] = useState<string | null>(null);
useEffect(() => { void fileManager.iCloudDirectory().then((cloud) => setFolder(cloud ?? fileManager.documentsDirectory)); }, []);
const [memos, setMemos, status] = useFileStorage<Memo[]>(folder && fileManager.url(folder, 'memos.json'), []);
The Showcase's Voice Memos keeps its recordings and their index this way, so a memo recorded on one device plays on the next.
Animation#
withAnimation(animation, () => …) animates the pass a state change makes,
and the animation modifier a view's changes when a value changes.
withAnimation(animation, body, completion) runs the completion once the
pass has finished animating ({ completionCriteria: 'removed' } before
the body waits for every effect to be gone); a body that renders nothing
runs it at once.
PhaseAnimator moves its content through phases, each change animated;
KeyframeAnimator plays tracks of keyframes (linear, cubic, spring,
move) and renders its content with the values each frame.
Charts#
Chart takes BarMark, LineMark, AreaMark, PointMark and RuleMark
with their values in x and y: categories, numbers or dates. The
component builds the scales and ticks the Swift Charts module builds
(bands, nice numeric domains that include zero, calendar strides), groups
lines and areas by series, colors foregroundStyleBy series from the chart
palette with a legend, puts bars of one x side by side by their
positionBy (.position(by:)), and places annotations. yAxisFormat writes
the numeric axis's labels (.chartYAxis { AxisMarks(format:) }), as in
yAxisFormat={(v) => ${v}}.
Mixing with ordinary React#
Both directions work, and they nest: a react-dom page can hold a SwiftUI
island, and the island can hold ordinary React DOM inside one of its rows.
The island page of the demo (island.html) does exactly that.
A SwiftUI tree inside a react-dom app#
SwiftUIView, shown in Getting started:
a component whose children are a SwiftUI tree, drawn in a box of the page.
React DOM inside a SwiftUI element#
Host puts ordinary React DOM, with its own components, stylesheets and
event handlers, inside a SwiftUI tree. Its children render with react-dom
in a host element the layout engine sizes, so the DOM sits inside list
rows, stacks and screens like any other view:
function Composer() {
const [notes, setNotes] = useState('');
return (
<List>
<Section header="Appearance">
<LabeledContent label="Notes" value={`${notes.length} characters`} />
</Section>
<Section header="Composer" footer="A textarea and a counter, rendered by react-dom inside the list row.">
<Host className="composer">
<textarea value={notes} placeholder="Write something…" onChange={(e) => setNotes(e.target.value)} />
<div className="count">{280 - notes.length}</div>
</Host>
</Section>
<Section header="Map">
<Host sizing="fill" frame={{ height: 160 }}>
<MapView />
</Host>
</Section>
</List>
);
}
Typing in the textarea updates notes in the React component above, the
SwiftUI row shows the count, and the row grows with the text.
- Sizing.
sizing="content"(the default) measures the DOM like text: as wide as the content wants, up to the width the parent proposes, and as tall as it is at that width. Whenever the content changes size (more lines, an image that loaded, a state change), the tree is laid out again around it.sizing="fill"takes the proposal, so aframe(or the parent's size) decides the box and the content fills it;height: 100%in the content reaches the box. - Styling. The content inherits the device's font and text color, and
the iOS tokens are CSS custom properties it can use:
var(--sb-color-secondary),var(--sb-color-accent),var(--sb-color-separator), the Dynamic Type sizes, and so on; they follow dark mode.classNameandstyleland on the wrapper the children render in. - Events. The DOM handles its own events. Pointer downs inside a host never start the renderer's gestures (no swipe, no drag), so text selection, scrolling inside the host and native controls work; the row around it still swipes when the pan starts outside the host.
- Hooks. The content can use this package's hooks:
useDismiss()from a sheet or a pushed screen,useNavigation()to push,useColorScheme(),useScenePhase().
A host is a React root of its own, so it needs the react-dom peer
dependency, and React context does not cross into it by itself; see below.
It survives StrictMode's simulated unmount and remount, as does
SwiftUIView (island.html?strict in the demos runs under it).
Contexts across roots#
SwiftUIView and Host each start a React root, and React context stops at
a root boundary. This package's own contexts (the environment, navigation,
dismiss, the view environment) are bridged automatically. For the page's
own contexts, name them on the component and they are read on the outer
side and provided again inside:
<SwiftUIView contexts={[ThemeContext, RouterContext]}>…</SwiftUIView>
<Host contexts={[ThemeContext]}>…</Host>
The list must be the same on every render of that component (each entry is read with a hook). Props, callbacks and external stores need no bridging.
Another root's tree, drawn here#
RemoteTree draws a tree that another SwiftUI root produces, wherever that
root runs: a sandboxed script, a worker, another JavaScript runtime, a
server. The other side renders with this package as usual, into a root made
with remote: true, and sends the ops it gets to a RemoteRoot here; the
RemoteRoot keeps a mirror of the elements and RemoteTree draws them as
elements of this tree, so they lay out, scroll and animate with the rest and
work on the web and natively alike. Events the renderer sends them go back
to the other root, synchronously when the other root is in the same thread:
// Here: the host.
const remote = createRemoteRoot();
remote.onEvent((event) => sandbox.dispatch(event)); // taps, text, toggles… for the child's elements
remote.onEnvironment((environment) => sandbox.setEnvironment(environment));
sandbox.onOps((ops) => remote.applyOps(ops)); // the child's render passes
<NavigationStack>
<RemoteTree root={remote} />
</NavigationStack>
// There: the child (the same package, its own React).
const root = createSwiftUIRoot((ops) => send(ops), { remote: true });
root.render(<Counter />);
receive((event) => root.dispatch(event));
The child's top-level views are drawn in place; what it would put on a
screen of its own joins the screen RemoteTree sits in (navigationTitle,
toolbar, searchable, toolbarVisibility), and its sheets and alerts
are presented over the host's root. A pass the child made in withAnimation
animates here too, and the child's completion runs when the host's animation
ends.
A NavigationStack in the child becomes the host's, when RemoteTree sits
in one: the child's root screen is drawn in place, and every screen the
child pushes (NavigationLink, its path) is pushed on the host's stack,
with the child's title, display mode, toolbar and search field on it. The
child's path stays the truth: a push or pop there (dismiss included)
pushes or pops the host's screens, and a pop in the host (the back button,
the swipe, a tap on an earlier screen in the bar) pops the child's path to
the same place. The host's path holds the child's screens as pushed views,
so a bound path sees them; a screen the host pushes over them stays until
the child's stack moves. Outside a host stack the child's stack is drawn as
its own. A pushed value that is plain data (strings, numbers, booleans,
arrays and plain objects) is the screen's route, on its host path value
(PushedScreen.route), so the host can name the child's screens (in a
URL), and <RemoteTree initialPath={routes} /> opens them again: the
child's stack is set to those values once it shows (a setpath event), and
its destinations build the screens, as SwiftUI's NavigationPath of
Codable values is restored. Only the child's first stack is mapped (one in a sheet presents in
the sheet), and not yet: Host elements
(their DOM lives in the child's page, which has none here), and the ops a
loader answers (request, swiftdata, defaults).
A child's NavigationSplitView belongs to the host's two stacks. In a
regular width its detail stack is the one RemoteTree maps, as above, and
its sidebar is the host's own sidebar's to push: useRemoteSidebar(root, path, setPath) keeps the screens of the child's sidebar column (its root,
then what it pushed there) on the bound path of the host's sidebar
NavigationStack, after whatever the host put there itself, so the host's
sidebar drills into the app's with a back button to the host's own, as
iPadOS's Settings and Files drill their sidebars. A back past the child's
root shows the host's sidebar again, and the child's comes back when
options.shown goes true anew or options.generation changes (the app
chosen again); a back out of a screen the child pushed in its sidebar pops
the child's sidebar stack. options.rootBackButtonHidden leaves the child's
sidebar root without a back button (navigationBarBackButtonHidden), for a
host that offers its way out in the detail instead, so the two columns
never each show a back; the hook answers whether the child's sidebar shows
on the host's now, for the host to show that way out while it does. In a compact width the child's split view is a
stack rooted at its sidebar, mapped as any stack, and the hook keeps nothing
on the host's path. The host's sidebar NavigationStack is the split
view's column stack when it is the sidebar prop itself:
const [sidebarPath, setSidebarPath] = useState<readonly unknown[]>([]);
useRemoteSidebar(app?.remote ?? null, sidebarPath, setSidebarPath, { shown: app !== null });
<NavigationSplitView
sidebar={<NavigationStack path={[sidebarPath, setSidebarPath]}><List>{/* the host's own */}</List></NavigationStack>}
detail={<NavigationStack><RemoteTree root={app.remote} /></NavigationStack>}
/>
How it works#
src/host/: a react-reconciler host whose instances are protocol elements. After each React commit,HostTree.flushresolves two virtual kinds (a preference merges props into the enclosingnavscreenorsheet, in tree order, and a view's own preferences come before its content, so the innermost wins; a hoist moves children to the enclosing screen or to the root, as.toolbar,.sheetand.alertdo), diffs the result against the last pass and emits one render pass: creates, updates, inserts (parents before children), removes,commit. Events from the renderer reach the element's handlers and flush synchronously.createSwiftUIRoot(sink)renders a tree into any ops sink;mount(screen, element)pairs a root with aRendererfrom@swiftbrowser/web/src/renderer.withAnimation(() => setCount(1))stamps the pass'scommitwith the animation, aswithAnimation { }does.src/modifiers.tsxapplies the modifier props;src/components/holds the components;src/components/host.tsxandsrc/island.tsxthe two mixing components, over the renderer'shostelement kind and its island layout mode (docs/ops-protocol.md).test/fidelity.test.tsxrendersExamples/Fidelity's tab view through the host and compares the element tree withExamples/Fidelity/__snapshots__/fidelity.jsonl, the ops the Swift app emits for the same screens;test/extras.test.tsxcovers the components beyond the Swift app.
What is covered#
- Layout: stacks,
LazyVStack,LazyHStack,Spacer,Divider,ScrollView(withcontentMargins, scroll edge effects,onScrollGeometryChangeand ascrollPositionby id or point),ScrollViewReader,Group,ForEach(withonDeleteandonMove),Grid,LazyVGrid,LazyHGrid(withpinnedViews),ViewThatFits,FlowStack(SwiftBrowser's own: children in lines, wrapping at the width it is given;spacing,lineSpacing,alignment),GeometryReader(its size, its frame on screen or in acoordinateSpacenamed on an ancestor, the visible bounds of its scroll view, and its safe-area insets; the content first runs once the host has measured the reader, never with a size of zero standing for one not measured yet),onGeometryChange, customLayout(withlayoutValues, priorities, view spacing, explicit alignment guides and a cache),containerRelativeFrame,safeAreaInset. - Content:
Text(withText + Textruns, inline images, italic, underline, strikethrough, tracking, a run's background colour),Image(symbols, catalog images with theassetsoption, remote images andAsyncImage),Labeland its styles,LabeledContent,Link,Coloras a view, shapes (built-in, custom paths,UnevenRoundedRectangle,ContainerRelativeShape) with fills, strokes and gradients,Canvas,TimelineView,VideoPlayer,AudioPlayerandAVQueuePlayer,Gauge,ProgressView, Swift Charts. - Controls:
Button(styles, roles, sizes),Toggle,Picker,Slider,Stepper,TextFieldandSecureField(focus bindings, submit labels),TextEditor,DatePicker,ColorPicker,ShareLink(a URL, text, or a file's bytes with its name),Menu,EditButton,fileImporter. - Containers:
List(selection, edit mode, swipe actions, deletion, reordering, pull to refresh),Form,Section(isExpandedcollapses it in a sidebar-style list, as on iOS),Table,GroupBox,DisclosureGroup(SwiftUI's own natively),ControlGroup,ContentUnavailableView. - Navigation and presentation:
NavigationStack(value and destination links, apathbinding, nested stacks flattened),NavigationSplitView,TabView/Tab, toolbars, search fields, sheets with detents, popovers (as sheets), alerts and dialogs, inspectors. - Interaction:
onTapGesture(withcount),dragGesture(withcoordinateSpace),magnifyGesture,rotateGesture,onLongPressGesture,simultaneousGesture,highPriorityGesture,contentShape,contextMenu,draggableanddropDestination(in the app, and text or files from outside the page),onHover,onContinuousHover,help,pointerStyle,keyboardShortcut,onKeyPress,sensoryFeedback,useUndoManager,useAppStorage,fileManager. - Animation and effects:
withAnimation,animation, transitions,PhaseAnimator,KeyframeAnimator,matchedGeometryEffect,symbolEffect,contentTransition,visualEffect,scrollTransition,redactedplaceholders,textCase,textSelection(text is not selectable otherwise, as on iOS). - Mixing:
HostandSwiftUIView.
Not yet#
contentTransition="numericText"rolls the whole text rather than only the digits that changed, andCanvassymbols always draw above the canvas's other commands.scrollTransitiontakes no thresholds: the effect starts as soon as any of the view is out of the visible area and is complete when all of it is.containerRelativeFramemeasures against the scroll view's whole visible area, content margins included, and itslengthclosure is read as a linear function of the container's length.- The Swift-only bridges (SwiftData, URLSession, notifications, Core ML, StoreKit) have no React counterpart, by design: a web app uses the platform's own.
- The ops protocol is the contract with the renderer and is versioned with it:
this package imports the renderer's sources from
@swiftbrowser/web/src/*.