SwiftBrowser docs
View as MarkdownEdit on GitHub

Render ops protocol#

The Swift core (the SwiftUI shim module) never touches the DOM. It turns a SwiftUI view tree into an element tree and emits a stream of ops that a renderer applies. Two renderers exist:

  • the browser renderer in Web/ (TypeScript, applies ops to the DOM inside an iPhone frame), and
  • headless mode, used by CI under wasmtime, which prints one op per line as JSON Lines so the output can be snapshot-tested.

Element ids are integers assigned by the Swift core and are stable across re-renders for an element that keeps its position and kind. Id 0 is the root container (the device screen) and is never created or removed.

Ops#

Each op is a JSON object with an op field.

op fields meaning
create id, kind, props Create a detached element.
update id, props Replace the element's props entirely.
patch id, set?, unset? Change some of the element's props: each key of set takes its value, each key in unset goes, the rest stay.
insert parent, id, index Insert element id as child index of parent (moving it if already attached).
remove id Detach and destroy the element and its subtree.
commit End of a render pass. Renderers may batch DOM work until this.

Ops within a pass are ordered so that applying them sequentially is always valid: an element is created before it is inserted, and parents exist before children are inserted into them.

patch is sent in place of update only to a host that says it takes it: the native host (opPatches() on its bridge, which run in @swiftbrowser/native reads into the root's patches option). Its keys are the props' top-level ones, so a changed style goes whole; a key whose value became undefined is unset, as JSON writes no such key. An element's update carried every prop at each change: a code editor's whole file text with each highlighting answer, a dozen times a second while scrolling. The web renderer, the raster session and RemoteTree apply a patch too, though the React host sends them update.

Element kinds and props#

kind props children
text text: string none
vstack spacing: number | null, alignment: "leading" | "center" | "trailing" any
hstack spacing: number | null, alignment: "top" | "center" | "bottom" any
spacer minLength: number | null none
button none the label
styled style: Style exactly one

spacing: null means "system default": 8 in an hstack; in a vstack, 8 unless text meets the gap (see "Layout engine semantics").

Any element's props may also carry accessibilityLabel: string, from .accessibilityLabel(_:) or a Label's title around it (the innermost wins), unless the element shows that text itself. The label is on the element that is the accessibility element in SwiftUI: a Text's is on its text (Text's own accessibilityLabel returns Text, so it composes with font, foregroundColor and Text + Text, where each side reads its label or its string), not on the styled boxes its font and color make; and the styled, gesture, touches and tapgesture boxes that modifiers such as .padding(), .frame and .contentShape put around one view pass a label on to that view's element, so Button { … }.buttonStyle(.plain) .contentShape(Rectangle()).accessibilityLabel("Next page") names the button. A button, navlink or menu whose content shows no text carries its content's label too (a menu's content is its label), so an icon-only Label names the control itself, not only the icon inside it; a label set on the control replaces it. The renderer makes the prop the element's aria-label.

Style#

Every field is optional. A styled element applies the style to the box around its single child. Nested styled elements preserve SwiftUI modifier order (.padding().background(...) is a styled{background} wrapping a styled{padding} wrapping the content).

{
  "padding":      { "top": 16, "leading": 16, "bottom": 16, "trailing": 16 },
  "font":         { "size": 17, "weight": "ultraLight" | "thin" | "light" | "regular" | "medium" | "semibold" | "bold" | "heavy" | "black", "design": "default" | "serif" | "rounded" | "monospaced", "monospacedDigit": true, "name": "Literata", "italic": true },
                  // every font field is optional: {"weight":"bold"} changes only the weight; `name` and `italic`: "Custom fonts"
  "foreground":   Color,
  "background":   Color,
  "frame":        { "width": 200, "height": 44, "minWidth": 0, "maxWidth": "infinity", "minHeight": 0, "maxHeight": "infinity", "alignment": "center" },
                  // every frame field is optional; a max/min value is a number or the string "infinity";
                  // alignment is center | leading | trailing | top | bottom | topLeading | topTrailing | bottomLeading | bottomTrailing
  "cornerRadius": 12,
  "backgroundCornerRadius": 12, // `.background(_:)` in a `.containerShape`: rounds the background only (no clip)
  "opacity":      0.5
}

Color#

Either an explicit sRGB color or a semantic name the renderer resolves for the current color scheme.

{ "r": 0.0, "g": 0.533, "b": 1.0, "a": 1.0 }
{ "name": "primary" | "secondary" | "accent" | "systemBackground" | "secondarySystemBackground" | "clear", "a": 0.5 }

a on a semantic color is an optional opacity multiplier (Color.secondary.opacity(0.5)).

UIKit's semantic colors, through Color(uiColor:), are semantic colors too, by their iOS names, so they follow the color scheme like SwiftUI's: label, secondaryLabel, tertiaryLabel, quaternaryLabel, placeholderText, separator, opaqueSeparator, tertiarySystemBackground, systemGroupedBackground, secondarySystemGroupedBackground, tertiarySystemGroupedBackground, systemFill (and its secondary, tertiary and quaternary levels) and systemGray2 to systemGray6 ({ "name": "systemGroupedBackground" }). UIColor.withAlphaComponent on one becomes a.

The iOS palette colors (red, orange, yellow, green, mint, teal, cyan, blue, indigo, purple, pink, brown, gray) are semantic as well ({ "name": "red" }, var(--sb-color-red)): iOS draws them a little brighter in dark mode. The values are iOS 26's (blue #0088ff / dark #0091ff, which is also the default accent; red #ff383c, orange #ff8d28…; Web/src/styles.css). UIKit's systemRed… are the same colors. black and white are explicit RGB.

Events (renderer → Swift)#

The Wasm module exports these C-ABI functions:

export meaning
sb_event(id: i32) A button element with this id was tapped. Runs the action and a render pass; the resulting ops are appended to the pending buffer.
sb_ops_ptr() -> i32, sb_ops_len() -> i32 Address and byte length of the pending ops buffer in linear memory: a UTF-8 JSON array of ops.
sb_ops_clear() Empty the pending buffer after the renderer has applied it.

The module is a WASI command: the renderer instantiates it with a WASI shim, calls _start (which runs the app's main, mounts the root view and performs the first render pass into the pending buffer), then reads and applies the buffer. After every sb_event call the renderer reads and applies the buffer again.

Headless mode#

When the environment variable SB_HEADLESS=1 is set, the app prints each op as one JSON line to stdout instead of buffering. SB_EVENTS may contain a script of events to replay after the first render, separated by commas or line breaks, e.g. tap:"Add", tap:"Add", tap:5. Each event is echoed as {"op":"event","type":"tap","id":5}, with the id its target resolved to, before its ops. Keys in every JSON object are emitted in sorted order so the output is byte-stable.

Event scripts#

An event's target is an element id or a selector, resolved against what is on screen when the event is replayed. Ids shift whenever an element is added above the target, so scripts that live in the repository (Examples/*/__snapshots__/events.txt, the CI relaunch steps) use selectors:

selector names
"Add" the element showing that text: a text, an image's systemName or name, a screen title, a control's label or placeholder, or an accessibilityLabel (a Label's title is one, so an icon-only toolbar button matches its title, as in XCUITest)
@save the element with .accessibilityIdentifier("save")
[tabview] an element of that kind; with text ([navscreen]"Detail") both must hold
…#2 the second of several matches, in document order

A match resolves to the nearest element at or above it that has a handler and suits the event: a button, navlink, listrow or tapgesture for tap (so tap:"Save" reaches the button around its label), a textfield, searchfield or texteditor for text, a toggle, picker or tabview, stepper, slider, datepicker, gesture (drag, longpress), listrow (delete, move), dropdestination (drop) or geometry for the others. [kind] replaces that list.

Only what is on screen matches: the top sheet or alert when one is presented, else everything except the screens a stack has pushed over and the unselected tabs. A selector that matches nothing, or several elements without #n, prints {"op":"error","message":"tap:\"Edit\" matches 3 elements (button 12, button 40, button 77); pick one with #1…#3"} and the run exits with status 1, so a script never taps the wrong element.

Two events need no target: back taps the visible screen's back button and dismiss the top sheet or alert. select:"Flavor":"Chocolate" and select:[tabview]:"Settings" name the option or tab instead of its index. A value may be quoted (text:"Name":"Smith, Jo"), and a line whose first character is # is a comment:

# Add a todo and open it
text:"New todo":Walk the dog
tap:"Add"
tap:"Walk the dog"
toggle:"Done":true
back

Phase 2 additions#

Everything above still holds. Phase 2 adds element kinds, a JSON event channel from the renderer to Swift, an environment event, and a state snapshot used by hot reload.

New element kinds#

kind props children
zstack alignment: Alignment (same names as frame.alignment) any; later children draw on top
image systemName: string none
divider none none
scrollview axes: "vertical" | "horizontal" | "both" any
list style?, form?: true (a Form: on a Mac the rows are laid out in the columns style, docs/notes/macos.md), formStyle?: "grouped" | "columns" (a Form's .formStyle(_:) other than automatic), minRowHeight? (rows at least this tall: the list's own, over an inherited defaultMinListRowHeight style; 44 on iOS and 24 on a Mac by default) rows, or sections
section header: string | null, footer: string | null, collapsible?: true, expanded?: bool (Section(isExpanded:): a tap on the section toggles it; the rows come whatever the state, and a renderer hides them collapsed in a sidebar-style list, as iOS does) rows
disclosuregroup expanded: bool (DisclosureGroup: a tap on it toggles; the label is the first child, the content the rest, laid out when expanded, as SwiftUI's own natively. Among a list's rows it is an outline, as in SwiftUI: the label a row with the chevron at its trailing edge, each content child a row under it a level further in, a nested group opening the same way) [label, ...content]
textfield text: string, placeholder: string, style: "plain" | "roundedBorder", secure: bool none
toggle isOn: bool, style?: "automatic" | "switch" | "button" (.toggleStyle) the label
navstack none navscreens, bottom to top; only the last is visible
navscreen title: string, subtitle?: string (.navigationSubtitle: under the title in a Mac's unified title bar, after it in a plain one; not drawn on iOS), displayMode: "automatic" | "large" | "inline", depth: number, toolbarRole?: "editor" | …, navigationBarHidden?, bottomBarHidden?, statusBarHidden?: bool ("Bar visibility" below), backButtonHidden?: bool (.navigationBarBackButtonHidden(): a pushed screen draws no back button, its leading items start where the button would be; the pop is the app's to offer), backGestureDisabled?: bool (React's navigationBackGestureDisabled, no SwiftUI equivalent: no swipe back from the screen's leading edge, "Navigation (extended): swipe back") the screen content
navlink none the label

Notes for renderers:

  • image: systemName is an SF Symbol name. Render the closest glyph from an open icon set at the current font size and color (1em), and a visible placeholder for unknown names. The Swift side never sends pixels. (The web renderer draws open-symbols, https://github.com/noya-app/open-symbols, an icon set addressed by SF Symbol names: about 7,400 icons, each one filled path, in Web/symbols/open-symbols.json. A page carries only the icons its sources name: the build searches the app's sources for quoted strings shaped like symbol names, and the SwiftUI shim's for systemName: and systemImage: arguments (Web/plugins/symbols.ts); a name it did not find is fetched from the rest, written beside the page in 64 buckets. A name the set lacks is drawn as the closest one it has, dropping a .badge… suffix and then trailing parts, with filled forms first, so person.crop.circle.badge.questionmark draws as person.crop.circle; a .slash variant never falls back to its base, which would mean the opposite; Apple's product names draw a generic stand-in (iphone → candybarphone, icloud → cloud). A tab bar draws each item's symbol in its filled form when the set has one (house → house.fill), as iOS does. SF Symbols themselves are licensed for Apple platforms only, so they are not used.)
  • list: iOS inset-grouped style. Every direct child that is not a section is one row. Rows get separators and the standard 52pt minimum height (iOS 26). navlink and toggle inside a list render as full-width rows (a navlink row shows a trailing chevron).
  • navstack: push and pop are expressed purely as children being inserted or removed at the end. The renderer animates the slide and draws the navigation bar: the title (large for automatic at depth 0 and for large, inline otherwise; Swift sends a pushed screen's automatic as the mode of the screen below it, as iOS inherits it, so a stack with a large root title shows large titles on what it pushes until a screen says .inline) and, for depth > 0, a back button (iOS 26: a chevron-only glass circle, no previous-screen title). Tapping back sends a tap event with the navscreen's own id; Swift pops to it.
  • navlink: a tap on it (its own id) pushes. Inside a list it is a row. selects: true marks a split view sidebar's link in a List(selection:) (its tap selects its value, and the split shows or pushes the detail): a native renderer lets the row's cell take the touch and select itself, as SwiftUI's split view does, instead of a button inside the row.
  • textfield: when an update carries the same text the field already shows, leave the caret alone.

button props (changed)#

button now carries style: "automatic" | "plain" | "borderless" | "bordered" | "borderedProminent" | "glass" and role: "destructive" | null. bordered is a gray capsule, borderedProminent a filled accent capsule, automatic, borderless and plain are text-only: automatic and borderless (.buttonStyle(.borderless)) in the tint (the accent), plain in the foreground around it (the label color, or its .foregroundStyle), as SwiftUI draws a plain button (SwiftBrowser Native hands each to SwiftUI's own style; it used to draw plain outside a list as .borderless, which tinted Numbers' document cards). A button also carries controlSize: "mini" | "small" | "large" | "extraLarge" when .controlSize (an environment value) is not regular; only bordered buttons change size with it. An EditButton is a button that also carries editMode: "active" | "inactive" (the mode it shows, "Done" / "Edit", and flips on tap), so a native renderer can draw the platform's edit button; the web renderer draws its title.

styled style (added fields)#

field meaning
disabled: bool dims the subtree and blocks input (opacity: 0.4, pointer-events: none)

JSON events (renderer → Swift)#

Taps keep using sb_event(id). Everything else goes through a JSON event:

export meaning
sb_alloc(len: i32) -> i32 Allocate len bytes in linear memory for the renderer to write into. Ownership passes to Swift on the next sb_event_json call.
sb_event_json(ptr: i32, len: i32) Deliver one UTF-8 JSON event written at ptr. Swift frees the buffer, handles the event, renders, and appends ops to the pending buffer (read it as after sb_event).

Event shapes:

{ "type": "tap",         "id": 12 }                       // same as sb_event(12)
{ "type": "text",        "id": 7, "value": "Milk" }       // textfield input
{ "type": "toggle",      "id": 9, "value": true }         // toggle changed
{ "type": "environment", "colorScheme": "dark" }          // device appearance changed

The renderer sends environment once after _start (before applying the first ops is fine) and again whenever the theme toggle changes. Swift re-renders views that read @Environment(\.colorScheme).

In headless mode SB_EVENTS accepts the same events in a compact form: tap:12, text:7:Milk, toggle:9:true, env:dark, where the id may be a selector (tap:"Add", text:"New todo":Milk; see "Event scripts" above). Each is echoed as {"op":"event",...} with the same fields as the JSON event.

Bytes#

Bytes that would otherwise cross as base64 inside the JSON (a fetched body, an image file) pass through linear memory beside it. In the JSON they are {"$bytes": n}, an object with that one key, wherever the base64 string would be; n names a buffer.

export meaning
sb_bytes(ptr: i32, len: i32) -> i32 Renderer → Swift: takes a buffer from sb_alloc holding len bytes for the next sb_event_json, and answers its n. Swift replaces each {"$bytes": n} in that event with the bytes, then drops any the event did not name.
sb_bytes_count() -> i32 Swift → renderer: how many buffers the pending ops name. The renderer calls it before sb_ops_ptr on every read; the first call tells Swift the renderer reads bytes this way, and until then the ops carry base64.
sb_bytes_ptr(n: i32) -> i32, sb_bytes_len(n: i32) -> i32 Where buffer n is. Valid until sb_ops_clear, so the renderer copies them out with the ops.

All four are optional (the CLI's generated manifest exports them): a renderer sends base64 to a module without sb_bytes, and a module's ops name buffers only for a renderer that asked with sb_bytes_count. Headless runs and tests print the same values as base64 strings, so a printed imagedata op reads as before. In Swift a value is _JSON.bytes; it is used for fetch response bodies (value.body) and imagedata sources (data, pixels).

Swift serializes the pending ops when the renderer reads them (sb_ops_ptr, sb_ops_len, sb_bytes_*), once per batch, rather than on every append.

State snapshot (hot reload)#

export meaning
sb_state_ptr() -> i32, sb_state_len() -> i32 A JSON object describing the current @State values that can be restored: { "<path>": value, ... }, where path identifies a mounted view by its position and type, and value is a number, string or bool. Only such values are included.

To restore, the renderer passes the same JSON in the WASI environment variable SB_STATE when instantiating the next build of the module. The runtime applies the values when it first mounts a view whose path matches and whose state type matches; everything else starts fresh. Mismatches are ignored silently, so a reload across a source change that reshapes the tree simply loses the state that no longer fits.

The dev server (npm run dev) watches Sources/ and Examples/, rebuilds the Wasm module with scripts/build-wasm.sh, and reloads the page. Before reloading, the page stores the snapshot in sessionStorage and feeds it back through SB_STATE on boot. Only the dev server's page does this: a built site (swiftbrowser build) starts every load with fresh state, as an app does at launch.


Phase 3 additions#

Phase 3 moves layout out of CSS flexbox and into a SwiftUI-style layout engine inside the renderer, and adds animation, sheets and Dynamic Type. The Swift side keeps sending the same element tree; the renderer now computes a frame for every element.

Font (changed)#

Text styles are no longer resolved to point sizes by Swift, so the renderer can scale them for Dynamic Type:

{ "textStyle": "largeTitle" | "title" | "title2" | "title3" | "headline" | "subheadline" | "body" | "callout" | "footnote" | "caption" | "caption2",
  "size": 64,                 // fixed size instead of a text style (does not scale)
  "weight": "...", "design": "...",
  "relativeTo": "body" }      // a fixed size that scales like this text style

Every field is optional; size and textStyle are mutually exclusive. headline implies semibold unless weight is given. The renderer resolves a text style for the current dynamicTypeSize with Apple's Dynamic Type table (Large is the default: largeTitle 34, title 28, title2 22, title3 20, headline 17, body 17, callout 16, subheadline 15, footnote 13, caption 12, caption2 11). A line is as tall as SwiftUI makes a Text: SF Pro's ascender plus descender (UIFont.lineHeight, 2444/2048 × the size) rounded up to a third of a point (body 20.33, largeTitle 40.67, title 33.67, footnote 15.67); each further line of a paragraph adds the HIG leading for the size (body 22, subheadline 20, footnote 18; other sizes round(size × 1.2)). An SF Symbol image is a square of that leading. Engine-placed text (.sb-text, section headers and footers) trims its first line to the cap height and starts the capitals 0.2476em down (text-box, where supported), where SF Pro's are, so it lands as on iOS whatever font the page has.

New element kinds#

kind props children
color color: Color none; fills its proposal
shape shape: "rectangle" | "roundedRectangle" | "circle" | "capsule" | "ellipse", cornerRadius: number, fill: Color | null, stroke: { "color": Color, "lineWidth": n, "dash"?: [n] } | null (a dash pattern draws as a CSS dashed border) none; fills its proposal (a circle: the largest square in it), fill: null means the current foreground color
sheet detents: ["medium", "large"] the sheet content

A sheet is always a root-level element (a child of id 0) placed after the app's tree; the Swift side appends it while it is presented and removes it when dismissed. A tap on the sheet's own id is a dismiss request (scrim tap or drag down); Swift then flips the binding and removes the element.

styled style (added fields)#

field meaning
layoutPriority: number stack space distribution priority (default 0)
lineLimit: number | null maximum lines of text in the subtree; extra text is truncated with an ellipsis
multilineTextAlignment: "leading" | "center" | "trailing" line alignment for wrapped text
fixedSize: { "horizontal": bool, "vertical": bool } the child is proposed nil on the fixed axes and takes its ideal size
animation: Animation, animationToken: number .animation(_:value:): whenever animationToken changes in an update, the layout and style changes of this subtree in that commit animate with animation
transition: Transition how this subtree appears and disappears inside an animated commit
textSelection: true .textSelection(.enabled): the text in the box can be selected (false, .disabled, undoes an enclosing true); text is not selectable otherwise, as on iOS. The web renderer sets user-select from it; the native renderer applies SwiftUI's modifier
labelIcon: true the box is a Label's icon: inside a list it takes the tint, while the row's label (a navlink row's too, however it is wrapped) keeps the primary color; an explicit foreground on or around it wins. In a list row the Label's hstack (the marked icon, then the title) lays out in iOS's icon column: the icon centred 12 pt past the row content's leading edge (28 from the card's), the title at 40, whatever the symbol's width, so titles and separators line up across rows and with the edit-mode controls
Animation:  { "type": "default" | "linear" | "easeIn" | "easeOut" | "easeInOut" | "spring",
              "duration": 0.35, "bounce": 0.0, "delay": 0.0 }
Transition: { "kind": "opacity" | "scale" | "slide" | "move" | "identity", "edge": "top" | "leading" | "bottom" | "trailing", "scale": 0.5 }
            // or an array of these, combined

commit (changed)#

A commit may carry a transaction animation from withAnimation:

{ "op": "commit", "animation": { "type": "easeInOut", "duration": 0.35 } }

In an animated commit the renderer animates every frame and style change of the pass, inserted elements transition in and removed elements transition out (keeping a visual copy until the transition ends). Without animation on the commit, only subtrees whose animationToken changed animate.

The chrome the page places from the engine's chrome rects (a section's card, a row's badge and chevron, a bar's titles, a control's parts) moves with the boxes around it: a chrome node that was shown and moves or resizes is reported to the Animator as a frame change (kind chrome, no id) and tweens in the same pass, so a list's cards and counts keep to their rows as a split view's column widens or narrows. A back button that a split view's sidebar toggle pushes further in (its indent, not a rect) eases between its two places the same way.

Environment event (extended)#

{ "type": "environment", "colorScheme": "dark", "dynamicTypeSize": "xLarge" }

dynamicTypeSize is one of xSmall, small, medium, large, xLarge, xxLarge, xxxLarge, accessibility1 … accessibility5. Either field may be omitted. Headless replay: env:dark, env:light, type:xLarge.

Layout engine semantics#

The renderer lays the tree out the way SwiftUI does: a parent proposes a size to each child, the child reports the size it wants, and the parent places it. A proposal has an optional width and height; null means "whatever you want", 0 asks for the minimum and Infinity for the maximum. The root is proposed the screen's safe area and centered in it, except a navstack, tabview, navsplit, inspector or alert, which is proposed the whole screen and insets its own content. Wrapped in a one-child zstack or in styled boxes without a frame, padding, aspectRatio or fixedSize, such a root still gets the whole screen (an app's root modifier often wraps its TabView so, and iOS keeps the bars at the screen's edges). Frames are in screen coordinates; the renderer positions every element absolutely from the computed frame.

kind size for a proposal placement
text measured with the resolved font. Width proposed: wrap greedily at word boundaries to that width (never narrower than the longest word unless lineLimit truncates); unspecified width: one line. Height = the first line's height + the leading per further line. lines aligned by multilineTextAlignment
image a square of the font's line height (symbol glyphs scale with the font)
spacer along its stack's axis: minimum minLength (default 8), maximum the proposal; 0 on the cross axis. Outside a stack it fills both axes.
divider height 1 (0.5 on 2× displays), width = proposal (in an hstack: width 1, height = proposal)
vstack / hstack SwiftUI's stack algorithm: measure each child's minimum and maximum along the axis (proposals 0 and Infinity) to get its flexibility; hand out the remaining space to children in order of highest layoutPriority first, then least flexible first, proposing remaining / childrenLeft to each; infinitely flexible children reserve their minimum until the others are sized, and spacers come last of all, taking what is left (as on iOS, HStack { VStack { … }.frame(maxWidth: .infinity); Spacer() } gives the stack all but the spacer's 8 points); sum the results plus spacing between children; cross size = largest child. Without spacing an hstack's gaps are 8, and a vstack spaces text by its font, as iOS 26 does (measured in the simulator on Examples/Fidelity's spacing screen): between two texts the lower font's leading less its line height, plus a pixel (2 for body and caption); a view above text 0.409em − 1.24 (caption 3.67, body 5.67, largeTitle 12.67); text above a view 0.6em + 1.13 (caption 8.33, body 11.33); 8 between other views. Text at a child's edge is found through modifiers without a frame or padding, decorations (their content), nested vstacks (their first or last child) and hstacks (their largest text). children in order along the axis, cross-aligned by alignment
zstack proposes its size to every child; size = the union of children all children aligned by alignment
styled padding proposes (proposal − insets) to the child; size = child + insets child inset
styled frame fixed width/height are proposed to the child and reported as is. Flexible min/max: the proposal is clamped and proposed; the reported size follows SwiftUI: a minimum raises the child's size (at most the proposal) to at least min, max(min, min(child, proposal)), then a maximum takes the proposal (or the child's size, if larger) up to max, min(max, max(child, proposal)), a nil proposal counting as the child's size. maxWidth: "infinity" therefore fills the proposal, while minWidth alone keeps a narrow child at minWidth (a badge's .frame(minWidth: 25) is 25 wide, not the width it was offered). child aligned by frame.alignment inside the frame
styled other pass-through; font, foreground and text settings change the context the subtree is measured with
button automatic/plain/borderless: the label's size. bordered/borderedProminent: label + padding 6 vertical, 12 horizontal, at least 34 high (controlSize: mini 3/8, 24 high, footnote label; small 4/10, 28 high, subheadline label; large 14/20, 50 high; extraLarge 18/24, 58 high)
toggle width = proposal width (the switch is 63×28 at the trailing edge, the label leads); height = max(label, 28). style: "button": sized as a bordered button (the label, padded), its fill drawn only while on; in a bottom bar its slot is 24 wider than a button's, the pill filling it less 8 and 50 tall, and its capsule 60 tall (the bar's center kept). In a bar any other style but switch is the bar's own toggle: a plain button's slot, its pill (the switch rect) 10 wider than the label each side and 36 tall, filled with the accent while on
textfield width = proposal width; height 34 (roundedBorder) or 22 (plain)
color / shape the proposal (nil axes → 10, like SwiftUI's default for unconstrained shapes); a circle is the largest square in it
scrollview fills its proposal; proposes null to its content along the scroll axes and its own size on the others. Content smaller than the view sits at its origin along the scroll axes and is centered on the others (SwiftBrowser Native sets the alignment anchor of a view scrolling both ways to top leading, SwiftUI centering such content and reporting the centering as a negative offset) content at the scroll offset
list fills its proposal and scrolls. Inset grouped: 18 above the first section, sections inset 16 with 26px corners; rows are proposed the row width minus 16 padding on each side, height = max(content + 2 × 15, 52) (2 × 10 for a toggle or stepper row, 2 × 14.5 for a segmented picker); section headers sentence case in the headline font (17 semibold, secondary color), lifted 8 into the gap above the card and 10 above it; footers footnote, 7.33 below the card; 35.67 between sections (24.67 below a footer)
navstack fills the whole screen (ignores safe areas) the top screen
navscreen the navigation bar occupies the status bar height plus 44 (plus 62 for a large title; iOS 26: plus 10 under an inline title at the top of the screen, the items staying in the 44 row, chrome barRow); the content is proposed the rest. A root list or vertical scrollview (through styled wrappers) scrolls under the bar, as on iOS 26: that view starts at the top of the screen, is proposed the bar (and the large title row) too, and starts its content below them (its rows are where they would be under a fixed bar); it carries a topInset chrome rect (the bar) and its content size includes the inset. A large title scrolls with it: it also carries a largeTitle chrome rect (the title row), and the page moves the title element into it, so the browser scrolls the title with the content. Once content is under the bar the screen gets data-sb-scrolled and the bar blurs it and fades it into the background (iOS 26's scroll edge effect), more strongly the further it has scrolled: --sb-edge-top ramps from 0 to 1 over the first 40px; once the title is under it, data-sb-collapsed shows the inline title. A list or vertical scroll view deeper in the content (in stacks, say) whose top edge touches the bar across the screen runs under it too (not under a large title), with the same topInset (no largeTitle): its frame grows up to the top of the screen, the parent's layout unchanged. Under a bottom toolbar or search field, the screen's list or scroll view runs to the bottom of the screen and carries a bottomInset chrome rect (the part they cover), as under a tab bar; a nested one whose bottom edge touches them, or a tab bar, grows down under them likewise (not one inside a styled that ignores the bottom safe area: that content has no bottom safe area, so a photo viewer's scroll view under a bottom toolbar is not inset by it). While content is under a bottom bar, the screen (else the tab the view fills) gets data-sb-scrolled-bottom and the same effect shows over the content there, behind the bar, its strength (--sb-edge-bottom) ramping down over the last 40px of content still under it
sheet large: screen height − status bar (iOS 26: its top is the safe area's), with 38px top corners; medium: 433 (at most large), floating 8 from the screen sides and 15 above its bottom with 38px corners (chrome floating, as for a height or fraction detent); the content is proposed the sheet size minus the grabber row (a grabber only with more than one detent; without one the content starts 16 down, except in a full cover). A navstack fills the sheet from its top and its screens' bar takes that room above its 44 row (20 with a grabber, else 16), so the bar's items sit where iOS 26 puts them and the stack's background reaches the sheet's edge; a list or scrollview fills the sheet below the grabber row. iPadOS: on a screen 700 or wider, any sheet but a full cover is a form sheet, 540 × 620 (clamped to the safe area less 20 on each side) and centered in the safe area, without a grabber, whatever its detents (chrome form) slides up from the bottom (a form sheet from below the screen); the presenting tree keeps its size and dims 20% behind it (iOS 26)

Device pixel snapping: frames are rounded to whole CSS pixels after placement, consistently (origins floor, sizes round), so adjacent elements never overlap by a fraction.


Phase 4 additions#

Phase 4 adds tabs, pickers, forms, value-based navigation, a host-driven executor so Task, .task and sleeps reach the screen, and GeometryReader.

New element kinds#

kind props children
tabview selected: number (index) tabs
tab title: string, systemImage: string | null, image?: string (a catalog image when the label has no SF Symbol, e.g. a custom symbol; absent otherwise) the tab's content
picker style: "segmented" | "menu", label: string, options: string[], selected: number none
geometry none exactly one
  • tabview fills the screen. The tab bar (iOS 26) is a floating glass capsule (with the glass rim, see the bottom toolbar) 62pt tall, as wide as its tabs (268/3 ≈ 89.3 each plus a 4 inset either side, measured in the 26.2 simulator: two tabs make a 186.7 capsule) and centered, but at most 21 from the screen sides (x 21…372 on a 393 screen, which four tabs fill), 21 above the bottom (8 above the bottom of a tab view that ends higher), with each tab's icon and title (10pt text) in equal slots inset 4 (an image custom symbol masks the item's color, in its .fill variant when the catalog has one); the selected item sits on a glass pill in the accent color, the others are in the label color. Only the selected tab's content is laid out and visible; the others stay in the tree so their state survives. Content is proposed the screen minus the tab bar and the gap under it (84 at the screen bottom). Tapping a bar item sends a select event with the tabview's id and the index.
  • picker with segmented style is an iOS segmented control (a capsule, height 32, width = proposal, equal segments, the selected one raised on a white / dark-gray capsule; in a list row it gets the 13pt row padding, a 58 row; as a leading / trailing bar item it is the glass capsule itself, as on iOS 26: 44 tall, no track, each segment the widest label (15pt regular) plus 42, the selection a 36-tall gray pill inset 4 with no shadow, chrome.bar on the picker marking it); with menu style it is a row with the label at the leading edge and the selected option plus a chevron.up.chevron.down glyph at the trailing edge (height 44 in a list row, 34 elsewhere); tapping it opens a simple menu of the options anchored to the control, and choosing one sends a select event with the picker's id and the index.
  • list props gain style: "plain" | "insetGrouped" | "grouped" | "sidebar". Form is a list with insetGrouped style (iOS's automatic form style on iPhone) and form: true (the Mac idiom lays its rows out in the columns style; the native renderer draws it as the system's Form); grouped draws full-width sections with hairlines instead of inset cards. sidebar (.listStyle(.sidebar), and what .automatic becomes in a NavigationSplitView's sidebar in the regular size class, as on iPadOS) is laid out like insetGrouped with rows at least 44 tall (11 above and below their text) and no chevrons; the page draws its rows on the list's background, without cards or hairlines, so only a selected row's rounded fill shows. In a compact width (an iPhone) it looks like insetGrouped, cards and chevrons included, as iOS draws it; its sections still fold (Section(isExpanded:), above).
  • geometry is transparent for layout (it fills its proposal, like SwiftUI's GeometryReader, and proposes that size to its child, aligned top leading). After every layout pass the renderer sends { "type": "geometry", "id": N, "width": w, "height": h } for each geometry element whose size changed since it last reported (the first time, whatever it is); Swift re-renders the content with the new size (and makes it with the first: "laidout", below). Its props carry reader, the Swift view the size goes to: when Swift keeps the element for another view (a page turned, each page with a Canvas), reader changes and the next pass reports the size again, unchanged or not, since the new view has not heard it. Every other element that reports its size (reportsSize) carries reader too.

Events (added)#

{ "type": "select",   "id": 12, "value": 1 }                 // tab or picker selection
{ "type": "geometry", "id": 7,  "width": 393, "height": 120 }

Headless: select:12:1, geometry:7:393x120, or geometry:7:393x120@16x200 with the origin a reportsFrame element reports ("Pointer, effects, matched geometry and frames on screen").

Executor (added exports)#

Swift concurrency on Wasm needs the host to drive it. The module installs a cooperative executor; jobs created by Task, .task, Task.sleep and ContinuousClock wait until the host calls in:

export meaning
sb_run_jobs(now_ms: f64) -> f64 Sets the executor's clock to now_ms (milliseconds, any monotonic origin), runs every queued job and every timer that is due, renders if state changed (ops land in the pending buffer, read it afterwards), and returns the milliseconds until the next timer, or -1 when none is pending.

The renderer calls sb_run_jobs after _start, after every event it delivers, and then whenever the returned delay elapses (via setTimeout, clamped to at least 4 ms). It reads and applies the pending ops after each call.

Applying ops lays them out, and the layout's events (geometry, laidout) call sb_run_jobs again from inside that call. Those nested calls pass the time of the outermost one: they run what the events queued, but no timer that came due while the pass was drawn. The timers due since run from the next setTimeout, after the browser has had its turn to paint. (Otherwise a pass slower than an app's timer, a game's tick, ran the next tick inside it, and so on, and the page never painted.)

Frames#

{ "op": "request", "id": 7, "kind": "frame", "params": {} }   // Swift → page
{ "type": "response", "id": 7, "value": { "ms": 12345.6 } }   // on the page's next animation frame

An .animation TimelineView updates once per frame the page draws, as on iOS: it asks for the next frame with a frame request, and the page answers in its next requestAnimationFrame callback (every request before it shares the one answer; ms is the frame's timestamp). The update the answer causes is drawn in that frame. Swift keeps one frame request out for every timeline at once. minimumInterval skips frames until that long has passed. A page that answers frame says so at launch with SB_FRAMES=1; elsewhere (headless runs, hosts without it) the timeline sleeps between ticks, by default 1/20 s. A hidden page draws no frames, and the timelines wait.

Headless mode drives the same executor with a virtual clock: after replaying SB_EVENTS, if SB_RUN_MS is set the runtime repeatedly runs jobs and jumps the clock to the next timer until no timer remains or the clock passes SB_RUN_MS, printing ops as usual. This makes timer-driven apps deterministic in snapshots. Within SB_EVENTS, wait:500 does the same for 500 ms of virtual time before the next event, as the page runs the work an event queues (a DispatchQueue.main.async, a host request's answer) before the viewer's next tap.


Phase 5 additions#

Phase 5 adds Xcode asset catalogs: images and colors a SwiftUI app refers to by name (Image("dough/plain-full"), Color("dough/plain-bg")), plus .aspectRatio / .scaledToFit() / .scaledToFill(). The Swift side keeps sending names only; the web side turns every *.xcassets under Examples/<App>/ into a manifest the page loads before the app.

Asset catalog manifest#

Web/plugins/asset-catalogs.ts serves /catalog/<App>.json (dev server and build) and the image files at /catalog/<App>/<name>.<ext>, where name has every / of a namespace replaced by __ (dough__plain-full.png). The page fetches the manifest before loading the Wasm module; a 404 or a broken manifest means "no catalog" and never an error.

interface AssetCatalog {
  images: Record<string, { src: string; width: number; height: number; scale: number; kind: 'image' | 'symbol' }>;
  colors: Record<string, { light: string; dark?: string }>;
  bytes?: AssetBytes; // what Swift reads: see "Asset catalog files for Swift"
}
  • Keys are catalog names. A folder whose Contents.json has "properties": { "provides-namespace": true } prefixes its contents with <folder>/ (nested folders chain); other folders add nothing.
  • *.imageset: the 2x entry of the light (any) appearance is published when present, else 1x, else 3x, else the first entry with a file (no scale → 1). width/height are points (pixels ÷ scale); PNG, JPEG and SVG are measured, other formats are skipped with a warning. kind: "image". A PDF (vector artwork) is published as the PNG pdf.js renders it to at 3× (scale: 3), its size in points read from the page's MediaBox; see "Backyard Birds".
  • *.symbolset: the SVG is published as kind: "symbol" (a template image; size irrelevant).
  • *.colorset: light is the entry without appearances, dark the one with luminosity: dark; idiom and contrast variants are ignored. Components may be hex ("0xC2"), floats ("0.439") or 0…255 integers ("255"); the values are CSS rgba(r, g, b, a) strings.

Asset catalog files for Swift#

On iOS UIImage(named:) and NSDataAsset(name:) read their bytes from the compiled catalog, the bundle's Assets.car. The manifest's bytes lists what Swift needs for the same:

interface AssetBytes {
  images: Record<string, {
    light: { src?: string; width: number; height: number; scale: number };
    dark?: { src?: string; width: number; height: number; scale: number };
    kind: 'image' | 'symbol';
  }>;
  data: Record<string, { src: string; type?: string }>;
}
  • An image set gives, for the light (any; a luminosity: light entry when there is one) appearance and the dark one when the set has it, the entry iOS loads on the iPhone the page stands for: the 3x one, else the nearest larger scale, else the nearest smaller, then a single-scale entry; an iphone entry before a universal one, other idioms only when there is nothing else; high-contrast entries never. width/height are points and scale the file's. A file the page already shows (images[name].src) is listed as it is; another is published as /catalog/<App>/<name>.<scale>x.<ext> (<name>.dark-<scale>x.<ext> for the dark one). A PDF gives the PNG it renders to (scale: 3). An SVG and a symbol have no src: only the page draws them.
  • *.dataset: the iphone or universal entry's file, published as /catalog/<App>/<name>.data, and its universal-type-identifier.

Before starting the module the page fetches every listed file, in parallel with the resources ("Resource bundle") and while the module compiles, and mounts them in the /bundle mount's Assets.car folder, each under the last part of its URL, with Assets.car/catalog.json: AssetBytes with file (a name in that folder) in place of src. A file that does not load leaves its image without file (named, sized, no bytes) and its data set out. The shim's _AssetCatalog (Sources/SwiftUI/Runtime/AssetCatalog.swift) reads the index once:

  • UIImage(named:) of a set has the listed size and scale and reads the file when its bytes are first wanted (pngData(), jpegData, cgImage, draw(in:), Core Image, the pasteboard); Image(uiImage:) still sends the name, except for a dark image, drawn from its file. The appearance is the page's color scheme. A name the catalog lacks finds a loose image file in the bundle (name@3x.png, name@2x.png, name.png, or the name with its extension), else is nil. Without Assets.car/catalog.json (headless runs, tests) UIImage(named:) is never nil and names the image as before.
  • NSDataAsset(name:) gives the data set's bytes and type identifier (public.data without one).

The cost is at launch: an app's catalog files are fetched before it starts (each image set's light and dark file, not all its scales). They come from the same URLs as the page's <img>s, so a host's caching can serve those again.

image props (changed)#

image props are now one of two forms:

{ "systemName": "checkmark.circle.fill" }        // an SF Symbol, as before
{ "name": "dough/plain-full", "resizable": false } // an asset catalog image
catalog entry size for a proposal rendering
kind: "image", resizable: false always the intrinsic point size <img src alt="" draggable="false"> filling the frame (object-fit: fill; fitting is aspectRatio's job)
kind: "image", resizable: true width: proposal.width ?? intrinsic, height: proposal.height ?? intrinsic (fills what is proposed, like SwiftUI; Infinity passes through so it is maximally flexible in stacks) same
kind: "symbol" a square of the font's line height, like an SF Symbol a span with mask-image: url(src) filled with currentColor (tints like a symbol)
not in the manifest 44×44 the dashed placeholder unknown symbols get, with the name in title

styled style (added field)#

field meaning
aspectRatio: { "ratio": number | null, "contentMode": "fit" | "fill" } .aspectRatio(_:contentMode:); .scaledToFit() is { ratio: null, contentMode: "fit" }, .scaledToFill() the fill form

Layout: let the child's proposal (after the frame, padding and fixedSize steps of the same styled, which nest as frame > padding > fixedSize > aspectRatio > child) be (pw, ph), where either may be nil or infinite. When ratio is null the child is measured with a nil proposal and its ideal width ÷ height is the ratio (1 when degenerate). Then:

  • both finite: fit → the largest size with that ratio inside (pw, ph); fill → the smallest size with that ratio covering it;
  • one finite: the other axis is derived from the ratio;
  • both infinite: Infinity × Infinity (a flexible child fills an unbounded box, so a custom layout probing the maximum sees it as flexible);
  • neither otherwise: the child's ideal size.

That size is proposed to the child and the child's reported size is what the styled box reports, for fill too (clipping is a visual concern: SwiftUI needs .clipped() as well). The child is centered (or aligned by frame.alignment when the same box has a frame).

Color (added form)#

{ "named": "dough/plain-bg", "opacity": 1.0 }

A .colorset of the catalog, resolved for the current color scheme. opacity (0…1) multiplies the catalog alpha. The renderer declares every catalog color as a --sb-asset-color-<slug> custom property under .device[data-theme="light"] and .device[data-theme="dark"] (the slug is the name with / → __ and anything but [A-Za-z0-9_-] → _; a colorset without a dark variant keeps its light value) and renders a named color as var(--sb-asset-color-<slug>, magenta), wrapped in color-mix(... , transparent) when opacity < 1. A name the catalog lacks therefore shows up magenta.

Transition addition#

transition parts gain { "kind": "offset", "x": number, "y": number } (AnyTransition.offset(x:y:)): the view enters from, and exits to, that translation in points. Combines with the other parts like move.


Phase 6 additions#

Phase 6 runs the app-level screens of Apple's Food Truck sample: custom Layouts evaluated on the Swift side with host-measured subviews, Grid, LazyVGrid, Gauge, overlays and backgrounds with views, menus, toolbars, search fields, badges and row insets, shape styles (hierarchical levels, gradients, materials) and visual effects. The three sub-sections were written with their implementations.

Phase 6: layout containers#

Phase 6 adds SwiftUI's Grid, LazyVGrid, Gauge, .overlay { } / .background { } with a view, .position(x:y:), .tint and the Layout protocol: a custom layout is the app's rule, which the host calls as it lays the element out, with subviews it measures. Everything in docs/ops-protocol.md still holds; the renderer lays these kinds out like the others (propose / report / place) and positions every child absolutely from its frame.

New element kinds#

kind props children
layout serial: number (changes when the app's rule, or what it reads, does) the subviews, in order
grid horizontalSpacing: number | null, verticalSpacing: number | null, alignment: Alignment gridrows, or any other element (one full-span cell)
gridrow alignment: "top" | "center" | "bottom" | "firstTextBaseline" | "lastTextBaseline" | null the cells
lazyvgrid columns: GridItem[], spacing: number | null, alignment: Alignment the cells (already flattened)
lazyhgrid rows: GridItem[], spacing: number | null, alignment: Alignment the cells (already flattened)
gauge value: number (0…1), style: "automatic" | "linearCapacity" | "accessoryLinear" | "accessoryCircular" | "accessoryCircularCapacity" | "progress", hasLabel: bool, hasCurrentValueLabel: bool the label (when hasLabel), then the current value label (when hasCurrentValueLabel)
decorated role: "overlay" | "background", alignment: Alignment exactly [content, decoration]

Alignment is the frame.alignment set (center, leading, trailing, top, bottom, topLeading, topTrailing, bottomLeading, bottomTrailing). spacing: null means the system default, 8.

Proposal: { "width": 393 | "infinity" | null, "height": 759 | "infinity" | null }
          // null is a nil axis ("whatever you want"), "infinity" the maximum

GridItem: { "size": { "kind": "fixed", "value": 80 }
                  | { "kind": "flexible", "minimum": 10, "maximum": "infinity" }
                  | { "kind": "adaptive", "minimum": 100, "maximum": "infinity" },
            "spacing": 8 | null,          // to the next column (default 8)
            "alignment": Alignment | null } // for the cells of this column (default: the grid's)

The renderer gives each a div with the kind class (sb-layout, sb-grid, sb-gridrow, sb-lazyvgrid, sb-lazyhgrid, sb-gauge, sb-decorated). The gauge owns two chrome nodes, .sb-gauge-track and .sb-gauge-fill, positioned from its own box; they carry no data-sb-id.

styled style (added fields)#

field meaning
gridCellColumns: number .gridCellColumns(_:): the cell spans this many grid columns (default 1). The styled is the direct child of the gridrow.
gridCellAnchor: { "x": 0…1, "y": 0…1 } .gridCellAnchor(_:): unit point the cell is aligned by inside its cell box (default: the row's vertical and the grid's horizontal alignment)
gridCellUnsizedAxes: boolean .gridCellUnsizedAxes(_:) with .horizontal: a full-span cell does not widen the grid
gridColumnAlignment: "leading" | "center" | "trailing" .gridColumnAlignment(_:): the horizontal alignment of every cell in this cell's column (the first such cell in the column wins; a cell's gridCellAnchor still takes precedence)
tint: Color .tint(_:) (same JSON forms as foreground): sets the CSS variable --sb-tint on the box; gauge fills, switched-on toggles and borderedProminent / plain button colors below read var(--sb-tint, …)
position: { "x": number, "y": number } .position(x:y:): the box takes the whole proposal (the child's ideal size on nil axes) and places the child's center at (x, y) inside it; the child is measured with a nil proposal

Layout rules#

layout (custom Layout)#

A custom layout is answered in the host's layout pass: the host calls the app's rule as it lays the element out, and measures the subviews itself at whatever the rule proposes them. Nothing is reported for it and no render follows for it.

  • The rule is the app's, by element id: its size for a proposal (sizeThatFits), where it puts each subview once placed (placeSubviews: each subview's top leading corner in the layout's bounds and what it proposes it, or nothing for one it does not place, which then sits in the middle proposed the layout's size, as in SwiftUI), and its explicit guides (explicitAlignment, where a stack or frame aligns it by one). Each call carries the proposal, the pass's container (containerRelativeFrame's: the screen, or the viewport of the scroll view the element is in) and the number of subviews; a subview's size for a proposal is the host's own measure of it (LayoutSubview.sizeThatFits), its min, ideal and max its measures at a zero, unspecified and infinite proposal.
  • Kept as a plan. The host keeps the rule's answers by proposal and container, as it keeps any element's plans, until a subview changes (the element's plans and its ancestors' go, as for any child) or the element's serial does (the rule, or what it reads, changed: its plans and its ancestors' go, its subviews placed again only where what the rule proposes them changes). So a rule must be a pure function of what it is asked, its subviews' sizes and what its serial covers. In @swiftbrowser/react the serial follows the layout object and the inputs it declares; in a development build each call is made twice and the answers compared, and a state set while a rule runs is said (it would be another commit and another pass, every pass).
  • Each host's way to the rule. The web renderer and the in-memory one call a React app's root (layoutRules; @swiftbrowser/native's run sets __sbLayoutRules for a host in the app's realm), and a Swift app's module through sb_layout (below). The native views call the app's JavaScript from SwiftUI's own sizeThatFits and placeSubviews through the engine (__sbLayout(method, id, request), JSON, with a native measureSubview(index, width, height) bound for the call, which measures with SwiftUI's LayoutSubview.sizeThatFits), the container measured by a last, hidden subview in a containerRelativeFrame; a pass the app sends while the call is on the stack is held and applied once SwiftUI's layout is over.
  • Without a rule (a host that hands the pass none), the element stands as a zstack: the proposal, its children's union at their ideal sizes on an unspecified axis, each child in the middle proposed its size.

A Swift app's module answers sb_layout(ptr, len) -> len (the answer at sb_layout_ptr()), a JSON request written into a buffer from sb_alloc:

{ "id": 12, "method": "size" | "place" | "guide",
  "proposal": [393, null],                 // an axis: points, null (unspecified) or "infinity"
  "subviews": 3,
  "bounds": [393, 120],                    // place, guide: the size it was given
  "guide": "leading",                      // guide: leading, horizontalCenter, trailing, top, verticalCenter, bottom
  "measures": [[0, 393, null, 393, 44.5]] } // what the page measured: [index, width, height, measured width, height]

and answers {"size": [w, h]}, {"places": [[x, y, w, h] | null, ...]} (each subview's top leading corner and the proposal it was given) or {"guide": v | null}; where its run asked for a subview's size the request did not carry, it answers {"missed": [[index, w, h], ...]} instead, and the page measures those and asks again (a layout is a pure function of what it is asked and its subviews' sizes, so the run that misses nothing is the answer). The module keys the measures to a millionth of a point. Rendering nothing, the call may still schedule a render (the shim's off-screen measuring of views for UIHostingController.sizeThatFits(in:), a representable laid out at its size), which the page runs with the jobs after its pass.

grid / gridrow#

  • Each gridrow child is a row whose children are the cells; any other child of the grid is a row with one cell spanning every column. A cell's span is its gridCellColumns (read through its styled wrappers), default 1.
  • Column count = the maximum over rows of Σ spans (at least 1).
  • A column is flexible when it has no non-spanning cells or all of its non-spanning cells are flexible, i.e. report a width ≥ the proposal width when proposed { width: proposal width (Infinity when nil), height: null }. Other columns are fixed at the largest ideal width (nil proposal) of their non-spanning cells.
  • With a finite proposal width the flexible columns share, equally and at least 0, what is left after the fixed columns and horizontalSpacing × (columns − 1). Without one they take their cells' largest ideal width.
  • A full-span cell (a non-gridrow child) is measured with { width: proposal width, height: null }; when it is wider than the columns (a divider takes the whole proposal) every column grows by the same share of the difference, so the grid is that wide. A full-span cell with gridCellUnsizedAxes: true (.gridCellUnsizedAxes(.horizontal)) is left out of this and just takes the grid width.
  • A cell's box width = the widths of its spanned columns + horizontalSpacing between them; a full-span cell gets the whole grid width. Row height = max over the row's cells of measure(cell, { width: cell width, height: null }).height.
  • Grid size = (Σ column widths + spacing, Σ row heights + spacing). The grid does not fill a proposal that has no flexible column (unless a full-span cell widens it).
  • Placement: rows top to bottom, cells left to right; each cell is aligned in its box by gridCellAnchor, else horizontally by its column's gridColumnAlignment or the grid alignment, and vertically by the row alignment (top / firstTextBaseline → 0, center → 0.5, bottom / lastTextBaseline → 1; null → the grid alignment's vertical anchor). Every gridrow gets a frame (the grid width × its row height).

lazyvgrid#

Columns are resolved for the proposal width W:

  • fixed → value.
  • With W finite: R = W − Σ fixed − Σ gaps, where the gap after item i is that item's spacing (default 8) and there is one gap between consecutive items. Flexible and adaptive items share R equally; flexible → that share clamped to [minimum, maximum]; the width left after the flexible items, W', is split equally between the adaptive items, each of which becomes n = max(1, floor((W' + s) / (minimum + s))) columns of (W' − (n − 1)·s) / n capped at maximum (the minimum only counts the columns: one column of a minimum wider than W' is W' wide), s being the item's spacing (also used between its columns).
  • With W nil: flexible and adaptive → one column of the cells' largest ideal width clamped to [minimum, maximum].
  • An empty columns list is one flexible column (minimum 10).

Cells fill rows left to right, one per resolved column; row height = max cell height measured with (column width, null). Size = (W, or the columns plus gaps when W is nil; Σ row heights + spacing (default 8) between rows). When the columns are narrower than W they are offset inside it by the grid alignment's horizontal anchor. Each cell is placed proposing its box (column width × row height), so a cell that grows with its height (a VStack with a Spacer) fills its row, and aligned in the box by the column item's alignment, else the grid's. All cells render; nothing is lazy.

lazyhgrid#

The same along the other axis: the rows are resolved for the proposal height H as lazyvgrid resolves its columns for W (with H nil a flexible or adaptive row is the cells' largest ideal height), and the cells fill columns top to bottom, one per resolved row. A column is as wide as its widest cell measured with (null, row height); columns are spacing (default 8) apart. Size = (Σ column widths + gaps; H, or the rows plus gaps when H is nil). Rows shorter than H together are offset inside it by the grid alignment's vertical anchor, and each cell is placed proposing its box (column width × row height) and aligned in it by the row item's alignment, else the grid's.

gauge#

  • Width = the proposal width (100 when nil); height = 4 + (label row + 4 when there is a label or a current value label). The label row is the taller of the two labels measured in the caption text style with the gauge width.
  • The label is placed leading and the current value label trailing on the same row (centered vertically in it); the bar (chrome track, 4px, rounded, var(--sb-color-fill)) is below them, and chrome fill is the leading value share of the track, colored var(--sb-tint, var(--sb-color-accent)). value is clamped to 0…1.
  • Circular styles (accessoryCircular, accessoryCircularCapacity) are a 58-point square whatever the proposal, with chrome ring (an SVG, about a 6-point stroke) instead of the bar: a capacity gauge fills a full track clockwise from 12 o'clock, an accessoryCircular gauge an arc of 270° open at the bottom, from its bottom-left end. The value is the tint, else the primary color, and the track the same at 35%. The current value label, else the label, is centered in the ring, proposed 40.67 × 29 in a 24pt semibold font (iOS 26: Backyard Birds' water drop is a 24pt symbol there). An accessoryCircular gauge with both labels shows the label too, proposed 36 × 17.67 in the gap at the bottom of its arc; a capacity gauge shows only the one in the middle.
  • progress is a determinate ProgressView: the label in the context font (not the caption) above the bar, 8 apart, and the current value label (caption, secondary color) 6 below the bar; height = (label + 8) + 4 (+ 6
    • value label), each part only when present. An indeterminate ProgressView is no gauge but Image(systemName: "progress.indicator") at 20pt (.font(.system(size: 20))): iOS's activity indicator, eight rounded spokes in the secondary color (or the view's tint), the leading one full strength and the three behind it fading; the page steps that fade clockwise around the still spokes, once a second (its label, secondary, 8 under it).
  • The element has role="meter" with aria-valuenow, and data-sb-style.

decorated#

Size = the content measured with the proposal. The decoration is proposed the content's size, aligned inside it by alignment and placed with that proposal; it never affects the size. For overlay the decoration (the later child) draws above the content; for background the content is raised (z-index: 1, the box is an isolated stacking context) so the decoration draws below it.

position#

In the styled nesting (frame > padding > fixedSize > aspectRatio > child) the positioned box replaces the child step: it reports the proposal it is handed (the child's ideal size on nil or infinite axes) and places the child, measured with a nil proposal, with its center at (x, y) inside that box.

Events (added)#

{ "type": "batch", "events": [ { "type": "geometry", ... }, { "type": "scrollgeometry", ... } ] }

When a layout pass produces more than one geometry / scrollgeometry event the renderer sends them as one batch: Swift applies every event in it and renders once, instead of once per element. A batch is never nested. sb_run_jobs runs once after the batch as after any event.

{ "type": "laidout" }
{ "type": "batch", "events": [ { "type": "geometry", ... }, { "type": "laidout" } ] }

Once a host has laid out every commit it was sent so far and sent what that layout reported (its geometry and scrollgeometry events), it sends laidout: last in the pass's batch, or alone when the pass reported nothing. Commits laid out together get one, and a host whose layout of a commit ends after a newer commit arrived leaves laidout to the newer one's (the native views, whose update and the app's next pass can interleave). A host reports a size only when it changed, so a laidout with no report since the last one says the layout moved nothing the app reads: it has settled, and an app that measures itself in rounds knows it is done (@swiftbrowser/react useLayoutSettled). So does a laidout whose reports the app answered with no render to commit (sizes it already had): no other layout is coming to say so.

The Swift core holds a pass's .onAppear actions for it when the pass made a geometry element (or one with reportsSize): on laidout it renders the sizes reported before it in the batch, then runs those actions. On iOS a GeometryReader has its size when its content first runs and onAppear runs after layout, so withAnimation there animates a distance taken from the size; run before the size came, it animated nothing (an unmeasured reader's distance is often zero), and the size moved the view in one step. The page says it sends laidout with the launch variable SB_LAIDOUT=1, so the first pass is held too; a host that sends one is counted from then on, and one that never does runs onAppear right after the pass, as before.

For the same hosts a reader's content waits for the reader's size too: the pass that makes a GeometryReader creates its geometry element empty (it fills its proposal whatever is inside), and the content is made in the pass that renders the first geometry event for it, with that size, a size of zero included when that is what the host measured. The content is never run with the zero of a reader not measured yet: what it did once with that size stayed (a scroll view's opening position worked out among pages of no width, a value kept in @State). onGeometryChange likewise runs no action before its view's first report. A host that never lays out (a headless run) has no size to give: there the content is made at once, at zero size, and the one-value onGeometryChange runs with the value zero makes. @swiftbrowser/react's GeometryReader does the same for every host (each of its hosts lays out): its content first runs when the first geometry event came.

The native views send laidout only while the app listens for it: their marker is an update of the root view on every commit, which in a code editor scrolling (a highlighting pass every 80 ms) dropped frames for an event nothing heard. run (@swiftbrowser/native) tells the host it listens for none as it starts (wantsLaidOut(false)), and the tree asks while it has a listener (HostTree.onLaidOut, useLayoutSettled; the root option onLaidOutWanted). Asking counts as a commit, so the next update ends with laidout whether or not a commit comes, and the first one after it counts only the reports since the ask. A bundle from before the call (which never says) hears them on every commit, as before. The web renderer and the raster session send them always; theirs costs nothing.

Phase 6: menus, toolbars, search, tap gestures and list row hints#

Everything in docs/ops-protocol.md still holds. This document is the renderer-side contract for the Phase 6 chrome features: the exact encodings the Swift side emits and the layout rules the web renderer (Web/) applies.

New element kinds#

kind props children
menu {} [label, ...items]
toolbar placement: "trailing" | "leading" | "principal" | "bottom" | "secondary" | "largeTitle" | "keyboard", sharedBackground?: "hidden" the items (buttons, menus, navlinks, texts, images)
searchfield text: string, placeholder: string (default "Search") none
tapgesture {} exactly one

picker style (added)#

style gains "inline": Picker with .pickerStyle(.inline), or the default style of a Picker inside a Menu.

styled style (added fields)#

field meaning
badge: string | null .badge(_:); only meaningful on a list row (a direct child of a list, or of a section in a list)
listRowInsets: { "top", "leading", "bottom", "trailing" } .listRowInsets(_:); replaces the row's default insets for that row
listRowBackground: ShapeStyle .listRowBackground(_:) with a Color (other views are accepted without effect): the row's cell is painted with it instead of the card's white, and a section card holding such a row leaves its background to its rows, so Color.clear shows the list's background
imageScale: "small" | "medium" | "large" .imageScale(_:); symbol images in the subtree scale by 0.8 / 1 / 1.25

A navscreen had exactly one child, its content. It now has [content, ...extras], where every extra is a toolbar or a searchfield. The renderer partitions the children by kind: the first child that is not an extra is the content (several such children form an implicit VStack, as before).

Events#

Nothing new. tapgesture and the rows of a menu popover send the existing events:

{ "type": "tap",    "id": 12 }              // a tapgesture; a button or navlink item of a menu
{ "type": "select", "id": 9, "value": 1 }   // an inline picker row, or a picker item in a menu popover
{ "type": "text",   "id": 7, "value": "Mi" } // searchfield input, exactly like textfield

Layout and rendering rules#

  • Size: the label's (children[0]) size for the proposal. The items are never laid out in place: they have no frames, are listed in LayoutResult.hidden, and the DOM gives them the hidden attribute (plus a CSS rule hiding every child of .sb-menu but the first), so they never show inline.
  • Control: the element is role="button", aria-haspopup="menu", focusable, drawn in the accent color like a plain button. Enter / Space activate it.
  • Popover: a tap opens the same popover a menu picker opens (250 wide, --sb-color-menu-background: Liquid Glass, 82% over a 40px backdrop blur with the glass rim; 13px radius, scrim-less; a click anywhere outside closes it and is swallowed, Escape closes it), anchored with its trailing edge on the label's trailing edge, 4 below the label when it fits, else 4 above, clamped 8 from the screen edges. The rows are built from the current item children each time it opens, in order:
    • button / navlink → a 44pt row (role="menuitem") showing the subtree's text (all text descendants joined with spaces) and, trailing, its first image with a systemName; a role: "destructive" button is red; a styled { disabled: true } wrapper disables the row. Clicking sends { "type": "tap", "id": <the button/navlink id> } and closes the popover.
    • picker (any style) → one 44pt menuitemradio row per options[i] with a checkmark on selected, as a group separated from its neighbours by an 8pt band. Clicking sends { "type": "select", "id": <picker id>, "value": i } and closes the popover.
    • divider → an 8pt separator band (never doubled).
    • section → its header as a 32pt dim caption, then its children as rows.
    • text → a 44pt static (disabled) caption row.
    • a nested menu → a submenu, as iOS 27 shows one: a 44pt row (58 with a subtitle; role="menuitem", aria-haspopup="menu") with its label's symbol, title (an icon-only label's accessibility title) and subtitle, ending in a chevron.right. Tapping it opens a panel of its own (data-sb-level 1, 2, …) over the menu's, as wide and at its leading edge: a header row (the submenu's symbol, its title in semibold over its subtitle, 60pt with one, and a chevron.down) laid over the row it came from, a hairline, then the nested menu's rows. The panel it came from is pushed back behind it (data-sb-behind: scaled to 0.968 around its top trailing corner, at 60% opacity, its rows inert). The header, or a tap anywhere on the pushed-back panel, closes the submenu and brings that panel forward; a tap outside every panel closes the menu. A submenu panel taller than the screen's room moves up, then scrolls inside. Submenus nest. A nested menu whose label has no title has nothing to tap: its items are flattened in.
    • any other container → its children, in order.
  • The rows sit in a child of the panel (.sb-picker-menu-rows) that scrolls when the popover is taller than its room, so the panel's glass, rim and corners stay put while the rows pass under them.
  • An update or remove of the menu or of anything inside it closes an open popover (the popover reflects what the items were when it opened).

picker style inline#

  • Size: height = (number of options + 1 if label is non-empty) × 44; width = the proposal, or the widest row (label width, or option width + 28 for the checkmark and its gap) when none is given.
  • Rows: the label, when non-empty, is a leading dim (secondary color) caption row; each option is a row with the title leading and an accent checkmark trailing on the selected one (role="radio", aria-checked). Hairlines separate the rows.
  • In a list / form: the picker is one row of its section whose height is options × 44 (no extra vertical padding, like a menu picker row), and its rows span the full list row width with the usual 16pt content inset, so they read as rows of that section. Elsewhere the rows span the control's frame.
  • Tapping a row sends select with its index (the checkmark moves at once; Swift's update confirms or reverts it).

toolbar in a navscreen#

  • Items are measured at their ideal size (a nil proposal) and vertically centered in the 44pt bar row (the row under the status bar, also for a large title). leading and trailing items (iOS 26, measured in the simulator: Examples/Fidelity topbar*) float on 44-tall glass capsules (22pt radius, items in the label color rather than the accent unless tinted). Adjacent toolbars of one placement share a capsule (a run; a ToolbarSpacer of that placement, a toolbar with "spacer" and no children, ends one, and draws nothing itself): every item gets a slot, centered in it, a symbol (an item that is only an image) the 44 circle, anything else max(44, width + 2 × 12); the slots are 12pt apart and the capsule reaches 1pt past the end slots (a lone item's capsule is its slot: a 44 circle for a symbol). principal items are an hstack with 16pt spacing. The toolbar element's own frame spans its items' slots; the items are ordinary elements with ordinary frames, so buttons, menus and navlinks inside work as anywhere else (the bar never swallows their clicks). The capsules are chrome.leadingGlass0 … and chrome.trailingGlass0 … on the screen, drawn like the bottom bar's (below). A toolbar holding a segmented picker is a run of its own whose capsule is the picker's frame, 4pt clear of its neighbours on each side (so 16 to the next capsule); a toolbar with "sharedBackground": "hidden" (.sharedBackgroundVisibility(.hidden)) is a run of its own at its items' widths with no capsule.
  • trailing: the runs end 16pt from the trailing edge, in their order in the content (the last one at the edge), 12pt apart. leading: the first run starts 12pt after the back button (16pt from the leading edge when there is none); the runs are 12pt apart. principal: the group is centered in the row and the inline title is not drawn. largeTitle (iOS 26 .largeTitle): the items take the large title row in place of the title's text, from its 16pt leading margin, each proposed the row's width less the margins and centered in the 62pt row; the page keeps the toolbar in the large title element, so it scrolls with the screen's list or scroll view as the title does, hides the title's text, and shows the inline title once the row has gone under the bar. While the title is inline there is no row, and the toolbar is hidden. bottom (iOS 26, measured in the 26.2 simulator): the items float on Liquid Glass in a 48pt row 28pt above the screen bottom (8pt above a view that ends higher) and 28pt in from the sides. The bottom toolbars' items, in order, share a capsule until a ToolbarSpacer (a toolbar with "spacer", no children) ends one: an icon (narrower than 44) takes a 50pt slot, other items their width and 18pt either side, 6pt between slots, each item centered in its slot; a lone icon is a 48pt circle. Flexible spacers share the room the capsules leave and push them apart (so icon · spacer · status · spacer · icon puts the icons at the edges and the status in the middle); with none the row is centered; fixed spacers are 8pt. The capsules are chrome.bottomGlass0 … on the screen, which the page draws, as the navigation bar's, as .sb-bar-glass elements with a data-sb-placement (--sb-glass-background, --sb-glass-shadow, a backdrop blur, fully rounded, and the 1pt --sb-glass-rim ring every glass surface has at its edge: a conic gradient brightest at the top-left and bottom-right, where Liquid Glass catches the light, dimmest at the top-right and bottom-left; white, so a faint bright edge in light mode and iOS's gray hairline in dark) under the items; a toolbar's frame spans its items. Bottom items are drawn in the label color unless tinted, their symbols at the bar items' size in regular weight. chrome.bottomBar is the band from the row's top to the screen's bottom: non-scrolling content is proposed the area above it and a scroll view runs under it, inset by it. Elsewhere a ToolbarSpacer only separates groups and draws nothing (hidden).
  • Group animation (iOS 26). A bar group whose items come or go, or whose capsule or an item of it resizes, animates on its own, in a pass that carries no animation (src/animation.ts, implicitToolbars): the capsule's frame tweens with a spring (duration 0.5, bounce 0.2, TOOLBAR_ANIMATION), the items slide, a new item scales and fades in (.scale(0.6) with opacity, TOOLBAR_TRANSITION) and a removed one out, in a clone drawn as the bar drew it (data-sb-bar-item); a bar group, or a bottom bar, added to a screen already there comes in the same way, and leaves so, with its glass. A group that only moves (the screen resized, a More button appeared beside it) jumps: its items are as they were. The commit's own animation, or an .animation(_:value:) on the toolbar, takes the spring's place. The bottom bar's capsules are chrome rather than elements: the page reports their changes to the Animator as frame changes of kind barglass (no id), which follow the screen's bar toolbars. A capsule is known by the toolbars drawn on it (data-sb-toolbars, their ids), so a group that goes takes its own capsule with it, the groups after it keep theirs, and a spacer splitting a shared capsule leaves it to the first group and scales a new one in for the second.
  • Press feedback (iOS 26, src/press.ts). While a pointer is down on a bar button, the glass under it swells (scale 1.05 for a capsule, 1.08 for a circle) and brightens (--sb-glass-pressed); when the pointer lifts it springs back (an overshooting ease-out, 0.45 s). The whole group swells, as on iOS, never one item of it (a glass-styled button in a group is the group's press), and buttons on glass do not dim as plain buttons do. The glass under a control: its group's capsule, the bottom bar capsule under it (whose toolbars, beside the capsule rather than in it, swell along about the capsule's center: data-sb-pressed-with), the back and More circles, the sidebar toggle, a .glass button or the .glassEffect box around it; a control on no glass keeps the dimming. The highlight lifts while the pointer is more than 24pt outside the control and returns when it comes back, as UIKit tracks a touch. The page marks the glass data-sb-pressed and the item data-sb-pressed-item; reduced motion keeps the brightening only.
  • The inline title is placed as UIKit places it: chrome.title is a rect in the 44pt row, in a compact width no wider than 56% of the bar (a regular width gives it all the room the items leave), centered in the bar when it fits there clear of the back button and the leading / trailing items; otherwise slid off-center into the room they leave (8 clear of each side), and truncated only to that room when it does not fit even there. The back button (iOS 26) is chevron-only: a 44 × 44 glass circle at x 16 in the bar row (chrome.back), with no previous-title label.
  • Outside a navscreen a toolbar lays its children out as a plain vstack.

searchfield in a navscreen#

  • iOS 26: the field floats at the bottom of the screen, a 48pt glass capsule 28pt from each side and 28pt above the screen bottom (8pt above the bottom of a view that ends higher); the bar gets no search area, and the content is proposed the area above the field (or above a bottom bar, whichever reaches higher). chrome.searchField is the capsule, and so is the element's frame.
  • In a tab view (a screen a tab bar covers), iOS 26 puts the field under the title instead (measured in the Simulator, Backyard Birds): a 44pt capsule 16pt from each side, 1pt below the title row (y 166 under a large title), and the content starts 15pt below it (a 60pt row; a root list or scroll view is inset by it as by the title). The engine also reports it as chrome.searchTop, and the page draws it as the bar's field (a --sb-color-tertiary-fill capsule, no glass) that moves up with the content and fades under the bar when the scroll view carrying the large title scrolls (a CSS scroll-driven animation on that scroll view's timeline; where the browser has none, it stays put).
  • Rendering: --sb-glass-background with --sb-glass-shadow, the glass rim and a backdrop blur, fully rounded, 16pt horizontal padding, a magnifyingglass glyph leading in the secondary color, then an <input> (17pt, primary color) whose placeholder is placeholder ("Search" when empty) in the secondary color.
  • Typing sends { "type": "text", "id", "value" } on every input event, exactly like textfield; an update carrying the text the input already shows leaves the caret alone, a different text replaces the value.
  • Outside a navscreen it is a 36pt field taking the proposed width (200 when none).

tapgesture#

  • Size = the child's; the child is placed at the same origin.
  • cursor: pointer. A click anywhere on it sends { "type": "tap", "id" } (with "location": true in its props, { "type": "tap", "id", "x", "y" }: the click's point in the element, in points; see "MapKit") unless the click landed on an inner interactive element (a button, navlink, picker, menu, switch…), which handles it alone: the renderer resolves the innermost control under the pointer, so an inner button's tap never also fires the gesture.

List row hints#

Read through the row element's styled chain (outermost wins).

  • Default row geometry: content proposed the card width minus 16pt on each side; row height = max(52, content + 2 × 15); content centered in the row. (Menu and inline picker rows use 0 vertical padding, as before; a segmented picker gets 14.5, and the toggle / stepper rows 10.) Text field rows (the <input> itself) draw their hairline as a background image, since an input has no ::after. The hairline under a row starts at the row's first text (after a Label's icon; chrome separator, its x from the row's leading edge, which the page sets as --sb-separator-leading, else 16) and ends 16 before the trailing edge, in --sb-color-row-separator (light rgba(0,0,0,0.09), dark rgba(84,84,88,0.6)).
  • listRowInsets: { top, leading, bottom, trailing } replaces all four values for that row: content x = card x + leading, content width = card width − leading − trailing (− the badge reserve), row height = max(52, content + top + bottom), content centered between top and bottom. The DOM row box is still the full card width; only the content moves.
  • badge: "text" (non-empty) reserves width(text) + 8 at the trailing edge: the content is proposed that much less width, and the text is drawn in the row's font (17pt body by default), secondary color, right-aligned flush with the trailing inset, full row height (chrome.badge, chromeText.badge). The DOM adds a .sb-badge span inside the row's styled element. null or "" reserves nothing.

imageScale#

image elements with a systemName, and catalog images of kind: "symbol", measure a square of line height × scale (scale 0.8 / 1 / 1.25 for small / medium / large) instead of the plain line height, and are drawn at font size × scale so the glyph (1em) scales with the frame. Text and bitmap images are unaffected. The scale flows down the subtree like a font; an inner imageScale replaces an outer one.

LayoutResult additions#

kind chrome keys
navscreen title (inline title rect; absent for a large title that cannot scroll away or with a principal toolbar), searchField, leadingGlass0 …, trailingGlass0 … (the bar's glass capsules, one per run of adjacent toolbars), bottomBar, bottomGlass0 … (a bottom toolbar's glass capsules), more (the More button of collapsed secondary items)
list, scrollview topInset (the screen's bar, when this is its root scroll view and scrolls under it; the visible area for scrollTo and the refresh spinner start below it), largeTitle (the screen's large title row, when the title scrolls with this view)
picker (inline) label (when non-empty), option0 … optionN-1
list rows badge (with chromeText.badge), separator (its x: where the hairline under the row starts)

hidden also lists the items of every menu.

Phase 6: ShapeStyles, stroke borders, visual effects, asymmetric transitions#

Everything in docs/ops-protocol.md still holds. Phase 6 widens what a view can be painted with, adds a few CSS-only visual effects to styled, and one transition form. The Swift side emits exactly the JSON below; the web renderer resolves it in Web/src/styles.ts (pure, unit-tested) and applies it in Web/src/renderer.ts.

ShapeStyle#

Wherever a Color used to be accepted for painting — style.foreground, style.background, a shape's fill and stroke.color — the value is now a ShapeStyle. The three Color forms are ShapeStyles and render exactly as before:

{ "r": 0.0, "g": 0.533, "b": 1.0, "a": 1.0 }                 // explicit sRGB
{ "name": "primary" | "secondary" | "accent" | "systemBackground" | "secondarySystemBackground" | "clear", "a": 0.5 }
{ "named": "dough/plain-bg", "opacity": 1.0 }                // asset catalog color

{ "name": "systemBackground" } is what .background() with no arguments and BackgroundStyle emit; it works as a background, fill and stroke (var(--sb-color-system-background)). { "name": "foreground" } is .foreground (ForegroundStyle, also a shape's default fill): the color where it is drawn, CSS currentColor, so it follows a .foregroundStyle above it and is white inside a borderedProminent button, as in SwiftUI.

The new forms:

{ "hierarchical": 1 | 2 | 3 | 4 }                            // .primary / .secondary / .tertiary / .quaternary
{ "linearGradient": { "stops": [{ "color": Color, "location": 0.0 }, ...], "start": { "x": 0.5, "y": 0 }, "end": { "x": 0.5, "y": 1 } } }
{ "radialGradient": { "stops": [...], "center": { "x": 0.5, "y": 0.5 }, "startRadius": 0, "endRadius": 100 } }
{ "angularGradient": { "stops": [...], "center": { "x": 0.5, "y": 0.5 }, "startAngle": 0, "endAngle": 360 } }
{ "colorGradient": Color }                                   // Color.gradient
{ "material": "ultraThin" | "thin" | "regular" | "thick" | "ultraThick" | "glass" | "glassClear" }

Points (start, end, center) are unit points in the view's bounds; radii are points; angles are degrees clockwise from 3 o'clock (AngularGradient with equal angles, and conicGradient, send a whole turn: end = start + 360); stop location is 0…1.

Every non-color form may carry an optional top-level "opacity": number (0…1) multiplier — { "hierarchical": 4, "opacity": 0.5 } for .quaternary.opacity(0.5), { "material": "thin", "opacity": 0.8 }, { "linearGradient": {...}, "opacity": 0.5 }, { "colorGradient": {...}, "opacity": 0.5 }. It is applied like a semantic color's a: hierarchical colors and every gradient stop are wrapped in color-mix(in srgb, C p%, transparent); a material's alpha is multiplied.

ShapeStyle.shadow(_:) (.drop(...) / .inner(...)) is an approximation: the shadowed style serializes as its base style and the shadow is dropped.

Resolution by role#

A ShapeStyle resolves differently depending on whether it colors glyphs (text role: style.foreground) or fills an area (paint role: style.background, shape fill, stroke.color). styleToCSS(style, role) returns { kind, value, solid, backdropFilter? }: value is what to paint with (a <color>, or a CSS <image> for gradients), solid a plain <color> stand-in used where an image cannot go (border colors, currentColor consumers such as symbols): the value itself for flat styles, the first stop for gradients, the base color for materials. A hierarchical level is the foreground's in either role, as SwiftUI paints it: Rectangle().fill(.primary) is the label color, .secondary the secondary label color (or the levels of a foregroundStyle set above, through --sb-hierarchy-<n>); the system fill grays are .fill (FillShapeStyle, the systemFill names).

style text role paint role
hierarchical: 1 var(--sb-color-primary) same
hierarchical: 2 var(--sb-color-secondary) same
hierarchical: 3 var(--sb-color-tertiary-label) same
hierarchical: 4 var(--sb-color-quaternary-label) same
linearGradient linear-gradient(<angle>deg, color pct%, …) same
radialGradient radial-gradient(circle <endRadius>px at <cx>% <cy>%, color pct%, …) same
angularGradient conic-gradient(from <startAngle + 90>deg at <cx>% <cy>%, color pct%, …), the stops over the swept share of the turn same
colorGradient: C linear-gradient(to bottom, color-mix(in srgb, C, white 12%), color-mix(in srgb, C, black 12%)) same
material the material's base color (see below) rgba(var(--sb-color-material-base), α) + backdrop-filter: blur(20px)

Levels outside 1…4 degrade to 1; an unrecognised object renders magenta.

The text-role levels are levels of the foreground around them, as on iOS: each is var(--sb-hierarchy-N, <the token above>), and a styled box with a non-hierarchical foreground sets --sb-hierarchy-1 … -4 to it at 100 / 50 / 25 / 18% (measured on iOS: FoodTruck's card header icon and chevron), so .secondary under .foregroundStyle(.blue) is half-strength blue. style.foregroundLevels: [ShapeStyle] (.foregroundStyle(primary, secondary[, tertiary])) sets levels 2 and 3 to those styles instead (a hierarchical one stays the primary's level); an image with renderingMode: "palette" (.symbolRenderingMode(.palette)) draws an enclosed filled symbol's enclosure in level 2 and its glyph in level 1 (moon.circle.fill under .foregroundStyle(.white, .indigo): an indigo disc, a white moon).

New theme variables in Web/src/styles.css:

variable light dark
--sb-color-quaternary-label rgba(60,60,67,0.18) rgba(235,235,245,0.16)
--sb-color-secondary-fill rgba(120,120,128,0.16) rgba(120,120,128,0.32)
--sb-color-tertiary-fill rgba(118,118,128,0.12) rgba(118,118,128,0.24)
--sb-color-quaternary-fill rgba(116,116,128,0.08) rgba(118,118,128,0.18)
--sb-color-material-base 255, 255, 255 30, 30, 30

(--sb-color-fill already existed: light rgba(120,120,128,0.2), dark rgba(120,120,128,0.36).)

Linear gradient angle. CSS measures gradient angles clockwise from "to top", so the angle is atan2(dx, −dy) with d = end − start: top→bottom is 180deg, leading→trailing 90deg, topLeading→bottomTrailing 135deg. A CSS gradient line always spans the whole box, so stop locations are mapped onto the projections of start and end on that line — exact for axis-aligned gradients (a gradient from y: 0.25 to y: 0.75 puts its stops at 25% and 75%), approximated on a unit square otherwise. start == end falls back to 180deg.

Radial gradient. Stops are placed at (startRadius + location · (endRadius − startRadius)) / endRadius. A missing or non-positive endRadius uses circle farthest-corner with the raw locations.

Materials. α is 0.55 (ultraThin), 0.7 (thin), 0.82 (regular), 0.9 (thick), 0.96 (ultraThick), times the optional opacity. The renderer sets both backdrop-filter and -webkit-backdrop-filter. glass (iOS 26 .glassEffect) is the bar buttons' fill, --sb-glass-background, and glassClear half of it, over blur(20px) saturate(180%); the element is marked data-sb-glass, which gives it the glass shadow and the 1pt glass rim (styles.css).

Where each role lands#

  • style.background → background-color (colors, materials; materials also get the backdrop filter) or background-image with a transparent background-color (gradients) on the styled box.
  • style.foreground → color and --sb-button-color on the styled box (the solid value). For a gradient the box additionally sets the inherited custom properties --sb-text-gradient (the image), --sb-text-clip: text, --sb-text-color: transparent and --sb-foreground-paint (the image), and data-sb-gradient-text. The .sb-text rule reads them: background-image: var(--sb-text-gradient, none); background-clip: var(--sb-text-clip, border-box); color: var(--sb-text-color), so every text in the subtree — including text under nested styled boxes — paints the gradient through its glyphs. A styled box with a flat foreground resets the four properties to initial, which ends the gradient for its subtree (with the properties unset the .sb-text declarations are invalid at computed-value time and fall back; color becomes unset, i.e. inherits as before). Symbols (currentColor) and other currentColor consumers get the first stop; a shape with fill: null paints var(--sb-foreground-paint, currentColor), so it shows the gradient too.
  • shape fill → the shape's background-color / background-image (materials with backdrop filter).
  • shape stroke.color → the border color. CSS borders are flat, so a gradient stroke uses its first stop (solid); a material stroke its base color.

Shape stroke border and containerRelative#

"stroke": { "color": ShapeStyle, "lineWidth": 2, "inset": true }

inset: true is .strokeBorder(_:lineWidth:): the stroke lies fully inside the shape's frame. The renderer draws every stroke as a CSS border on a box-sizing: border-box box, which is already inside the frame, so the look of a non-inset stroke is unchanged from before. Which one it was is recorded as data-sb-stroke="inset" | "center" on the shape element.

shape gains the name "containerRelative" (ContainerRelativeShape), rendered like roundedRectangle with the given cornerRadius.

A circle is drawn in the square centered in its frame (SwiftUI draws the largest circle that fits), so Circle().frame(width: 110) in a taller space stays round; the frame the siblings were laid out with is unchanged.

Custom shapes#

A Shape that is not one of the built-in shapes (any type with a path(in:), Path itself, an inset or trimmed custom shape) is sent as shape: "path" and drawn from its path:

{ "shape": "path", "cornerRadius": 0, "fill": ShapeStyle | null,
  "stroke": { "color": ShapeStyle, "lineWidth": 3,
              "lineCap": "round", "lineJoin": "bevel", "miterLimit": 10,
              "dash": [4, 2], "dashPhase": 0 } | null,
  "fillRule": "evenodd",          // FillStyle(eoFill: true)
  "reportsSize": true,
  "path": "M50 0L0 90L100 90Z",    // SVG path data, points rounded to hundredths
  "size": { "width": 100, "height": 90 },
  "affinePath": { "path": "M0 0L0 0L0 0Z",          // in place of path and size:
                  "width": [0.5, 0, 0, 0, 1, 0],    // each number's growth a point of width
                  "height": [0, 0, 0, 1, 0, 1] },   // and of height
  "frames": { "progress": [-0.3, …, 0, …, 1, …, 1.3], "index": [0, …], "paths": ["M…"] } }

The path depends on the size the shape is laid out at, which only the page knows, so the element reports its size (reportsSize, a geometry event like a GeometryReader's) and the next render sends path for a rectangle of size at the origin. Until the first report path is empty. A path whose every number is a constant plus a multiple of the width and of the height (a point a fraction of the way across, a margin in from an edge) can skip that: @swiftbrowser/react works the parts out from the path at three sizes, checks them at three more (a tiny one among them, where a clamp shows), and sends affinePath instead, with reportsSize: false. Its path is the data with each number its value for an empty rectangle; the ith number grows width[i] a point of the element's width and height[i] a point of its height. The page and the native renderer draw it for the size they lay the element out at, from the first layout, with nothing reported and no render waiting on one (AffinePath in SVGPath.swift, affinePathData in src/pathShape.ts). The page draws an <svg class="sb-path"> filling the element, with size as its view box (stretched until the path for a new size arrives) and one <path>: fill and stroke are SVG paints (gradients become SVG gradients), with the stroke's caps, joins and dashes. A .strokeBorder of a custom shape is drawn by the Swift side: the shape is inset by half the line (an InsettableShape with inset(by:), any other shape as a rectangle) and stroked as is, so stroke.inset is not sent. A trimmed custom shape is trimmed by the Swift side too (trimmedPath(from:to:)), so trim is not sent.

frames is sent with an update in which the shape's animatableData changed in a pass that may animate it (the transaction has an animation, or an .animation(_:value:) above the shape saw its value change; a change from a slider sends none): paths[index[i]] is the path with the data progress[i] of the way from the old value to the new one (values below 0 and above 1 are for a spring that overshoots; equal paths are sent once). When the commit animates the element (withAnimation, or an ancestor's changed animationToken) the page draws, on each animation frame, the frame nearest the animation's eased progress, and the final path when it ends; otherwise it draws path at once. That is SwiftUI's interpolation of animatableData, sampled.

Built-in shapes are unchanged: drawn by name from cornerRadius, without reportsSize. Circle().inset(by:) (and the other built-ins' inset(by:)) is a custom shape, so an inset ring is drawn with a gradient stroke.

Visual effect style hints#

New styled style keys. They are applied as CSS on the styled box and have no layout effect: the layout engine sizes and places the subtree as if they were not there.

{
  "offset":         { "x": 10, "y": -4 },          // .offset: points
  "rotation":       45,                            // .rotationEffect: degrees, clockwise positive
  "rotationAnchor": { "x": 0.5, "y": 0.5 },        // unit point, default center
  "scale":          { "x": 1.5, "y": 1.5 },        // .scaleEffect
  "scaleAnchor":    { "x": 0.5, "y": 0.5 },        // unit point, default center
  "shadow":         { "color": Color, "radius": 8, "x": 0, "y": 4 },
  "compositingGroup": true,                        // .compositingGroup() / .drawingGroup()
  "clipped":        true
}

CSS:

  • one transform, composed in this order: translate(xpx, ypx) rotate(deg) scale(x, y) (identity parts are left out; no transform is set when nothing applies);
  • transform-origin from the anchor as percentages (x·100% y·100%). CSS has a single origin for the whole transform, so when both rotationAnchor and scaleAnchor are present and differ the rotation anchor wins; without any anchor the origin stays at the default center;
  • shadow falls, as SwiftUI's .shadow on a container does, on each view the box draws, not on the box as a whole: on its texts, shapes, images and controls, on the backgrounds painted on boxes inside it, and on their own shadows, through a clip, a mask, a blur or an opacity on the way (measured in SwiftUI by Native/Tests/SwiftBrowserNativeTests/ShadowSemanticsTests.swift). The page hands a box's shadows down as --sb-shadow-filter (its own drop-shadow(xpx ypx radiuspx color), then those of the boxes around it), which each drawn view (text, image, shape, color, divider, canvas, registered, chart and the controls) takes as its filter; a background painted on a box takes them as a box-shadow, and a box that clips or masks takes them in its own filter too, so they are cast outside its clip (castShadows in renderer.ts, after each commit);
  • compositingGroup: true (.compositingGroup(), .drawingGroup()) draws the box as one: the shadows around it fall on it as a whole (its filter), not on the views inside it, as in SwiftUI. A shadow meant to fall around a view whole (a card, a thumbnail) puts one before it, or goes on the view's background instead;
  • clipped: true → overflow: hidden and data-sb-clipped on the box.

Animation: transform and filter are part of the Animator's animated style properties, so in an animated commit (withAnimation) or a subtree whose animationToken changed, a changed rotation/offset/scale/shadow tweens from the previous computed value. Frame animations tween left/top/width/ height and do not touch the transform. Enter and exit transitions compose their own transform on top of the box's (<own> <transition> → <own>), so a rotated view slides in while staying rotated.

Asymmetric transitions#

transition parts gain:

{ "kind": "asymmetric", "insertion": Transition, "removal": Transition }

where each side is a part or an array of parts (and may itself contain asymmetric parts; nesting is capped at 8 levels). When the subtree is inserted the renderer plays insertion; when it is removed, the exit clone plays removal. It combines with sibling parts of the enclosing array like any other part:

[{ "kind": "opacity" },
 { "kind": "asymmetric", "insertion": { "kind": "move", "edge": "leading" }, "removal": { "kind": "scale", "scale": 0.2 } }]

TypeScript#

Web/src/protocol.ts: ShapeStyle = Color | HierarchicalStyle | LinearGradientStyle | RadialGradientStyle | ColorGradientStyle | MaterialStyle (Color is unchanged and remains the type of color.color, gradient stops and shadow.color), UnitPoint, GradientStop, Shadow, Stroke.inset, ShapeKind + containerRelative, TransitionPart.insertion/ removal, and the Style effect keys. Web/src/styles.ts: colorToCSS, styleToCSS(style, role), linearGradientCSS, radialGradientCSS, effectsCSS(style). Tests: Web/src/__tests__/styles.test.ts (resolution), Web/e2e/phase6-styles.spec.ts (computed styles in Chromium).

Phase 7: charts, split navigation, ViewThatFits, masks, size classes#

Everything above still holds. Phase 7 brings the Food Truck sample's Swift Charts screens, its NavigationSplitView root and the City panel to the browser. The Swift side (Sources/Charts, the shim) turns data into unit coordinates; the renderer owns pixels: it measures axis labels and annotation views, derives the plot rectangle and draws the marks as SVG.

Environment event (extended)#

{ "type": "environment", "colorScheme": "dark", "dynamicTypeSize": "large",
  "horizontalSizeClass": "compact" }       // or "regular"

The renderer sends regular when the screen (#screen, the frame or the real viewport) is at least 700 CSS px wide, else compact, and re-sends the event when that changes (a resize or rotation). Swift exposes it as EnvironmentValues.horizontalSizeClass (UserInterfaceSizeClass?; .compact until the first event). Headless runs are compact.

Device mode (changed)#

A coarse pointer now means device mode at any width (a tablet fills the viewport instead of showing the phone bezel); the 500 px rule is gone. ?mode=frame / ?mode=device still force a mode.

New element kinds#

kind props children
chart marks: Mark[], xAxis: Axis | null, yAxis: Axis | null, legend: Legend | null chartitems (annotations and custom axis labels), in any order
chartitem role: "annotation" | "xLabel" | "yLabel", x0, x1, y0, y1: number (unit rect of the mark; for labels x0 == x1 / y0 == y1 is the tick), position: "top" | "bottom" | "leading" | "trailing" | "overlay", alignment: Alignment, spacing: number one view
navsplit sidebarVisible: boolean (false hides the sidebar) [sidebar, detail], each a navstack; the sidebar's content may carry a styled hint splitColumnWidth: { min?, ideal, max? } (.navigationSplitViewColumnWidth), its width
viewthatfits axes: "horizontal" | "vertical" | "both" the candidates, in order
flowstack spacing: number | null, lineSpacing: number | null, alignment: "top" | "center" | "bottom" its items, in order (below, FlowStack)

Unit coordinates#

Every chart coordinate is a number in 0…1 relative to the plot rectangle (the chart's box minus axes and legend, computed by the renderer): x runs left → right, y runs top → bottom (so the largest value is y = 0, like every other box in this protocol). Swift applies the scales: a continuous axis maps (value − min) / (max − min) with the "nice" domain it chose; a categorical (band) axis gives category i of n the band [i/n, (i+1)/n]. Values outside 0…1 are allowed (a mark may leave the plot) and are clipped by the renderer to the plot rectangle, except annotations.

Mark#

All marks carry style: ShapeStyle (Phase 6 JSON: a Color, linearGradient, radialGradient, hierarchical, …), opacity: number (0…1, default 1) and an optional mask: Mark (an area or rect mark whose geometry clips this mark; the renderer renders it as an SVG clipPath). kind selects the rest:

kind fields drawn as
rect x0, x1, y0, y1 (unit rect, x0 ≤ x1, y0 ≤ y1), cornerRadius: number (px, default 0), fixedWidth: number | null (px: the rect is fixedWidth wide, centered on (x0 + x1) / 2) a filled <rect> (BarMark, RectangleMark)
line points: [{ x, y }], lineWidth: number (px, default 2), interpolation: Interpolation, symbol: Symbol | null, symbolSize: number (px, default 8) a stroked <path> plus one symbol glyph per point (LineMark)
area points: [{ x, y0, y1 }] (y0 ≤ y1), interpolation: Interpolation a filled <path> between the two curves (AreaMark)
point x, y, symbol: Symbol, symbolSize: number (px, default 8) one symbol glyph (PointMark)
rule x0, x1, y0, y1, lineWidth: number (px, default 1) a stroked line between the two points (RuleMark)

Interpolation is "linear" | "cardinal" | "catmullRom" | "monotone" | "stepStart" | "stepCenter" | "stepEnd"; the renderer draws cardinal, catmullRom and monotone as a Catmull-Rom spline through the points (cubic Béziers) and the steps as right-angle paths. Symbol is "circle" | "square" | "triangle" | "diamond" | "cross" | "plus" | "asterisk"; it is drawn in the mark's style, centered on the point. Marks draw in array order.

Axis#

{ "position": "bottom",                      // x: "bottom" | "top"; y: "trailing" | "leading"
  "gridLines": [0.0, 0.25, 0.5, 0.75, 1.0],   // unit positions along the axis
  "ticks":     [0.0, 0.25, 0.5, 0.75, 1.0],
  "labels":    [{ "at": 0.125, "text": "Mon" }, …],   // default text labels; an x label of a date has "anchor": "leading" (it starts at its tick)
  "dashed": true }                             // present on a date axis

Grid lines are half a point wide; a date axis's are dashed 2pt on, 2pt off, as Swift Charts draws them (measured: FoodTruck's forecast).

Positions are unit values along that axis (for the y axis 0 is the top). A label whose content is a view instead of text is not in labels: it is a chartitem child with role xLabel / yLabel and the tick position in x0 == x1 (x) or y0 == y1 (y). null for the whole axis means hidden.

Legend#

{ "position": "top",                          // "top" | "bottom" | "leading" | "trailing"
  "items": [{ "label": "Cupertino", "style": ShapeStyle, "symbol": Symbol | null }] }

null: no legend. Swift builds one entry per distinct foregroundStyle(by:) / symbol(by:) value, in first-seen order, with SwiftUI's chart palette (blue, green, orange, purple, red, teal, yellow, pink, indigo, mint, cyan, brown, in that order, cycling).

Layout rules: chart#

  • Size: the proposal on both axes; a nil axis is 300 (width) / 200 (height) and an infinite axis stays infinite (the chart is as flexible as a shape). The chart's box is split into the legend row (top or bottom; a leading / trailing legend is a column), the axis bands and the plot. The legend is separated from the rest by 8 px.
  • Axis bands: the y-axis band is as wide as its widest label (text labels measured in the axis font, yLabel children at their ideal width) plus 6 px, 0 when there are no labels; the x-axis band is as tall as its tallest label (text: one line of the axis font; xLabel children at their ideal height) plus 6 px. The 6 px lie between the plot edge and the label (the ticks sit inside them). A top x axis puts its band above the plot, a leading y axis its band to the left. The axis font is caption (12 px) in the secondary color. Grid lines are 1 px in --sb-separator; ticks are 1 px, 4 px long, outside the plot, same color.
  • Plot: what remains. Marks are drawn into one <svg> the size of the plot (chrome; data-sb-id-less) with overflow: hidden. The engine reports the plot, the legend, the axis bands, every text label and every legend item as chrome rects (plot, legend, xband, yband, xlabel<i>, ylabel<i>, legend<i>).
  • Labels: an x text label is centered on at, clamped to the chart's width; a y text label is right-aligned (trailing axis: left-aligned) to the band, vertically centered on at and clamped to the chart's height. xLabel children: ideal size, centered horizontally on x0, against the plot edge of the x band (6 px away from the plot). yLabel children: ideal size, centered vertically on y0, against the plot edge of the y band.
  • Annotations (role: "annotation"): the child is measured at its ideal size and placed against the mark's pixel rect R (x0…x1, y0…y1 mapped into the plot): top → centered above R, bottom edge at R.top − spacing; bottom → below, top edge at R.bottom + spacing; leading / trailing → beside, centered vertically; overlay → centered on R. alignment shifts it along the free axis the way ZStack alignment does (top + .leading puts its leading edge on R.left). Annotations are not clipped to the plot and draw above the marks.
  • Legend items: a 10 px symbol glyph (or an 18 × 3 px line when symbol is null) in the item's style, then the label in caption (12 px) secondary text, 4 px apart; items flow horizontally with 12 px between them and wrap at the chart's width into rows 4 px apart (a leading / trailing legend puts one item per row and is as wide as its widest item). Each item is one line of the caption font tall (16 px at the default size) and its width is rounded up to whole pixels.
  • Styles in SVG: a Color paints with the same CSS it does elsewhere (semantic and named colors through the --sb-color-* tokens, the chart palette names included); hierarchical levels are the foreground's; a linearGradient becomes an SVG <linearGradient> in object bounding box units (start → x1 y1, end → x2 y2), a radialGradient a <radialGradient> in user space centered on the mark's bounds with startRadius / endRadius in px; colorGradient a vertical light → dark gradient of its color; a material a translucent gray (no backdrop blur inside the SVG). The style's opacity multiplies the stops, the mark's opacity the whole mark.

Swift side#

How the shim (Sources/SwiftUI/Charts, re-exported by Sources/Charts) fills the JSON above; these refine the spec rather than change it:

  • Domains. A continuous y scale includes 0 by default for every mark kind (as in Swift Charts; chartYScale(domain: .automatic(includesZero: false)) fits the data); a continuous x scale never adds 0. Numeric ticks use steps of 1, 2, 2.5, 5 × 10ᵏ (the one nearest to span / (desiredCount − 1), about 5 ticks by default, at least minimumStride); with roundLowerBound / roundUpperBound (default true) the domain extends to the first and last tick, otherwise ticks outside the data are dropped. Explicit AxisMarks(values: [...]) are used verbatim and never round the domain. A hidden axis still rounds the domain like a default one. Masks' marks do not contribute to the domain.
  • Dates are UTC epoch seconds; the tick unit follows the span: up to 3 days, every 1 / 3 / 6 / 12 hours ("9 AM"); up to 45 days, every 1 / 2 / 7 / 14 days ("Sep 30"); beyond, every 1 / 2 / 3 / 6 months ("Jan", or "Jan 2026" when the ticks cross a year) or 1 / 2 / 5 / 10 years ("2026"). The stride is the smallest giving at most desiredCount + 1 (default 8) intervals. Explicit date values are labelled by their own granularity.
  • Series. LineMarks / AreaMarks with the same key (series:, else the foregroundStyle(by:) value, else the symbol(by:) value, else none) form one line / area mark wherever they appear in the content, with their points in x order. The mark's style, line width, symbol and interpolation come from the group's first mark. A mark with no style and no by: value is Color.blue.
  • Bars on a band axis are 0.8 of the band; on a continuous x axis the band is the smallest gap between bar centers. MarkDimension.ratio scales the band, .inset is treated as .automatic, .fixed sets fixedWidth with x0 == x1 at the center. Bars are not stacked.
  • Symbols for symbol(by:) cycle circle, square, triangle, diamond, cross, plus, asterisk (.pentagon draws as diamond). symbolSize(_:) takes an area and emits its square root as the diameter.
  • Annotations anchor to the mark's rect (bars, rectangles), the rule's segment, or the point at (x, y) / (x, yEnd) for lines, areas and points; .topLeading and friends become top / bottom with the implied alignment. The default spacing is 4.

NavigationSplitView { sidebar } detail: { detail } renders by size class:

  • Regular: a navsplit with two children. The sidebar child is a navstack whose root navscreen holds the sidebar content (its title from .navigationTitle, displayMode large). The detail child is the detail view's own NavigationStack (a navstack), or one the shim wraps around it. Layout: the sidebar column is 320 pt wide (at most 40 % of the width left by the horizontal safe-area insets), the detail column takes the rest; a 1 px --sb-color-separator hairline sits between them. Each column's navstack fills its column (the renderer's chrome sidebar, separator and detail rects); the safe area's top and bottom insets apply to both columns (each column's screens reserve the status bar and the bottom inset exactly as a root navstack does), its leading inset to the sidebar and its trailing inset to the detail: the sidebar's navstack starts at the leading inset and the detail's ends at the trailing inset, so the column rects include the insets and the navstacks exclude them. A navsplit is only laid out as a root element (like a root navstack it ignores the safe areas itself). Sidebar toggle (iPadOS). The renderer draws a sidebar.left button (.sb-navsplit-toggle, a 44 pt glass circle like the back button) at the engine's chrome toggle rect: 16 in from the leading inset, in the bar row under the status bar. Its column's screens (the sidebar's, or the detail's while the sidebar is hidden) start their back button and leading toolbar items 52 further in. A tap sends tap with the navsplit's id; Swift flips the split view's column visibility with animation: the columnVisibility binding when one is given, else its own state (detailOnly hides the sidebar, any other value shows it) and sends sidebarVisible. With sidebarVisible: false the sidebar column and its separator sit just off the leading edge (so the columns slide) and the detail column takes the whole width; the element carries data-sb-sidebar-hidden.
  • Compact: a plain navstack rooted at the sidebar content. While the sidebar's selection (below) is non-nil (also at launch), Swift pushes one navscreen with the detail view's content; links inside the detail push after it; the back button pops it and clears the selection. A NavigationStack nested inside a navscreen of another stack is flattened: it renders its root content in place, its navigationDestinations register with the enclosing stack and its links push onto that stack (its path binding is ignored).

List selection. List(selection: Binding<Value?>) makes its rows selectable: a NavigationLink(value:) row inside it sets the selection to its value instead of pushing when the list is a NavigationSplitView sidebar (in compact mode the split view then pushes the detail, see above; outside a split view the link still pushes). The selected row's navlink carries selected: true (and a link under .buttonStyle(.plain) carries style: "plain": its label is in the foreground around it, not the tint) and the renderer draws it with a --sb-color-tertiary-fill rounded (10 px) background (sidebar style, data-sb-selected on the row) and no chevron when inside a navsplit sidebar; elsewhere (the detail column, a plain stack) the chevron stays. The label keeps reserving the chevron's width either way, so selecting a row never reflows it.

Inspector#

.navigationSplitViewColumnWidth(min:ideal:max:) on a split view column's content is a styled hint splitColumnWidth ({ min?: number, ideal: number, max?: number }; the fixed navigationSplitViewColumnWidth(_:) sends all three the same). A renderer reads it on the sidebar's content, through its styled wrappers, its navstack and that stack's root screen, and sizes the sidebar column at ideal (default: 140 on a Mac, 320 on an iPad), never more than 40% of the split view's width. On a Mac the user drags the column divider (the navsplit's chrome divider, an 8px strip astride the sidebar panel's trailing edge while it shows) between min (default: the platform's default width, or the ideal when smaller) and max, as SwiftUI's split view lets them; the page keeps the width it was dragged to for the split view's life (LayoutEnvironment.sidebarWidths), and when a drag that changed it ends, sends the navsplit a columnwidth event ({ type: 'columnwidth', id, width }, the width laid out, within the bounds) so the app can keep it and start there next time. An iPad's sidebar is not dragged.

.inspector(isPresented:content:) renders by size class, as on iPadOS / iOS:

  • Regular: an inspector element (props presented: boolean) whose children are the modified view's elements and, last, an inspectorpanel holding the inspector content. The inspector fills its proposal (as a root it ignores the safe areas, like a root navstack). The panel is a trailing column 320 wide (.inspectorColumnWidth(_:) on the inspector content, a styled hint inspectorColumnWidth; at most half the width) plus the trailing safe-area inset when it touches that edge, after a 1px gap where the panel draws its hairline (a box-shadow, so it moves with the panel); the content is proposed the rest and each of its children is centered there. The panel's content starts below the status bar, top-aligned (a list or form fills it). With presented: false the panel sits just off the trailing edge and the content takes the whole width; the element carries data-sb-presented while it is shown. Toggling the binding updates presented, and an update that changes presented animates the inspector's subtree even when its commit has no animation, as SwiftUI slides an inspector in and out: with the commit's animation when it has one (withAnimation), else default.
  • Compact: a sheet with the inspector content, presented while the binding is true (.sheet(isPresented:)).
  • In a screen: an inspector anywhere in a navscreen's content (through containers, but not inside a sheet, an alert, a nested stack, a split view, a tab view or another inspector's panel) is presented as iPadOS presents .inspector inside a navigation stack: its column stands beside the screen the whole height, from the top of the screen to its bottom, and the screen's bar, bottom bar and content keep to the rest, as a split view's detail does beside an inspector. The panel's content starts under the status bar. The inspector element spans the screen's whole area, so the panel is inside it; its content takes the box the screen gives it. Hidden, the column waits off the trailing edge and the screen is whole. A tree another root draws here (RemoteTree) gets this too: an app's root inspector becomes a column of the host's screen.

ViewThatFits#

Props axes (default both). The engine measures every child's ideal size and shows the first child whose ideal size fits the proposal on the restricted axes (ideal.width ≤ proposal.width when horizontal is restricted, same for height; a nil or infinite proposal axis always fits); when none fits, the last child. Only the chosen child is measured with the proposal and placed, and the element reports its size; the others get no frame and the renderer hides them (hidden attribute). Within one pass the choice is stable (it depends only on the proposal and the children).

FlowStack#

flowstack, SwiftBrowser's own (SwiftUI has none built in; an app writes one with Layout). Props spacing (between the children on a line; null is 8), lineSpacing (between lines; null is the spacing) and alignment (top, center or bottom: a child's place in its line). The engine measures each child's ideal size and fills lines leading to trailing, starting a new line where the next child would pass the proposed width; a child wider than the width is alone on its line, measured and placed with the width proposed. With no width proposed, one line. The element's size is its widest line by the sum of its lines' heights and the spacing between them; each child is placed at its measured size. The native renderer lays it out with a SwiftUI Layout doing the same (FlowStackLayout).

styled style (added fields)#

field meaning
hidden: true .hidden(): the box keeps its layout but draws nothing (visibility: hidden, no input)
mask: ShapeStyle .mask { Gradient / Color }: CSS mask-image (and -webkit-mask-image, mask-size: 100% 100%) from the style (a linearGradient / radialGradient becomes the matching CSS gradient, a Color a solid mask whose alpha is the color's: linear-gradient(rgba(0,0,0,a), rgba(0,0,0,a)); a hierarchical style or material a solid mask at its opacity). Only style masks are supported; a view mask falls back to the unmasked view on the Swift side

Headless#

chart and chartitem elements appear in snapshots like any other; their props are stable for a pinned SB_NOW.

TypeScript#

src/protocol.ts: ChartProps, ChartMark (union by kind), ChartAxis, ChartLegend, ChartItemProps, ChartInterpolation, ChartSymbol, NavSplitProps, ViewThatFitsProps, Style.hidden, Style.mask, EnvironmentEvent.horizontalSizeClass, NavLinkProps.selected.

Phase 8: interaction#

Everything above still holds. Phase 8 adds what real apps do with their fingers: gestures, swipe actions and context menus on rows, edit mode with deletion and multi-selection, alerts and confirmation dialogs, full-screen covers, pull to refresh, the remaining controls (Stepper, Slider, DatePicker, TextEditor), plus 3D rotation, blur, safe-area bleed, repeating animations and the scene phase. The driver is Examples/HackingWithSwift (five of Paul Hudson's public-domain SwiftUI projects).

Events (added)#

{ "type": "drag", "id": 12, "phase": "began" | "changed" | "ended" | "cancelled",
  "translation": { "width": 40.5, "height": -3 },     // since the pointer went down, points
  "location": { "x": 120, "y": 30 },                   // in the gesture element's box
  "startLocation": { "x": 80, "y": 33 },
  "velocity": { "width": 310, "height": 0 } }          // points per second (ended only; else 0)
{ "type": "longpress", "id": 12, "location": { "x": 40, "y": 18 } } // 0.5 s hold without moving more than 10 px
{ "type": "step",  "id": 7, "value": 1 }               // Stepper: +1 / -1
{ "type": "slide", "id": 7, "value": 0.35 }            // Slider: the value in its range
{ "type": "date",  "id": 7, "value": 1700000000 }      // DatePicker: seconds since 1970, UTC
{ "type": "delete", "id": 31 }                         // a `listrow`: swipe-to-delete or the edit-mode minus
{ "type": "move", "id": 31, "to": 2 }                  // a movable `listrow` dragged to a new place ("Reordering rows")
{ "type": "refresh", "id": 40 }                        // a `list` / `scrollview` with `refreshable`
{ "type": "scrollposition", "id": 31 }                 // a `scrollID` target: at the anchor of a `reportsPosition` scroll view, now settled
{ "type": "scrollvisibility", "id": 31, "visible": false } // a `styled` with `scrollVisibility`: came into its scroll view's visible area, or left it

text is reused by texteditor; tap by alert buttons, swipe actions, context-menu items and listrow selection. drag events are coalesced to one per animation frame while changed; began is sent once the pointer has moved minimumDistance (default 10 px, 0 for an immediate gesture), ended when the pointer lifts and cancelled when the browser takes the pointer (scroll, pointercancel). Headless: drag:12:changed:40x-3, longpress:12, step:7:1, slide:7:0.35, date:7:1700000000, delete:31, move:31:2, refresh:40, scrollposition:31.

Environment event (extended)#

"scenePhase": "active" | "inactive" | "background" from the document's visibility and focus (active when visible and focused, inactive when visible but unfocused, background when hidden). Swift exposes it as EnvironmentValues.scenePhase (ScenePhase; .active by default). Every environment event carries it; the renderer sends a new one on visibilitychange and window focus / blur only when the phase actually changed (window.__sb.scenePhase() reads the current value).

New element kinds#

kind props children
gesture drag: bool, longPress: bool, minimumDistance: number, minimumDuration: number exactly one
touches none exactly one ("Multi-touch")
swipeactions trailing: number, leading: number, fullSwipeTrailing: bool, fullSwipeLeading: bool [content, ...trailing actions, ...leading actions]; actions are buttons, each possibly inside styled wrappers (.tint is the tint style on such a wrapper and colors the action; .disabled likewise); role destructive is red
contextmenu none [content, ...items]; items as in a menu
listrow selectable: bool, selected: bool, deletable: bool, movable: bool (present only when true) one view (the row content)
alert title: string, message: string | null, style: "alert" | "dialog" the buttons, in order (a role: "cancel" button is drawn apart; none → the renderer adds "OK"), and textfields (drawn in the card above the buttons; "Editors, bars and alerts for a word processor")
stepper canIncrement: bool, canDecrement: bool the label (may be empty)
slider value: number, min: number, max: number, step: number | null [label?, minimumValueLabel?, maximumValueLabel?] as marked by labels: ["label", "min", "max"] in order present
datepicker seconds: number, components: "date" | "hourAndMinute" | "dateAndTime", min: number | null, max: number | null, timeZone?: string (IANA; the environment's \.timeZone) the label (may be empty; labelsHidden hides it)
texteditor text: string none

sheet gains detents: ["full"] for .fullScreenCover: the card fills the screen (no corner radius, no grabber, no drag to dismiss) and slides up like a sheet. list and scrollview gain refreshable: bool and refreshing: bool; list gains editing: bool. Swift omits these when false (refreshable and refreshing are both present on a refreshable element, editing only while editing): absent means false.

Gestures: gesture#

The element is transparent for layout (its child's size). The renderer tracks pointers on it: with drag, a pointer that moves minimumDistance starts a drag and the element receives drag events until the pointer lifts; the coordinates are relative to the element's own box. With longPress, a pointer held minimumDuration (default 0.5 s) without moving 10 px sends longpress. Taps still reach controls inside (a drag begins only after the distance is met; a long press suppresses the following click). A gesture inside a scrolling container claims the pointer once the drag begins on the axis the gesture wants; drag here is two-dimensional, so it claims immediately after minimumDistance. .gesture, .highPriorityGesture and .simultaneousGesture are one wrapper each, told apart by mode ("Gesture spaces and composition"). .onLongPressGesture is a gesture with longPress. A TapGesture attached with .gesture is the Phase 6 tapgesture element, not a gesture (a gesture that both taps and drags nests the tapgesture inside the gesture); a gesture with neither drag, long press nor tap emits nothing. Combined gestures (sequenced, simultaneously, exclusively) merge into one gesture that tracks both, with the smaller distance / duration; the shim does not order or exclude them. On the Swift side a cancelled drag ends the gesture: onEnded runs with the event's value (so state an app resets in onEnded is reset), and began is handled like changed. A longpress runs LongPressGesture's onChanged(true) and onEnded(true) together, and .onLongPressGesture's onPressingChanged is told true then false around perform. The longpress event's location is where the pointer was held, in the element's box; SwiftUI's value has no place for it, and RealityKit's entity-targeted long press (docs/realitykit.md, "Gestures") finds its entity with it. A renderer that cannot tell leaves it out.

Renderer details (src/interaction.ts): began carries the translation at the moment the distance is met (with minimumDistance: 0 the pointer is owned from the pointer down and began goes out with the first move); velocity is the displacement over the samples of the last 100 ms; cancelled is sent when the browser cancels the pointer (a native scroll won). A pointer down in a text field (input, textarea) never starts a gesture, so text selection still works there; everywhere else a pointer session suppresses text selection. A right click on a gesture with longPress shows no browser menu. When several behaviours could own one pointer they are asked in a fixed order on each move: swipe back (a down within 24 pt of a pushed screen's leading edge) first, then the wrappers between the target and the screen innermost first (gesture, contextmenu, swipe row), then the sheet card, then pull to refresh; the first whose direction matches claims the pointer and the others are dropped. Inside a vertical list or scrollview in a sheet the card is asked only while that view is scrolled to its top: as in UIKit, a downward drag there moves the sheet, and anywhere else the view scrolls. For touch, the first downward move at the top is kept from scrolling (or overscrolling) the view natively, which would cancel the pointer, unless the view is refreshable. A swipe row is not asked when the pointer went down inside a horizontal scrollview (axes horizontal or both) within the row, and horizontal wheel scrolling there scrolls the scroll view: as in UIKit, the inner scroll view keeps horizontal motion.

Multi-touch: touches#

A SwiftBrowser addition: SwiftUI has no gesture that reports every finger, and a piano, a drum pad or a multi-finger drawing needs chords and glissandi where the single-pointer gestures above own one pointer at a time. The shim's .onTouches { touches, phase in } (Touch: id, location; TouchesPhase) and @swiftbrowser/react's onTouches={(touches, phase) => …} wrap the view in a touches element, transparent for layout like gesture, with no props. The renderer owns every pointer that goes down inside it and sends the element touches events:

{ "type": "touches", "id": 12, "phase": "began",
  "touches": [{ "id": 3, "x": 41.5, "y": 80 }, { "id": 4, "x": 122, "y": 76.25 }] }

phase is began when a pointer came down, changed when pointers moved (coalesced to one per animation frame), ended when one lifted and cancelled when the renderer lost them all; touches is every pointer still down after the change, in order of arrival, with a stable id while it is down and its point in the element's coordinates (hundredths of a point). An app reads its state from each event (the keys under the fingers) rather than pairing ups with downs; a cancelled carries no touches.

Renderer details (src/touches.ts): a pointer down inside a touches element stops there, so no scroll view, swipe row or gesture above the element competes for the finger, and touch-action: none keeps the browser from scrolling or zooming with it; the pointer is captured on the element, so a finger sliding off it keeps reporting until it lifts. A pointer down in a text field inside the element still selects text. Clicks still reach the controls inside. Two touches elements can hold fingers at the same time; each hears only its own. Natively (Views/Kinds/Touches.swift) iOS 18 and macOS 15 report every finger through SpatialEventGesture; before that, and in the round trip against the shim, a DragGesture with no minimum distance reports the one finger it can, so a chord there is one note.

Sound is the app's: AVAudioEngine in @swiftbrowser/react ("An audio engine") plays files, buffers and samples through effects on both sides, and synthesis that has no node there plays through functions the app's Swift registers with NativeFunctions (docs/native.md, "The native escape hatch"). The Showcase's Piano does both: Native/Examples/Showcase/src/piano/sound.ts synthesizes with Web Audio on a page and calls piano.noteOn and friends natively, which apple/PianoSynth.swift answers with the same synthesis on an AVAudioSourceNode.

Pinch#

MagnifyGesture and RotateGesture (and the iOS 13 MagnificationGesture and RotationGesture) are a gesture with magnify / rotate, with minimumScaleDelta (default 0.01) and minimumAngleDelta (degrees, default 1). Both keys are absent unless set, so a drag's props are as above. Combined with a drag (simultaneously), one gesture tracks both.

{ "type": "pinch", "id": 7, "phase": "changed", "scale": 1.8, "rotation": 12.5,
  "scaleVelocity": 0.9, "rotationVelocity": 30,
  "startLocation": { "x": 100, "y": 80 }, "startAnchor": { "x": 0.5, "y": 0.4 },
  "location": { "x": 130, "y": 95 } }

scale is the distance between the two fingers over the distance when the second came down; rotation is the turn of the line between them since then, in degrees, clockwise positive and unwrapped past a half turn; velocities are per second over the last 100 ms. startLocation is the fingers' first midpoint in the element's points, startAnchor the same as a fraction of its size. location is the midpoint now, which SwiftUI's values leave out (React's PinchValue.location), so two fingers can pan as they zoom; a trackpad pinch keeps its start, and a renderer that cannot tell (the native one before iOS 18) omits it. The gesture began once the scale has moved minimumScaleDelta (with magnify) or the angle minimumAngleDelta (with rotate); changed follows once per animation frame, and lifting either finger sends ended (cancelled when the browser cancels a pointer). A pinch that never reached its threshold sends nothing.

Renderer details (src/pinch.ts): two touch or pen pointers on the element drive it, and the element has touch-action: none, so the page neither scrolls nor zooms under it. A trackpad pinch drives a magnify gesture too: Chrome, Edge and Firefox report it as wheel events with ctrlKey (each pixel of deltaY scales by e^-0.01; the gesture ends 150 ms after the last one), Safari on a computer as gesturestart / gesturechange / gestureend (scale and rotation). The page's own zoom is prevented in each case. A mouse alone cannot pinch. The single-pointer behaviours of the same element (a drag) run beside a pinch, as SwiftUI's simultaneous gestures do.

Swift: MagnifyGesture.Value has magnification, velocity, startAnchor, startLocation (and time, the moment the event arrived); RotateGesture.Value has rotation, velocity, startAnchor, startLocation. began and changed run onChanged (and updating), ended and cancelled run onEnded. Headless: pinch:7:changed:1.5, or pinch:7:changed:1.5@30 with a rotation of 30°.

allowsHitTesting(false) is the style hint hitTesting: false: the subtree gets pointer-events: none.

Hit testing follows SwiftUI's: a stack, spacer, geometry, grid, layout, viewthatfits, decorated, gesture / tapgesture wrapper or a plain styled box is not hit in its empty space (the pointer reaches whatever is under it, as a full-screen VStack { Spacer() } overlay never blocks the cards beneath it in Flashzilla); content is hit: text, images, shapes, colors, controls, rows, and a styled whose style paints a background. The renderer implements this with pointer-events: none on the containers and an opt-in on their children (styles.css), so an inert subtree (hidden, disabled, hitTesting: false, a popping screen, exit clones, a dismissing sheet or alert, a hidden tab) is blocked by an explicit descendant rule.

Swipe actions: swipeactions#

Wraps a list row's content. A horizontal pan on the row (by pointer, or a horizontal wheel/trackpad scroll) slides the content aside and reveals the actions of that edge as full-height colored buttons, 74 pt wide each, text (and symbol, stacked) in white, in a row behind the content: trailing actions on the right with the first declared action nearest the content, leading on the left. Tapping an action sends tap with the button's id and closes the row. Pulling past the actions' total width plus 60 pt with full swipe allowed performs the first declared action of that edge (its tap) and closes the row. Tapping anywhere else, scrolling, or another row opening closes the open row with the slide animation. Outside a list the element is transparent. A row with onDelete (below) and no swipeActions behaves like one with a single trailing destructive "Delete" action that sends delete instead of tap. Several .swipeActions on one row accumulate into one element (trailing actions in declaration order, then leading ones); the per-edge allowsFullSwipe is the last one declared for that edge. The actions are flattened like a menu's items, so trailing + leading equals the number of children after the content; the renderer finds each action's button by looking through its styled wrappers (that is where a .tint lives). When a row has both swipeActions and onDelete the listrow wraps the swipeactions element.

Renderer details: the action button children are never laid out (they are in hidden, like a menu's items); when a row starts to open the renderer builds the buttons from the current children (title from their text, symbol from their first image, destructive role → red, a tint on the button or its styled wrapper → that color, otherwise gray). The content follows the pointer 1:1 up to the actions' total width, then with resistance (no further than the row width), and the button nearest the content stretches past the total width. On release the row opens when the content is past half the actions' width or flung open faster than 300 pt/s, closes otherwise; fullSwipeTrailing / fullSwipeLeading default to true. A tap outside an open row closes it and is swallowed (nothing under it fires). A horizontal wheel sequence settles 150 ms after its last event with the same rules.

Context menus: contextmenu#

The content is laid out alone; the items are hidden inline, like a menu's. A long press (0.5 s) or a right click on the content opens the same popover a menu opens, anchored to the content, with the items as rows; choosing one sends tap with the item's id. The browser's own context menu is suppressed on the subtree, the long press swallows the click that follows it, and the long press is cancelled by moving 10 px (so the row still scrolls or swipes).

Edit mode and list selection: listrow#

Swift wraps a List row in a listrow when it can be selected (the list has a selection: binding and the row carries a .tag, or is a NavigationLink(value:) in a List(selection:)) or deleted (its ForEach has .onDelete). The row's list carries editing (from EditButton / the editMode environment). Rows are the list's direct children and the children of its sections; the wrapper takes over the row's identity (its ForEach key), and a row that is neither selectable nor deletable is emitted bare, as before. A listrow whose content is a swipeactions is the swipe host itself: the whole row slides and the actions sit at the row's edge (the swipeactions wrapper also spans the row's width in the layout, so a pan anywhere on the row starts the swipe). A ForEach id is a row's implicit tag, as in SwiftUI, so List(items, selection:) needs no .tag; a tag (or link value) counts only when it is of the selection's value type (Set<V> or V?). A tag below styled, swipeactions, contextmenu, gesture or tapgesture wrappers still marks the row. .deleteDisabled(true) makes a row not deletable. A row whose ForEach has .onMove is movable unless .moveDisabled(true); see "Reordering rows" below.

The editMode binding comes from the nearest navscreen (each screen owns its own mode, as on iOS), or from the List itself when no screen encloses it (a list in a sheet or a plain root); an app-supplied .environment(\.editMode, $mode) below either wins. EditButton sets the binding to .active / .inactive and shows "Done" / "Edit".

A tap on a listrow: for a NavigationLink(value:) row that is not editing, Swift does what a tap on the navlink does (push, or select in a split-view sidebar); otherwise a Set selection toggles the value, a V? selection sets it, or toggles it (deselects on a second tap) while editing. delete on a deletable row calls its ForEach's onDelete with the row's offset in the ForEach's data (one offset, computed from the row's position among the ForEach's children, so it is right after earlier removals).

  • Not editing: a selectable row with a single-value selection sends tap on its id when tapped (Swift sets the selection; the row shows selected with the Phase 7 selected-row fill). A multi-selection list ignores taps. A deletable row swipes to delete (see swipeactions).
  • Editing (list.editing): every selectable or deletable listrow gains a 44 pt leading control, 6 pt in from the card's edge (its 22 pt circle is centred 28 from the edge, as iOS draws it), and its content shifts right by 40 with the list's animation: a selection circle for selectable rows (filled accent with a white checkmark when selected; a tap sends tap on the row id and Swift toggles the selection), a red minus circle for deletable rows that are not selectable (a tap slides the content to reveal a trailing "Delete" button; tapping it sends delete). EditButton itself is a button whose title Swift flips between "Edit" and "Done" (with editMode on the op, see "button props").
  • delete is sent with the listrow id; Swift maps it to the row's offset in its ForEach and calls onDelete with an index set of one.
  • Renderer details: the listrow is transparent for layout and keeps the list-row context (a navlink inside it still gets its chevron; badge / listRowInsets on a styled inside it still apply). In edit mode the engine proposes the row content 40 less width and reports the control as the row's editControl chrome (44 × row height, 6 in from the card's leading edge); the shift animates with the commit like any frame change. Swift emits the listrow as the row's outermost element (the row modifiers inside it): the row clips to its box, so a styled wrapper around a listrow would clip the control. A tap on a selectable row sends tap with the row id whether or not the list is editing (inner controls still win the tap); a non-selectable row sends nothing on a plain tap.

Reordering rows#

Swift marks a listrow movable: true when its ForEach has .onMove and the row is not .moveDisabled (the prop is left out when false, so earlier snapshots hold). onMove alone is enough for the wrapper: a row that is movable and neither selectable nor deletable is still a listrow.

The renderer lifts a movable row two ways:

  • Editing (list.editing): the row gains a 44 pt grip at its trailing edge, 6 pt in from the card like the leading control (three 21 pt lines 1.33 thick and 4.67 apart in the tertiary label color, centred 28 from the edge, as iOS draws them; the engine proposes the content 40 less width and reports the grip as the row's reorderControl chrome, beside editControl when the row is also selectable or deletable; a row that is only movable keeps its content where it was). A pointer down on the grip owns the pointer at once. The grip sits in the row's content slot: when the minus (or a swipe) reveals Delete it slides aside with the content, while the minus stays and stands upright, as on iOS.
  • Not editing: a long press (0.5 s without moving 10 px) on the row lifts it, as iOS does; a context menu inside the row wins the press.

While lifted the row follows the pointer up and down with a shadow above its neighbours, which slide out of its way by its height; a pointer within 40 pt of the list's top or bottom edge scrolls the list. The row cannot leave the run of movable rows around it in its card (a section's rows, or the loose rows of the list): that is its ForEach. Letting go slides the row into its slot (0.3 s) and then sends move:

{ "type": "move", "id": 31, "to": 2 }

to is the index, among the row's container's children (the list's, or its section's, view headers and footers included), of the child the row now goes before, counted in the order before the move (0 ... the child count, as move(fromOffsets:toOffset:) takes its destination). A drag that ends in the row's own slot sends nothing. Swift maps to to the ForEach's data: the destination is the number of the group's rows before that child, so a drop among a section's other views, or before its header, still lands at the right offset, and calls onMove with an index set of the row's offset. The ForEach re-renders in the new order (a keyed move, no new elements); the rows' slid positions coincide with the new layout, so nothing jumps. An onMove that leaves the data alone puts the rows back.

Headless: move:"Coffee":2 (the child index) or move:"Coffee":"Lunch" (before the row showing that text). A destination that names no row on screen is an error.

Alerts and dialogs: alert#

A root-level element (a child of id 0) like sheet, placed after the tree. style: "alert" draws an iOS 26 alert: a dimming scrim, a 320 pt wide Liquid Glass card (--sb-alert-card, white at 70% in light mode, over a 60px backdrop blur, with the glass rim, 34 pt radius, a soft shadow) with the bold title, the message below it in the secondary color, both left-aligned, and the buttons: gray capsules (--sb-color-fill) in the label color, two side by side (a cancel one first, on the left), otherwise stacked; destructive is red, and cancel is not bold in an alert. style: "dialog" draws an action sheet: the buttons (accent, destructive red) in a bottom card above a separate bold cancel button, the title (and message) as a dim caption on top (Swift sends an empty title unless titleVisibility is .visible, as iOS hides it by default; an empty title and null message mean no caption). A button tap sends tap with the button id (Swift runs the action and dismisses); a tap on the scrim of a dialog, or on an alert with no buttons, sends tap with the alert's own id (dismiss). Both appear with a 0.25 s fade (alert: scale from 1.1) and leave with a fade. An alert above a sheet covers the sheet.

Geometry (engine chrome: card, title, message, button<i>, ok, cancelCard; chromeText: the title / message lines, leading-aligned in an alert and centered in a dialog). The scrim is 20% black (46% in dark mode, as iOS 26 dims), the cards Liquid Glass (a translucent fill over a 60px backdrop blur, with the glass rim); the layer never scales with the presenting tree behind a large sheet. alert: the card is 320 wide (narrower only on a screen under 336), vertically centered in the safe area; the title is headline (17 semibold) and the message subheadline (15), inset 21 from the top and 30 at the sides and 6 apart, then 20 above the buttons; every button is a 46-high capsule inset 16 from the card's sides, two buttons share one row (140 each, 8 apart, a cancel one first), one or three and more stack in order 8 apart, none gives a renderer-drawn "OK" capsule; 16 below the last button. The scrim of an alert that has buttons swallows the tap (modal). dialog: the button card and the cancel card are inset 8 from the screen sides; the cancel card is 57 high and ends 8 above the bottom safe area, the button card 8 above it (no cancel child: the button card sits there itself); rows are 57 high with 20 pt labels, in declared order without the cancel; the title (footnote semibold) and message (footnote) are a secondary-color caption inset 14 top and bottom and 16 at the sides (absent when both are empty, so the first row is flush with the card top). A button child gets its row as its frame with the label centered (a cancel label is measured semibold in a dialog, regular in an alert); a tap on it is an ordinary tap.

Controls#

  • stepper: the label leads; a 94 × 32 pt minus/plus capsule trails (--sb-color-tertiary-fill, 16 pt radius, a short --sb-color-opaque-separator divider 7 pt from the top and bottom); a disabled half (canDecrement / canIncrement false) is dimmed (35%) and swallows taps. A tap sends step with −1 / +1; Swift applies step within in and emits the new label. Like a toggle: the label is proposed the width minus 94 + 8, the height is max(label, 32), the width is the proposal or label + 8 + 94 (engine chrome: label, control, decrement, increment).
  • slider: 6 pt track (--sb-color-tertiary-fill) with the accent fill from the minimum to the thumb, a 38 × 24 pt white shadowed pill thumb (iOS 26); width = proposal (200 when nil), height 31. The label child is not drawn, as iOS draws no slider label (SwiftUI keeps it for accessibility): it is hidden and names the slider (aria-labelledby); an app that wants a title shows a Text beside the slider. The min / max value labels sit 8 from the track's ends, vertically centered in the 31 row (SwiftBrowser Native draws them with Slider(…minimumValueLabel:maximumValueLabel:)); the thumb's center travels from 19 after the track start to 19 before its end, so the thumb stays inside the track (engine chrome: track, fill, thumb). Dragging or tapping anywhere on the slider sends slide continuously (coalesced per frame, the thumb follows at once) with the value in min…max, snapped to step (to the nearest multiple from min, with the step's decimals; six decimals without a step); Swift confirms with value. The drag's first slide carries editing: true and, on release, one more carries the last value with editing: false (onEditingChanged, so a scrubber can stop following a position while the thumb is held); the values between carry no editing. Without labels all children are ignored.
  • datepicker: compact style. The label leads; one or two capsule buttons trail (--sb-color-tertiary-fill, 8 pt radius) showing the date ("Oct 3, 2026") and/or the time ("7:00 AM") formatted by the renderer in US English from seconds in timeZone (the viewer's zone when absent; an unknown name reads as UTC). Each capsule is its text (body font) plus 11 at each side, 34 high; two capsules are 8 apart and the label is proposed the width minus the capsules and 8; the width is the proposal or label + 8
    • capsules (engine chrome: label, date, time). labelsHidden: true drops the label child from the layout. Tapping one opens the browser's native <input type="date"> / <input type="time"> picker (an invisible input over the capsule); a change sends date with the combined seconds: the changed component replaces its part of seconds (day, or hour and minute) read in that zone, and the other part is kept; seconds within the minute are dropped. min / max bound the native date input; the time input only when they fall on the shown day.
  • texteditor: a <textarea> filling the proposal (nil height → 100, nil width → 200, flexible on an infinite axis like a shape), body font, no border (its parent provides the frame); input sends text like textfield, and an update with the same text leaves the caret alone.

Pull to refresh#

A list or scrollview with refreshable lets a pull past 60 pt at the top (by touch or wheel) send refresh; the renderer shows a spinner row of 40 pt above the content while refreshing is true (Swift sets it before running the action and clears it after). .refreshable is an environment hint the nearest List / ScrollView below it reads; a refresh that arrives while refreshing is ignored. The action runs as a Task on the host executor, so the clearing update arrives on a later sb_run_jobs.

Renderer details: the pull is read from the pointer (a mouse drag at scrollTop 0, the content following with resistance and the spinner fading in), from touch moves (the browser cancels the pointer once the scroller scrolls, so touches are read directly), and from an upward wheel at scrollTop 0 (a sequence ends 300 ms after its last event). Each pull or wheel sequence sends refresh at most once, on reaching 60 pt (the pointer pull sends on release). While refreshing the content is translated down by 40 (an iOS content inset: the last 40 pt scroll under the viewport edge) and the spinner row sits at the top of the scroller.

styled style (added fields)#

field meaning
rotation3D: { "angle": degrees, "axis": { "x", "y", "z" }, "anchor": UnitPoint, "perspective": number } .rotation3DEffect: CSS perspective(500px / perspective) rotate3d(x, y, z, angle) about anchor (default center); perspective default 1 → perspective(500px) (a fixed distance, not scaled by the box). A zero angle or axis is the identity. The transform list is translate(offset) rotate(rotation) perspective() rotate3d() scale(scale) (CSS applies it right to left: scale, 3D turn, 2D turn, offset); one transform-origin: rotationAnchor, else rotation3D.anchor, else scaleAnchor
blur: number .blur(radius:): filter: blur(<radius>px) on the box; a shadow is cast by the views it draws, not in this filter (see shadow); 0 is the identity
hitTesting: false .allowsHitTesting(false): pointer-events: none on the subtree
ignoresSafeArea: "all" | ["top", "bottom", "leading", "trailing"] the engine extends the styled box to the screen edge on each listed side when the box's edge is at (or inside) the inset band it must clear: the safe area at the root, a navscreen's bar (plus large title) inside one, the tab bar under a tabview. The parent's layout is unaffected (the box reports its unextended size). A child whose size changes under the grown proposal (a color, gradient, shape, resizable image, a stack of them) is proposed the grown box and fills it, so Image.resizable().ignoresSafeArea() and RadialGradient.ignoresSafeArea() bleed under the (transparent) navigation bar, whose items stay on top; a child whose size does not change (a fixed frame) stays where the parent put it and the extension shows the box's own background only
backgroundIgnoresSafeArea: "all" | ["top", "bottom", "leading", "trailing"] .background(_:ignoresSafeAreaEdges:) and .background(ignoresSafeAreaEdges:): the edges on which the box's background paint runs on to the screen edge where the box touches the safe area, by the same test as ignoresSafeArea (the safe area at the root, a navscreen's bar inside one, the tab bar under a tabview). Only the box's frame grows, so its CSS background paints the band: the parent's layout, the child's proposal and its position are unchanged, and a tinted header colors the status bar above it while its text stays below. Absent means every edge, SwiftUI's default, so the shim writes it only for another set; [] keeps the paint in the box. Not in a list row (a cell does not pass the safe area to its content), and not for a box that also rounds, clips, masks, rotates or scales what it draws
ignoresKeyboard: true .ignoresSafeArea(.keyboard) (and the default .all regions, when the edges include the bottom): the on-screen keyboard. In device mode, while a field is being edited, the page measures the keyboard (the layout viewport's height less the visual viewport's, src/deviceMode.ts; the browser's pan to the field is undone, not subtracted) and the engine takes it as a bottom safe-area inset, as iOS does: a plain root, a navigation screen's content, a tab's content and a sheet's stop above it, a scroll view that ran to the screen's bottom ends at it (so defaultScrollAnchor(.bottom) keeps a chat's last line in view), and the tab bar or bottom toolbar under it stays where it is, covered. With this hint the styled box runs down under the keyboard instead (as ignoresSafeArea extends it into the container's insets), and a root carrying it keeps the keyboardless height. .ignoresSafeArea(.container, …) alone leaves the keyboard inset in place

Animation (extended)#

Animation JSON gains "repeat": { "count": number | "forever", "autoreverses": bool } (.repeatCount(_:autoreverses:), .repeatForever(autoreverses:)): the WAAPI iterations (Infinity for forever) and direction: alternate when autoreversing, applied to the style and frame tweens of that commit. Enter and exit transitions of the same commit play once (a forever repeat would never drop the exit clone); a count of 0 or less is ignored.

A pointer that goes down within 24 pt of the leading edge of a navscreen with depth > 0 and moves right drags the screen interactively (the screen below slides from −30% toward 0 and un-dims). Releasing past a third of the width, or with a rightward velocity above 500 pt/s, sends tap with the screen's id (the same pop the back button sends) and the renderer completes the slide; otherwise the screen snaps back. Nothing is sent until release.

A navscreen with backGestureDisabled: true has no swipe back: a pointer that goes down at its leading edge is the content's like any other (a canvas drawn on to the edge, where strokes would otherwise turn into a pop), and its edge strip is not drawn. The back button still pops. It does not reach the browser's own edge swipe below (while the page mirrors navigation in the history) nor, natively, the navigation controller's edge pan.

While the page mirrors navigation in the browser's history (the app page always, an island by default; Web/src/browserHistory.ts) this gesture ignores touch and pen: the browser's own edge swipe is the swipe back, and it reaches the app as a popstate that sends the same tap. A mouse drag from the edge still works as above. Such a popstate also starts the renderer's repaint keep-alive (5 s of tiny repaints, through Safari's 3 s watchdog): Safari hides the live page under the entry's snapshot once its swipe animation ends, until a new frame is committed, and a pop that had finished animating by then would otherwise stay hidden until the watchdog, which also interrupts a touch in progress when it fires on a page that has stopped painting. The browser has animated that pop already, so the renderer does not slide the popped screen out again: it goes at once and the screen it uncovers takes its place without a transition (Renderer.popWithoutAnimation).

Renderer details: the drag starts once the pointer has moved 8 px right by more than it moved vertically (a vertical move leaves the pointer to the list); a pointer down in a text field never starts it. On touch devices a 24 pt strip along the edge owns the touch so the list does not scroll (a plain tap on the strip is forwarded to what is under it); with a mouse the pointer position alone decides. The screen below carries a 12% black dim at rest (--sb-nav-dim, also during push and pop) that fades out with the drag. After the tap the screens stay where the drag left them until the remove arrives: the pop clone then slides from that position (--sb-nav-from) instead of from 0, and the screen below finishes its slide to 0 as the new top screen. Should no remove arrive within 0.7 s the screen snaps back.

A screen draws its own bar (the back and More circles, the glass capsules and the leading / trailing items on them), and slides as a whole, so its bar's items would slide with it. On iOS 26 the navigation controller draws one bar, and through a push or pop the items stay in it: the renderer morphs the bar of the screen that leaves into the bar of the one that arrives (Web/src/barMorph.ts) while the screens slide under it. A capsule both screens have changes shape from the one's to the other's (trailing capsules matched from the trailing edge, leading ones from the leading edge; a capsule with none opposite scales and fades as a bar item does); the leaving screen's items scale and fade out as the arriving screen's scale and fade in, except an item both screens draw the same at the same place, which stays as it is; the back and More circles appear, stay or go. The titles travel with their screens as the content does (the large title with the content it heads, the inline title with its bar).

The morph is an overlay on the navstack element (.sb-navbar-morph, above the screens and the pop clone, taking no input) of visual clones of both screens' bar parts, built from where the parts are at the commit that holds the push or pop (in the frame the slide starts, after the layout has placed the arriving screen's) and dropped when the slide ends; the parts themselves carry data-sb-bar-morph and are hidden meanwhile. Its tweens take the slide's duration and easing (and reduced motion's 0.01 s). A swipe back builds the morph when the drag claims the pointer and moves it with the drag; a release that pops holds it where the drag left it until the remove arrives and then plays the rest over the slide's duration, with the pop clone's slide, and a snap back plays it back to its start. A pop the browser has animated already (Renderer.popWithoutAnimation) has no morph: the uncovered screen's bar shows at once, as the screen does.

Swift notes#

  • DatePicker's selection is generic over _DatePickerValue (seconds since
    1. and ForEach.onDelete / remove(atOffsets:) over _OffsetSet; FoundationLite conforms Date and its own IndexSet (FoundationEssentials has neither IndexSet nor the format styles). _OffsetSet is public protocol _OffsetSet { init(_offsets: [Int]); var _offsets: [Int] { get } } (ascending, unique). The shim also ships _IndexSetLite: _OffsetSet, which onDelete / onMove infer when nothing pins the type (an app without FoundationLite can write .onDelete { items.remove(atOffsets: $0) }); remove(atOffsets:) is on RangeReplaceableCollection and move(fromOffsets:toOffset:) on MutableCollection & RangeReplaceableCollection. onDelete / onMove are declared on DynamicViewContent (ForEach and their own result conform), so they chain as in SwiftUI. Text(_:format:) and TextField(_:value:format:) take a _TextFormat (format and parse); FoundationLite supplies .currency(code:) and .number for Double / Int.
  • AnyTransition.modifier(active:identity:) is accepted and rendered as opacity (the shim cannot diff arbitrary modifiers yet).
  • A TabView renders every tab, so only the selected tab's navigationTitle and .toolbar reach the enclosing (flattened) screen; a NavigationStack of its own inside a tab keeps its own title. Switching tabs re-emits the screen's title and bar items.
  • Headless replay seeds WASI's random_get (SB_SEED, scripts/run-wasi.mjs), so apps that shuffle replay identically; the wasm links with an 8 MB stack (the reconciler recurses once per view).

TypeScript#

src/protocol.ts: DragEvent, LongPressEvent, StepEvent, SlideEvent, DateEvent, DeleteEvent, RefreshEvent, GestureProps, SwipeActionsProps, ContextMenuProps, ListRowProps, AlertProps, StepperProps, SliderProps, DatePickerProps, TextEditorProps, Style.rotation3D, Style.blur, Style.hitTesting, Style.ignoresSafeArea, Animation.repeat, EnvironmentEvent.scenePhase, ListProps.editing/refreshable/refreshing, ScrollViewProps.refreshable/refreshing, SheetProps.detents with "full".

Phase 9: incremental rendering#

Nothing in the wire protocol changes: the ops a commit carries are the same ops a full re-render would have produced. What changes is how little work produces them, on both sides of the boundary.

Swift: dirty-tracked reconcile#

Every _MountedNode knows its parent and carries two flags: dirty (its own state changed) and subtreeDirty (some descendant is dirty). The runtime marks a node dirty, and the chain of ancestors above it subtreeDirty, when:

  • one of the node's own @State / @StateObject boxes is written (each box's _onChange names its owning node);
  • an @Observable property the node's body (or a ForEach's row closures) read is mutated: each body runs under its own withObservationTracking;
  • an ObservableObject the node observes (@ObservedObject, @EnvironmentObject, @StateObject) sends objectWillChange. Publishers keep one subscriber per observing node, so every observer of a shared object re-runs (a weak owner table, pruned on send());
  • the node's editMode or GeometryReader size changes.

_Runtime.invalidate() (no node) still means a full render: the renderer's environment events use it, as does an observable read while producing elements (rare; the element phase runs under a fallback tracker).

A render reconciles from the root with force = fullRender. For a node whose force is false:

  • not dirty and no dirty descendant: it is returned as is, children untouched;
  • not dirty but subtreeDirty: its view value is unchanged, so its body does not run and no reflection happens; its children are the mounted ones (their stored views), reconciled with force = false in turn; the node's own setup (context for its children: navigation stack, screen, environment modifiers) still runs because a dirty descendant may need it;
  • dirty: the body runs and every child is reconciled with force = true (a new view value cannot be compared with the old one, so the whole subtree re-runs).

Per-pass state that descendants fill in while they are reconciled (navTitle / navDisplayMode on a screen, splitSelection on a split, sheetDetents on a sheet) is reset only on a pass that re-ran the node's body; a clean pass keeps what the skipped descendants set last time. A NavigationStack / compact split keeps its _NavContext on the node across passes (detailShown is recomputed only when the split re-runs, and the screens' pop handlers capture it).

Known limit: a .navigationTitle that disappears (an if around it) while its screen is clean leaves the old title; a title that changes value updates.

Swift: cached elements and reconciler short-circuit#

elements(of:) caches each node's output (cachedElements, plus the sheets and alerts its subtree presented, which the element phase collects as side effects). The cache is dropped for every node that re-ran and for every ancestor of a dirty node; clean subtrees return the cached array.

Every _Element carries a token, fresh per produced element and kept by copies. _Reconciler.reuse returns the previous Rendered unchanged when the tokens match: no props comparison, no descent, no ops. Code that derives a modified copy of a child's element must give the copy a fresh token (_hoistBarItems does, and only when it actually removed something).

Web: incremental layout#

LayoutPass persists across commits. The renderer tells it what its ops did:

Op Invalidation
update id by what changed (invalidateProps): the node, its ancestors (sizes may change) and its descendants (context may change); only the node and its ancestors for a styled whose style changed in keys no child inherits (all but font, italic, lineLimit, lineLimitMin, multilineTextAlignment, imageScale, scrollDisabled, defaultMinListRowHeight, ignoresSafeArea); nothing for props set to what they were or a scrollview's scrollOffset alone (carried out after layout); for a navscreen, the whole stack (the next screen's back label)
insert parent id the old and new parents' ancestor chains, the moved subtree
remove id the parent's ancestor chain; the subtree's frames, text, chrome, hidden entries and memo are dropped
environment, fonts, catalog a new pass

Invalidating a node drops its measure memo and its last placement (and those of its implicit stack). Both are keyed by the proposal and the container (containerRelativeFrame): the screen, or inside a scroll view its viewport, which is the scroll view's own proposal, so a page sized by the container is measured again for each width the scroll view is tried at. place(node, proposal, x, y) returns immediately for a node placed before with the same proposal and container at the same origin whose last placement survived: the whole subtree's frames, chrome and text are still right. Everything a run places, hides or drops is collected in LayoutResult.changed; applyLayout visits only those ids (plus the renderer's dirty set of elements whose inline style was reset) and keeps its box map across runs. hidden entries are owned by the node that added them and cleared when that node is placed again; a node's chrome from an earlier run is dropped when it is placed again (a parent's row / badge set in the same run just before is kept). LayoutPass.stats counts placed and skipped nodes per run; Web/e2e/perf.spec.ts (SB_PERF=1) is the probe.

Measured on Food Truck's Truck screen (header at 20 fps, 733 elements) in headless Chromium: Swift per tick ~24 ms → ~2 ms; renderer per commit ~5 ms → ~1.5 ms; main thread busy ~36% → ~6%; the timer reached its 20 fps.

Phase 10: bring your own app#

The protocol is unchanged. What this phase adds sits around it:

  • @swiftbrowser/web exposes the renderer and dev server to other packages through an app registry (AppSpec: name, display name, the wasm path, the asset catalogs, the directories to watch and a build hook) and two calls, createDevServer(options) and buildSite(options). The examples run through the same registry (Web/node/examples.ts); Web/vite.config.ts is a thin use of it. The landing page reads __SB_APPS__ (name, display name, description, optional icon) instead of the old example list.
  • @swiftbrowser/xcodeproj reads project.pbxproj (old-style plist) into targets with their Swift sources (navigator order), resource files, asset catalogs, build settings and package products, including Xcode 16 synchronized folders and their exception sets. No Xcode needed.
  • @swiftbrowser/cli stages a project into <project>/.swiftbrowser/<Name>/: a SwiftPM package depending on @swiftbrowser/swift by path, whose one executable target is a copy of the app's sources with three line-preserving adjustments (import SwiftUI also imports FoundationEssentials + FoundationLite, as Apple's SwiftUI re-exports Foundation and Combine; import Foundation becomes those two in lean mode; #Preview blocks are blanked) and SWIFTBROWSER defined. Diagnostics are mapped back to the user's files. check compiles natively (same errors, seconds), dev and build for WebAssembly.
  • Shim additions driven by running the Hacking with SwiftUI projects in place: _Publisher + View.onReceive(_:perform:) (a task that subscribes while the view is shown), and in FoundationLite Timer.publish(every:on:in:).autoconnect(), Timer.scheduledTimer, RunLoop, and an in-memory UserDefaults.

Foundation, measured (wasm-opt -Os, stripped): import Foundation costs nothing while unused, about 42 MB (36 MB of ICU data, 17 MB gzipped) as soon as any symbol of it is referenced, because CoreFoundation's initialization pulls FoundationInternationalization in; FoundationEssentials costs about 4 MB. Hence lean mode by default and --foundation full as the escape hatch.

Trimmed ICU data for full Foundation (packages/cli/src/icu.ts). The SDK's lib_FoundationICU.a has one data object, icu_packaged_data.cpp.obj, whose single wasm data segment is ICU 76's complete common-data package (icudt76_dat, 34.0 MB, format "CmnD": a UDataInfo header, a table of (nameOffset, dataOffset) pairs, NUL-terminated names, 16-byte-aligned items; 4,855 items, of which locale resource bundles in ten directories, collation tables, converters, break-iteration rules and dictionaries). icupkg from a host ICU refuses the file (ICU 76's name table is longer than ICU 74's limit), so the CLI parses the ar archive, the wasm object and the CmnD table itself. It keeps root.res, every item that is not a locale bundle (string pools, supplementalData, likelySubtags, time zones, ucadata.icu and root collation, unames.icu, the .brk rules, normalization data, small converters) and the bundles of the configured languages ("locales", default ["en"]), and drops the other languages' bundles in every directory, translit/, the .dict word-break dictionaries (cjdict.dict alone is 2 MB) and converters of 16 kB and more. English: 1,016 items, 5.6 MB; each further language 100 to 300 kB, Chinese 1.7 MB. A dropped locale falls back to root formatting at run time.

Replacing the data at link time was the hard part. wasm-ld's --wrap only handles functions (symbol type mismatch for a data symbol); --allow-multiple-definition keeps the first definition, which is the archive's because the swift driver hoists the SDK's -L ahead of any user search path and puts -Xlinker inputs after the autolinked -l flags; a -L with a modified archive copy loses for the same reason. What does precede the archives on the link line is every target's object files, so the staged package gets a C target _ICUData with one assembly file (#ifdef __wasm__ around a .globl icudt76_dat, .p2align 4, .incbin of the trimmed package from ~/.cache/swiftbrowser/icu/<key>/). Its object defines the symbol before the linker reaches lib_FoundationICU.a, so the archive's data member is never pulled; the SDK is untouched and a host check build assembles an empty file. Result on the probe app (DateFormatter, NumberFormatter, JSON, URLComponents, format styles): 46.7 MB → 19.2 MB optimized (code 10.7 MB, data 8.2 MB), 18.5 MB → 6.6 MB gzipped, identical output in the headless harness.

Phase 11: the real Foundation by default#

The protocol is unchanged. The CLI's default Foundation mode flips from lean (FoundationEssentials + FoundationLite) to full (the wasm SDK's swift-corelibs Foundation with trimmed ICU data), because every Foundation API then compiles as on iOS and the cost, measured on Counter with wasm-opt -Os, is 18.3 MB raw / 6.7 MB gzip / 4.6 MB brotli against 4.5 / 1.7 / 1.2 MB lean. Compile time in Chromium is not the issue (90 ms for the full module, 164 ms with the CPU throttled 4x); transfer is. Lean stays as --foundation lean.

Where the 10 MB over lean-with-Essentials goes (linker map, before wasm-opt): ICU code 2.0 MB, corelibs Foundation 1.7 MB, FoundationInternationalization 1.0 MB, CoreFoundation 0.6 MB; ICU data 4.7 MB plus 1.5 MB of their data segments. The ICU data compresses 5:1 (4.7 MB → 1 MB brotli), so dropping more of it barely moves the download; the two drops made here (the CJK / phrase / loose / normal line-break rule variants, reached only through the Japanese and Chinese bundles, and unames.icu behind the \N{…} regex escape) take the English package from 5.6 to 4.7 MB raw. Converters (0.55 MB), language and region display names (0.3 MB) and collation (0.94 MB) would be the next candidates, each breaking a Foundation API when missing, so they stay.

Coexisting with the real Foundation. The shim never imports Foundation: on wasm its modules are whole-module objects, so a single reference to CGSize would link Foundation, CoreFoundation and ICU into every lean app. Both therefore declare CGFloat, CGPoint, CGSize and CGRect, and an app importing both gets "ambiguous use" (verified on the host: Swift has no shadowing between two imported modules, even when one imports the other; it only lets the current module shadow imports). So the CLI generates _SwiftBrowserFoundation.swift into the staged app with public typealiases pointing the four names at the shim's types (what frame(width:) and the layout protocol take; public so the app's own public API may use them) and Timer / RunLoop at FoundationBridge's.

What corelibs Foundation lacks on WASI, found by probing the SDK: RunLoop is marked unavailable, Timer compiles but does not link (CFRunLoopTimerCreate and friends are undefined), Timer.publish is Combine's, Bundle.main traps at first use, NotificationCenter's closure observers and OperationQueue are absent, AttributedString(markdown:) is absent. Working: UserDefaults (in memory for the run), Locale.current (en_001), TimeZone.current (GMT), DateFormatter, NumberFormatter, NSRegularExpression, Measurement, AttributedString, String(data:encoding:), IndexSet, localizedCaseInsensitiveContains.

FoundationBridge (Sources/FoundationBridge, a product of the package and of @swiftbrowser/swift) is the full-mode counterpart of FoundationLite's glue: IndexSet: _OffsetSet, Date: _DatePickerValue, Text(_:format:) for any FormatStyle with string output and TextField(_:value:format:) for any ParseableFormatStyle (through a _TextFormat adapter and a new public TextField(_placeholder:value:format:) on the shim), and Timer + RunLoop with publish(every:on:in:) and scheduledTimer(withTimeInterval:repeats:block:). The timer logic moved into the shim as _IntervalPublisher<Output> and _ExecutorTimer, which FoundationLite and FoundationBridge both wrap with Date; a scheduled timer now stays alive until it fires (FoundationLite's used to hold itself weakly, so an unretained Timer.scheduledTimer never fired).

Staging in full mode: import SwiftUI → import SwiftUI; import Foundation; import FoundationBridge; import FoundationLite → import FoundationBridge (the examples' #if canImport(FoundationEssentials) branch); import FoundationEssentials stays (Foundation re-exports it); the generated typealias file; the _ICUData target. check (a host build) works the same way, with the host's Foundation. In a repository checkout the root package also declares the example executables, whose names a staged example app shares, so scripts/full-foundation-examples.sh uses the published layout of @swiftbrowser/swift (node packages/swift/sync-sources.mjs) and builds every example in full mode, running each headless with its snapshot events as a smoke test (formatting differs from FoundationLite's, so no op-stream diff). All six examples and the Hacking with SwiftUI projects that compile in lean mode compile and run in full mode; Flashzilla's countdown ticks through the bridge's timer.

Phase 11 additions: the viewer's locale, saved defaults, the resource bundle#

Locale and time zone. The page passes TZ (from Intl.DateTimeFormat().resolvedOptions().timeZone) and SB_LOCALE into the WASI environment at launch. corelibs Foundation honors TZ on WASI as is, but its CoreFoundation layer (ISO8601DateFormatter, a DateFormatter with a calendar, NSCalendar) reads the zone as a TZif file under /usr/share/zoneinfo and traps when there is none, which in any zone but GMT stopped the first date formatting (Ice Cubes' ServerDate, TelemetryDeck). The page mounts /usr/share/zoneinfo read-only with every zone the browser knows, each file made from Intl when the app first opens it (Web/src/zoneinfo.ts: the offsets from 1970 to 2037 and their abbreviations, TZif version 1). The headless runner mounts the host's directory. The locale is chosen by Web/src/locale.ts: the first of navigator.languages whose language the module ships (AppSpec.locales, "locales" in swiftbrowser.json, default ["en"], "*" for all), kept with its region (en-GB); else the first shipped language; ?locale= on the app URL overrides. Clamping matters because a locale without data falls back to ICU's root formatting (2023 M11 14 23:13). On the Swift side swift-foundation has no hook: LocaleCache.preferences() returns a hard-coded en_001 under NO_CFPREFERENCES and reads no environment variable. The one call to it (from _currentAndCache) survives as a relocation in the SDK's Locale_Cache.swift.obj, so the staged full-mode package links with --wrap=$s20FoundationEssentials11LocaleCacheV11preferencesAA0C11PreferencesV_SbtyF (and the same for the static Locale.preferredLanguages getter), and FoundationBridge/Locale.swift defines the __wrap_ symbols: a class method (Swift passes self in its own trailing parameter on wasm, and the cache pointer must land there; a struct method or a free function has a different arity, which the wasm validator rejects at instantiation) returning a struct that mirrors LocalePreferences field for field (60 bytes on wasm32; the caller reads doCache at that offset) with locale / languages from SB_LOCALE. This is tied to the SDK's swift-foundation, which the CLI pins and CI exercises (French formatting in a full-mode build). Verified: fr-FR gives Locale.current.identifier == "fr_FR" and € 3,50-style output once the fr data is shipped; en-GB gives 14 November 2023 at 22:13. Lean mode keeps FoundationLite's US English.

defaults op (Swift → host): {"op": "defaults", "values": {…}}, the whole UserDefaults dictionary after every change, emitted through the render host like any op (headless prints it). The loader (Web/src/wasm.ts) takes the last one of a batch out before the renderer sees the ops and hands it to the page, which stores it in localStorage["sb-defaults:<App>"]; at the next launch the page passes it back as SB_DEFAULTS. Values: strings, booleans, numbers (whole numbers come back as Int), arrays, dictionaries, Data as {"$data": base64}, Date as {"$date": seconds}, URL as {"$url": string}. register(defaults:) values are fallbacks and never saved. One UserDefaults for all suites.

Resource bundle. AppSpec.resources (the CLI fills it from the target's Copy Bundle Resources, minus asset catalogs and what Xcode compiles: storyboards, Core Data models, .strings, Info.plist; or "resources" in swiftbrowser.json) is published by Web/plugins/bundle-resources.ts as /bundle/<App>.json ({files: [{path, size}]}) plus /bundle/<App>/<path>, a file under its base name, a folder with its structure. Before loading the module the page fetches them all and mounts them read-only at /bundle (a PreopenDirectory of @bjorn3/browser_wasi_shim, fd 3), where WASI libc resolves paths, so Data(contentsOf:), FileManager and String(contentsOf:) work unchanged. _FoundationCommon.Bundle answers main, url(forResource: withExtension:), path(forResource:ofType:inDirectory:), urls(forResourcesWithExtension:subdirectory:), bundlePath / bundleURL / resourceURL (SB_BUNDLE_PATH, default /bundle), bundleIdentifier (SB_BUNDLE_ID) and an infoDictionary with the app's name (SB_APP_NAME); localizedString looks the key up in the app's string tables ("Localized strings"). The headless runner mounts SB_BUNDLE_DIR at /bundle through Node's WASI preopens. The asset catalog's files join the mount in its Assets.car folder ("Asset catalog files for Swift").

_FoundationCommon is the new shared target: UserDefaults and Bundle written against FoundationEssentials (whose types the full Foundation re-exports), re-exported by FoundationLite and aliased by FoundationBridge (and again by the generated _SwiftBrowserFoundation.swift, so they shadow corelibs Foundation's in the app).

Phase 12: the rest of the Hacking with SwiftUI list#

Phase 12 re-ran check over the nineteen Hacking with SwiftUI projects and closed the shim gaps that stopped the ones no framework stands in front of. Twelve now compile and run unchanged (1, 2, 3, 5, 6, 7, 8, 9, 15, 17, 18, 19); the other seven need Core ML, URLSession/AsyncImage, SwiftData, Core Image, PhotosUI, StoreKit, MapKit, Core Location or Local Authentication.

Focus and submit. @FocusState wraps a State, and .focused($field) / .focused($field, equals:) put an _FocusRequest in the environment that TextField and SecureField read: the textfield element gains "focused": true|false on every pass, and the renderer calls focus() / blur() after commit so the DOM follows the state (syncFocus). The reverse direction is a new whole-event handler: focusin / focusout on a text field send {"type":"focus","id":N,"value":true|false}, which the runtime routes to the field's handler and which sets or clears the focus state. .onSubmit marks the field with "submit": true; Enter in such a field sends {"type":"submit","id":N} and the handler runs the closure (SubmitTriggers is accepted and ignored). .submitLabel(.go) etc. emits "submitLabel", which becomes the input's enterKeyHint. Handlers that need the environment implement _EnvironmentHandling and are assigned after the environment modifiers have been applied.

Text input hints. .keyboardType(_:), .textContentType(_:), .textInputAutocapitalization(_:) and .autocorrectionDisabled(_:) are environment modifiers for the text fields below, which carry them as "keyboard" (the UIKeyboardType case name; nothing for .default), "contentType" (the UITextContentType name), "autocapitalization" (never, words, sentences, characters) and "autocorrectionDisabled": true. The renderer sets the input's inputmode (emailAddress → email, URL → url, numberPad → numeric, decimalPad → decimal, phonePad → tel, webSearch → search; other keyboards leave it unset), autocomplete (emailAddress → email, oneTimeCode → one-time-code, newPassword → new-password…; off without a content type, as before), autocapitalize (never → none) and autocorrect="off". As on iOS, an email keyboard alone still capitalizes: write .textInputAutocapitalization(.never) too. The native renderer applies the four as SwiftUI's modifiers (docs/native.md, "Controls").

Preferred color scheme. .preferredColorScheme(.dark) is an environment modifier (_PreferredColorSchemeModifying) that the runtime notes while mounting the active tree (inactive tabs don't count). When the preference differs from the one last sent, render() prepends {"op":"update","id":0,"props":{"colorScheme":"dark"|"light"|null}} for the root; the renderer turns that into an sb:color-scheme DOM event and the page applies the theme without persisting it (null returns to the stored or system theme).

Scroll targets. .scrollTargetBehavior(.viewAligned | .paging) on a ScrollView emits "snap": "viewAligned" | "paging" and .scrollTargetLayout() on the stack inside it emits "scrollTarget": true on that hstack / vstack only (the modifier is consumed by the first _ScrollTargetContainer below it). The behavior is the first scroll view's below the modifier and not the scroll views' inside that one, as on iOS (scripts/scroll-probe asks the simulator: under .paging on a pager alone, its pages that scroll down do not page). CSS does the rest: scroll-snap-type on the scroll view and scroll-snap-align: start (or center for paging) on the children of the target layout. Under a finger a paging view pages as a UIScrollView with paging does (Web/src/touchPaging.ts): touch-action keeps the browser off its axis, on the view and on everything inside it (a button's manipulation would let Safari pan the view under a quick swipe that starts on it), and a drag of ours cancels its touch moves from the first move that decides its direction, 3 px in: Safari pans a scroll view under a finger regardless, and a move left to it begins a pan after which it cancels the touch for the page), the page drives the offset 1:1 with the finger (the snap turned off meanwhile, as a snapping container snaps every offset it is given), and at the lift runs it, eased, to the page pagingDestination chooses, writing every frame to the end (only an app's own scrollTo command ends the run early; a drag in progress carries on across such a command, the page under the finger found again after it and the offset moved by what it moved, so an app re-centring its pages on the one arrived at leaves the content under the finger where it was): one page on in the direction of a flick (0.3 px/ms over the finger's last 100 ms) however short the drag, else the nearest page (half a page across is the next); inside a page longer than the viewport a flick runs on with its momentum, to the page's edge at most. The pages are the target layout's children; without one, the content's children when it has several, else the viewport's length after length, as SwiftUI's .paging turns a scroll view whose content is one stack. Wheel and trackpad scrolling stay native, snapped by CSS. .scrollBounceBehavior is an accepted no-op.

What takes a finger's drag itself inside a paging view keeps the touch, as a gesture recognizer or a control inside a paging UIScrollView does (ownsDrag): a gesture element that drags and is not simultaneous (the renderer writes its mode as data-sb-gesture-mode; one switched off by its mask has no drag), a touches element, a slider, a list row's reorder grip and, across a horizontal pager, a row with swipe actions. The page does not start a drag of its own on them, and their touch-action: none holds inside the pager too, so the browser does not pan across the paging axis under them and cancel the gesture. A scroll view (or list) inside that scrolls along the paging axis has the drag while it can still go that way: the browser pans it (touch-action allows both axes inside it), and the pager takes a drag that starts with it at that end. Where paging views are nested, a drag is the one's that pages its way (pagerFor): across pages that page down it turns the pager around them, and along a paging strip inside a page it scrolls the strip until that is at its end, then turns the page.

.scrollClipDisabled() emits "clipDisabled": true on the scroll views below it. A horizontal-only one then draws its content past its sides, as far as the screen's (an ancestor that clips, such as a sheet's card, still does), as a row of cards in a padded column runs to the screen's edges on iOS: the engine widens its frame to the screen's sides and keeps the content where it was, with chrome viewport the rect the scroll view laid out in. The page widens the scroll content by the space after the viewport and sets scroll-padding to both spaces, so it scrolls as far and snaps against the same edges as before. Vertical scroll views still clip.

containerRelativeFrame. .containerRelativeFrame(.horizontal), the count:span:spacing: overload and the closure overload all become a style hint "containerRelativeFrame": {"horizontal": true, "a": slope, "b": intercept, "alignment": …} (vertical likewise), where length = a * container + b; the closure is sampled at 0 and 1000 to recover a linear function. The layout engine keeps the current container size in its Context (the screen at the root, the viewport inside a scrollPlan) and resolves the hint into a fixed frame before measuring the child. The container is part of the measure memo's key, so a page measured while its scroll view was tried at another width is measured again at the final one, and the scroll view places its content under the context it measured it in.

visualEffect. .visualEffect { content, proxy in … } runs the closure once with a zero-sized proxy and applies the resulting chain (offset, scale, rotation, 3-D rotation, opacity, blur; the color effects are accepted and dropped) through the ordinary styled wrapper, so the effects appear in that element's style and are not sent separately.

Typed environment objects. @Environment(Order.self) var order and the optional @Environment(Order.self) var order: Order? read an Observable object stored by .environment(order); a missing object traps with the type name, like SwiftUI. .environment(_:) also accepts an optional object.

Smaller additions. navigationTitle(Text) and navigationTitle(Binding<String>); dynamicTypeSize(range) clamps to the nearest size in the range; accessibilityInputLabels; Angle * Double, /, +=, -=; UITextChecker (always "no misspelling") moved to FoundationBridge because it needs NSRange.

CLI. Companion files and the lean import Foundation rewrite now import Observation too, so a Foundation-only file can declare @Observable (CupcakeCorner's Order). File references in .pbxproj whose case doesn't match the checkout are repaired component by component (repairCase) because Xcode on a case-insensitive disk never noticed. CI builds the twelve projects in full mode and the ones without Foundation-only code in lean mode, and runs Flashzilla, Moonshot and WordScramble headless; Moonshot must render "Apollo 11" from its staged JSON and request the dark color scheme.

Headless runner. SB_BUNDLE_DIR is mounted only when the directory exists; an app without resources stages none, and a missing preopen used to abort uvwasi_init before main ran.

Phase 13: networking#

The app has no network of its own; the page is the network. Two additions to the protocol carry everything: a request op from the app and a response event from the page.

request op. {"op":"request","id":N,"kind":"fetch"|"image","params":{…}}. The id is the app's, increasing per request; it never collides with element ids (it is a different namespace). The loader (Web/src/wasm.ts) takes these ops out of the batch before the renderer sees it and performs each with Web/src/hostRequests.ts:

  • fetch: params is {"url","method","headers":{…},"body":base64|null,"timeout":ms}. The page runs the browser's fetch with those (an AbortController for the timeout) and answers with {"status","statusText","headers":{…},"body","url"}, body as bytes (see "Bytes"; base64 for a module without sb_bytes); header names come back lower-cased, url is the final URL after redirects. HTTP errors are answers, not failures, as with Foundation's URLSession.
  • image: params is {"url"}. The page decodes the image off screen (an Image()) and answers with {"width","height"} in pixels. The bitmap never crosses into Wasm: the <img> the renderer creates later finds it in the browser's cache.

response event. {"type":"response","id":N,"value":…} on success, {"type":"response","id":N,"error":"message"} on failure. The message starts with a tag the app maps to a URLError: timeout, abort, offline, network (a failed fetch, which is also how the browser reports a CORS refusal), headless (no fixture). The event goes through sb_event_json like any other, which also runs the executor, so the awaiting task resumes at once.

Runtime. _Runtime._hostRequest(kind:params:) async throws -> _JSON allocates the id, emits the op and parks a continuation until the matching response arrives (_HostRequestError for error). Kinds the page does not know itself are a page module's (Web/plugins/page-modules.ts): the page hands each module HostRequests, whose register(kind, handler) answers a kind with the handler's promise (RealityKit's realitykit.asset, a model's outline; docs/realitykit.md, "Models"). URLSession and AsyncImage (Sources/_FoundationCommon, shared by lean and full builds like UserDefaults) are built on it.

URLSession. data(from:), data(for:), upload(for:from:), download(from:) / download(for:) (the body written to a file in the temporary directory, which the caller moves or removes), the completion-handler dataTask / uploadTask (started by resume()), URLSessionConfiguration (its httpAdditionalHeaders and timeoutIntervalForRequest are honored), URLRequest (method, headers, body, timeout), URLResponse / HTTPURLResponse (status, headers, MIME type and charset from Content-Type), URLError with Foundation's codes. In full mode corelibs Foundation declares these names as unavailable (they moved to FoundationNetworking, which the SDK does not ship), so FoundationBridge aliases them and the CLI's generated _SwiftBrowserFoundation.swift settles them in the bridge's favor, as for Timer.

AsyncImage. All three initializers (url:scale:, url:scale:content:placeholder:, url:scale:transaction:content:) and AsyncImagePhase. The view renders the placeholder (or .empty), sends an image request from its .task(id: url), and on the answer switches to .success(Image), an image whose props are the new URL form: {"url","resizable","width","height"}, the size in points (pixels / scale). The layout engine uses that as the intrinsic size (or the proposal when resizable); the renderer sets the <img>'s src to the URL and marks the element data-sb-url. A nil URL stays .empty and asks nothing; a failed load is .failure(URLError), which the two-closure form shows as the placeholder, like SwiftUI. Transaction is a plain struct the shim accepts. The <img> is inert, as a SwiftUI image is (no pointer events, not draggable). React's AsyncImage webInteractions adds "webInteractions": true to the props, which the Swift core never sends: the element is marked data-sb-web and the <img> takes pointer events and is draggable, so the browser's own long press (Save / Share / Copy on iOS), drag out and right-click menu work on it; inside an inert subtree it stays inert.

Headless mode. No page answers, so SB_RESPONSES (a JSON array) does: each item names a url (exact) or a prefix and carries status, headers and body (text) or bodyBase64 for a fetch, width and height for an image; a request with no entry fails with headless: …. The runtime answers inside _hostRequest, so the awaiting task resumes on the next executor run (SB_RUN_MS). scripts/snapshot-test.sh and scripts/full-foundation-examples.sh read Examples/<App>/__snapshots__/responses.json into it; scripts/run-wasi.mjs forwards it.

Lean builds. error.localizedDescription now exists in FoundationLite (Foundation's comes from its NSError bridge, which FoundationEssentials lacks), and "\(value, format: style)" interpolates with a FoundationLite style (the bridge adds the overload for Foundation's FormatStyle).

Example. Examples/CupcakeCorner (Hacking with SwiftUI project 10): AsyncImage from hws.dev, an order posted with URLSession.upload and the echo decoded into the confirmation. Its snapshot replays the whole order with responses.json; the Playwright test routes both URLs and asserts the POST's JSON body and the alert.

WebSockets#

URLSessionWebSocketTask (Sources/FoundationBridge/WebSocket.swift) runs over the browser's WebSocket, through the same request channel. Each call on the task is a request of kind websocket, with an action:

action Params Answer
open url, protocols {socket} once the socket is open; fails (network: …) when it cannot connect
send socket, and string or data (base64) {}
receive socket the next message, {string} or {data}. Messages that arrive while nobody is receiving wait in a queue on the page. Once the socket has closed and the queue is empty, the answer is {closeCode, reason}, and the task fails the receive with URLError(.networkConnectionLost).
close socket, code, reason {}. A page may only send 1000 or 3000–4999, so other codes close as 1000.

resume() opens the socket. A send or receive before the open finishes waits for it, which matches the task's pull model: an app calls receive again for each message, as Ice Cubes' stream watcher does. Pings are the browser's own business: sendPing answers once the socket is open. Headless, open fails ("headless: WebSockets are not available"), as it would offline.

Phase 14: one Foundation#

Lean mode is removed; every app links the real Foundation (Phase 11's build), and the layers that existed for lean go with it:

  • The SwiftUI shim imports Foundation. onDelete / onMove and remove(atOffsets:) / move(fromOffsets:toOffset:) take an IndexSet, DatePicker a Date, Text(_:format:) and the "\(value, format:)" interpolation a FormatStyle, TextField(_:value:format:) a ParseableFormatStyle. The protocols that stood in for them (_OffsetSet with _IndexSetLite, _DatePickerValue, _TextFormat) and FoundationBridge's conformances to them are gone.
  • Sources/FoundationLite and Sources/_FoundationCommon are deleted. FoundationBridge holds what corelibs Foundation lacks on WASI: Timer, RunLoop, UserDefaults, Bundle, URLSession and friends, AsyncImage, the Locale hook, UITextChecker. The CLI's generated alias file settles the names Foundation also declares; AsyncImage needs no alias.
  • The root Package.swift declares the three libraries and HelloWasm only. The examples are built through the CLI (scripts/build-wasm.sh runs swiftbrowser build Examples/<App>), so they get the same trimmed ICU data, generated alias file and wasm-opt as any app, and their sources say import Foundation like an Xcode project. scripts/full-foundation-examples.sh is gone (it was this).
  • Headless snapshots run in en_US and GMT (SB_LOCALE, TZ in scripts/snapshot-test.sh), so currency is $, and are recorded with ICU's formatting.
  • CLI: --foundation and "foundation" in swiftbrowser.json are accepted and ignored with a warning; import FoundationLite in an old file becomes import FoundationBridge; check no longer prints a Foundation mode.

Phase 15: smaller modules#

Where an 18 MB module went (Counter, optimized): 10.8 MB of code, of which the app itself is 6 kB and the shim 0.6 MB; the rest is the Swift standard library (3.5 MB, with every generic specialization), FoundationEssentials (2.3 MB), ICU's library (1.35 MB), the NSObject layer of corelibs Foundation (0.9 MB), the runtime, CoreFoundation, libc++ and the regex engine; and 7.1 MB of data, 4.7 MB of it ICU's locale package trimmed to English. The linker's dead-code elimination works, at function granularity: what survives is reachable through protocol conformances (any dynamic cast or String(describing:) may need any conformance, so every witness table of every linked type stays, with its methods: 366 kB of description getters nobody calls, 343 kB of Codable witnesses), through per-object-file metadata segments, and through the dense NSObject graph that FoundationEssentials itself pulls in. The SDK's archives are machine code, so the compiler's whole-program eliminators cannot run over them. What this phase changes:

  • ICU trimming drops more. The legacy character-set converters (*.cnv, 549 kB; UTF-8/16/32, ASCII and Latin-1 are algorithmic, so only String(data:encoding:) with Shift JIS, Windows-1252 and the like loses, and returns nil), the StringPrep profiles (*.spp, IDNA 2003 and LDAP) and the spoof-checker data (confusables.cfu). "collation": false in swiftbrowser.json also drops the collation tables (coll/, 0.9 MB) for apps that never compare strings in a locale: localizedCompare, localizedStandardCompare and .localizedStandard sorting then order by Unicode scalar instead of failing.
  • wasm-opt runs -Oz (measured as fast as -Os on an 18 MB module, and 1.3% smaller), and the CLI removes the .swift1_autolink_entries custom section afterwards (108 kB of library names the linker already used; --strip-debug leaves it). packages/cli/src/wasm.ts splits a module into sections and rewrites the custom ones; nothing else is touched.
  • Counter: 17.4 MB (4.5 MB brotli), from 18.4 MB (4.6 MB).
  • Not done, measured: -Osize for the shim and app saves 26 kB (0.1%); the shim's own references into the NSObject layer (IndexSet, CharacterSet) cost nothing to remove because FoundationEssentials pulls the layer anyway.
  • Built, measured and parked on the icu-sidecar branch: the ICU data as a content-named file beside the module (icudt76l-<hash>.dat), which the module reserves zero-filled memory for and exports the address of, and the loaders copy into memory before _start from a swiftbrowser.icu custom section's directions. Counter becomes a 13.6 MB module (3.6 MB brotli) plus a 3.9 MB file (0.8 MB) that every app on a site shares and an update never re-downloads; wasm-opt gets 2 s faster. For a single-app site that is a fifth off each update's download, against a second file the module cannot start without, so it is not in.

Phase 16: skipping unchanged views#

Before this phase, a body that re-ran forced every view below it to re-run: the runtime could not tell whether a child's new view value differed from the one it held. In Food Truck a new order re-ran the whole Truck screen under TruckView (which observes the model), though only the orders card showed anything new: 37 ms of a 81 ms task, during which the truck header, redrawn every 50 ms, stalled.

When a parent re-runs, a child is now treated as clean (its body and its subtree are skipped, its elements reused) when all of these hold (_Runtime.canSkip):

  • the child is not dirty itself (its own @State, observed object or @Observable read did not change);
  • it has a body of its own: the shim's containers and primitives (stacks, modifiers, Text, ForEach) re-run as before, because they are cheap and their values hold their whole content, which would be walked again at every level; the views with bodies inside them are compared one by one;
  • its new view value is the same as the one it holds (_Sameness, by reflection, with each type's strategy worked out once): Equatable values compare with ==; class instances by identity; @State, @StateObject, @FocusState, @Environment, @EnvironmentObject and @ScaledMetric are ignored (they belong to the node or come from the environment); structs, tuples, enums, optionals and collections member by member. A binding made from a state or an observed object ($value, $model.property, $item.name) is the same when it points at the same storage through the same key paths and the value it was made from is the same (_BindingSource); a closure, a binding made from a getter and a setter, or a value larger than 256 members is different. A view type that holds one of those is remembered and not compared again;
  • the context it receives is the same: the environment (every entry compared the same way), the path, the enclosing navigation stack, screen, sheet, split view and tab state. The values the runtime itself re-creates on every pass carry an identity for this: a screen's or sheet's DismissAction, the edit-mode binding a screen or list owns and a List(selection:)'s selection (their identities include the current mode or selection, so a change re-runs the views below);
  • it is not itself part of the navigation structure (a stack, screen, split view or tab view), whose pass state follows the view it was given. What its subtree set on the ancestors while reconciled (a screen's title, a sheet's detents, a split view's sidebar selection) is kept on the nodes between (_MountedNode.writes) and set again when the subtree is skipped, because an ancestor that re-ran reset it and expects it to be set again. A registered destination needs no replay: the stack's registry keeps it.

The rules are conservative: anything not proven equal re-runs, as before.

Measured on Food Truck's new order (Chromium, optimized module): the render pass reconciles 142 nodes instead of the whole tree's 1,572; the order task, 69 ms (median of nine orders) before, is now under 50 ms for five orders of nine and 52 to 62 ms for the others; the longest gap between truck header frames around an order is 110 ms (median) instead of 136, against about 100 ms between frames when nothing happens.

Phase 17: cheaper passes#

Phase 16 cut how many views a pass re-runs. This phase cuts what each pass costs, measured on Food Truck's Truck screen. There the header animates, which means a render pass several times a second.

The runtime side:

  • View traits per type (_ViewTraits, Runtime/ViewTraits.swift). Reconciling a node asked its view about two dozen runtime protocols (_GroupView, _HostView, _SheetPresenting, _OnAppearing, and so on). Producing its elements asked about more. Each question was a dynamic cast to an existential, which is a conformance lookup every time. The answers are now worked out once per view type, from the metatype, and cached as a bit set. A cast still runs where the runtime needs the view's values, and only for protocols the type conforms to. The skip gates of Phase 16 (has a body, writes to its ancestors) became bit tests.

    The answers come from the type, not from the value. A dynamic cast of an Optional value unwraps it, so before this phase if show { Text("x") .onAppear { ... } } was both a group (the optional) and an onAppear view (the text inside). The onAppear action ran once for each of the two nodes, and a .task started twice. An optional is now a group and nothing else.

  • Modifier chains in linear time. Every modifier is a _StyledGroup around its content. It applies to each child of a content that is a group of other than one child (or a keyed one, such as ForEach), so both its children and its keys asked the content for its children and its keys. Down a chain of n modifiers that was about 2^n calls, each allocating an array. A view with eight modifiers cost 256 of them per pass. Groups now answer _spreads directly, and a chain asks each level once.

  • Toolbar hoisting by token. A screen moves toolbar and searchfield elements from anywhere in its content to its own children. That walked the whole content on every pass that produced the screen's elements. The subtrees found to hold none are remembered by element token, and a clean node's cached elements keep their token. A pass now walks only the elements produced anew.

The renderer side:

  • Style snapshots only when a pass can animate. Before applying an update, the renderer recorded the element's computed animatable styles, and before a remove, its rectangle, in case the pass animated. Each read forces a style recalculation in the middle of the batch. The renderer now looks ahead to the pass's commit when the pass starts. The pass can animate when that commit has an animation, or when one of its updates changes an animationToken. Only then does it take the snapshots, and it reads the animation root's rectangle once per pass. A pass whose commit is in a later batch is assumed to animate. A pass that cannot animate still retargets running frame tweens, which needs none of this.
  • The screen size after a resize only. Every layout read the root's clientWidth and clientHeight after the pass had changed the DOM: a forced layout. The size is now read once and again only after a ResizeObserver reports a change, or when viewportChanged is called. Without a ResizeObserver it is read on every pass, as before.
  • Spring curves cached. A spring's linear() easing (60 samples) was computed for every tweened element. It is now cached per duration and bounce.

Measured again on Food Truck's order detail at iPad width (the split view's sidebar toggle, which re-lays out both columns with animation):

  • Reads before writes. A pass that can animate snapshots the styles of the elements its updates change and reads the rectangles of those its removes take out before it applies its first op (prereadPass), so the reads share the one clean layout. Read op by op, each followed DOM writes and forced a style recalculation or layout: five of each inside the toggle's click. The scroll views' state syncs (the under-bar and bottom-edge flags, read from scrollTop and scrollHeight) are batched the same way (src/scrollSync.ts): queued while the layout is applied, then all measured before any is applied. The Animator takes an .animation root's box from its inline style, not offsetWidth. One forced style recalculation and one layout remain.

  • Hidden screens are not animated. A screen below the top of its stack is not drawn once the push has settled (visibility: hidden), yet the Animator tweened its boxes: on that toggle 83 of the 107 tweens were the rows, chevrons and badges of the Orders list under the pushed detail. What such a screen holds now jumps to its new boxes; during a push or pop, while the lower screen slides, it animates as before.

  • Covered screens are not laid out. The engine placed every screen of a navstack on every run; on that order detail 848 of the 952 boxes were the covered Orders list. A screen below the top one that has frames keeps them while it is covered, however the stack resizes or its content changes meanwhile, and the page does not walk it either (it is not in changed). Its plan is left as it is, so when a pop uncovers it the usual check passes only if nothing changed since those frames were made; otherwise it is laid out afresh in the pop's pass, before the frame paints. A back swipe shows a covered screen without a pop, so when one starts the page has the engine lay that screen out (uncover) and runs a layout before the drag moves anything. A screen pushed under another in one pass has no frames yet and is placed. With this the toggle lays out 102 boxes instead of 950 and touches 57 elements instead of 146.

  • Skipped subtrees set their screen's title again. The toggle's pass on the Swift side re-ran 174 of the 176 nodes it visited to change one element: the split view's own state flips, both column stacks are rebuilt, and every screen's content was unskippable under the Phase 16 rule that a subtree writing to its ancestors (here a navigation title, a destination, a sidebar selection) never skips. The rule is now the replay above: the writes are kept on the nodes and set again when the subtree is skipped. On the order detail the Orders list (the biggest subtree) is skipped whole. The Swift time of a toggle goes from 8–12 ms to 4–7 ms (unoptimized module, steady state).

  • Bindings compare by their source. The sidebar and the detail column still re-ran: each holds a @Binding to the app's selection, and a binding never compared equal. A binding made from a state or an observed object now carries where it points and the value it was made from (_BindingSource, above), so Sidebar(selection: $selection) is the same input as last time while the selection is. With both, the Swift time of a toggle is 3–4 ms and the handler 11–12 ms instead of 16–22 ms.

  • A pass reads nothing it wrote. Two reads were left after the pass's writes, each making the browser lay the frames out inside the pass (4 ms on the toggle) and again for the frame. The scroll views' under-bar and bottom-edge syncs read scrollTop, scrollHeight and clientHeight: the offset is now read for every list and scroll view before a pass's first op touches the page (readScrollOffsets, scrollSync.ts), and the content and viewport lengths are the ones the pass set, which predict the scroll extent exactly. The Animator's commit reads the updated elements' computed styles (the values a style tween ends on; transform is layout-dependent) and the removed boxes' places. It now runs in the next animation frame's callback (commitNextFrame), before that frame paints: the reads cost the frame its one layout, every tween still starts on the first frame after the change, and a hidden page commits at once. The toggle's handler is 6–7.5 ms instead of 10–11.5 ms, with the first frame 1–2 ms earlier; a test that inspects a commit's tweens waits for that frame.

  • Less garbage per pass. A toggle's pass allocated about 530 KB of JavaScript objects (traced: a scavenge every few toggles, incremental marking steps, and a 4–5 ms major collection every ten or so, which can cost a frame mid-animation; the much larger GC numbers in CPU profiles are the profiler's own). A quarter of it was the geometry report walking every element of the page (about 1,500, an entry and an iterator result each) to find the few that report their size, and a generator per updated element for the Animator's walk up its ancestors. The renderer keeps the set of reporting elements, and the walk is a loop: about 415 KB now. The rest is the engine's plans and contexts, the frame keyframes and the ops text, and is left as it is.

At 4× CPU throttling the toggle's first frame went from about 200 ms to 150 ms with the first two changes, and to 75 to 115 ms with the third; the slide drops one or two frames instead of three to eight.

Measured with the optimized module in Chromium, three runs each. On the Truck screen at rest, script time per second goes from 127–150 ms to 90–102 ms: wasm from 76–87 to 58–68, JavaScript from 45–58 to 27–30. In a profile of the unoptimized module, which keeps the names, dynamic casts went from 84 ms to 17 ms over the same six seconds. The renderer's update went from 31 to 13 ms per second. The new-order task's long tasks are 50–55 ms instead of 55–74, and there are fewer of them. The header's frame gaps around an order are within noise of before. They are dominated by the header's own cadence, about 100 ms between redraws in this measurement.

Phase 18: SwiftData on IndexedDB#

An app that imports SwiftData links the SwiftData module of the Swift package (Sources/SwiftData, with its macros in Sources/SwiftDataMacros). The models live in Swift memory for the run; the page keeps them across launches in IndexedDB. The protocol gains one op and one launch variable.

swiftdata op (Swift → host): one save of one store, {"op":"swiftdata","store":"default.store","put":[{"id":1,"entity":"Book","values":{…}}],"delete":[2,3]}, plus "clear":true when ModelContainer.deleteAllData() emptied the store first. put holds every model the save inserted or changed, whole; delete the keys of the models it deleted. The loader (Web/src/wasm.ts) takes these ops out of the batch, in order, and hands each to the page, which writes it in one IndexedDB transaction (Web/src/swiftData.ts). Headless runs print it like any op.

SB_SWIFTDATA (host → Swift, at launch): every store the app saved, {"<store>":[{"id":1,"entity":"Book","values":{…}},…]}. The page reads the app's database before it instantiates the module and passes it only when it holds records. ?swiftdata=reset on the app URL deletes the database first.

The database. One per app, sb-swiftdata:<App>, version 1, with one object store, records, keyed by [store, id]; a row is {store, id, entity, values}. A store is named after its configuration's URL: default.store for ModelConfiguration(), <name>.store for a named one. In-memory configurations (isStoredInMemoryOnly) send nothing.

Values. A record's values holds every persisted property: strings, numbers and booleans as themselves, Date as seconds since 1970, nil as null, other Codable values as JSONEncoder writes them (sorted keys, dates as seconds since 1970; UUID and URL as strings, Data as base64, enums with raw values as the raw value). A to-one relationship is the related record's id or null, a to-many one an array of ids. Ids are unique across the app's stores and increase; a launch continues after the largest one it was handed.

Headless. scripts/run-wasi.mjs forwards SB_SWIFTDATA. With SB_SWIFTDATA_FILE set, that file plays the database: its stores are handed in at launch and the run's swiftdata ops are applied to it afterwards, so a second run starts from what the first saved (CI runs Bookshelf and SwiftDataProject twice this way).

@Model#

Apple's SwiftData expands @Model with macros, and so does this one; the expansion follows Apple's shape so that what compiles there compiles here.

  • Each stored var of the class that is not @Transient (nor static, lazy or computed) gets @_PersistedProperty, which turns it into a computed property over the model's backing data: an init accessor (@storageRestrictions(accesses: _$backingData, initializes: _title)) so that self.title = title in the class's initializer and an initial value (var city = "Unknown") still work, and a getter and setter wrapped in Observation's access / withMutation, so models are Observable. A _title: _SwiftDataNoType peer keeps definite initialization honest: the class's initializers must still give every persisted property a value.
  • The class gains _$backingData, persistentBackingData, an observation registrar, required init(backingData:) (how a context materializes a stored record) and static var schemaMetadata, one Schema.PropertyMetadata(name:keyPath:defaultValue:metadata:) per persisted property with its initial value and its @Attribute or @Relationship arguments.
  • An extension adds PersistentModel, which is Observable, Hashable (by persistentModelID) and Identifiable (id is the persistentModelID, unless the class declares its own id).

The metadata is built in a generic context where each property's type is known, so the store learns there how to encode and decode the property, whether it relates to other models (a model, an optional model, an array or set of models, optional or not) and how to notify its observers.

Backing data. A model's values are live Swift values once set or read; a model fetched from the store holds its record's JSON until a property is first read, so a fetch decodes only what a screen shows and a relationship looks up its models only when it is followed. A property missing from a record (added to the class since the data was saved) takes its initial value, or nil when it is optional.

Contexts. A context keeps one object per record (two fetches return the same model), the inserted, changed and deleted models, and the store it saves to. fetch evaluates the descriptor's predicate (Foundation's Predicate.evaluate) over the store's records of the entity and the context's unsaved inserts, sorts with the SortDescriptors, then applies fetchOffset and fetchLimit. Setting a relationship inserts the models it now holds into the context and keeps the inverse in step on both sides; the inverse is the one @Relationship(inverse:) names on either side, else the only relationship of the related type that points back. Deleting applies the delete rules: .cascade deletes the related models, .nullify (the default) and .deny take the model out of the inverse, .noAction leaves it. @Attribute(.unique): a new model whose value a saved record already has replaces that record when it is saved. A save in one context reaches the store's other contexts (their unchanged models read the saved values; deleted records leave). rollback() returns inserted, changed and deleted models to their saved state.

Autosave and @Query. A container's mainContext has autosaveEnabled; a change schedules a save through _Runtime._afterUpdate, which runs once the event (or executor run, or launch) that made it has rendered, so one tap is one swiftdata op. Every change to a context bumps an observable generation that @Query reads while the view's body runs, so the view re-runs on inserts, deletes and property sets; the query fetches again only when the generation moved. @Query reads modelContext from the environment through the shim's new _EnvironmentReading protocol, which, unlike @Environment, stays part of the view's value for Phase 16's sameness check: a parent that rebuilds a child's query with other inputs re-runs the child. .modelContainer(for:) on a view or scene makes its container once (by model types) and puts its main context in the environment; a scene modifier wraps the root view through the shim's _RootModifiedScene.

#Predicate. The open-source Foundation macro accepts localizedStandardContains, localizedCompare and caseInsensitiveCompare only when it is built into Apple's Foundation, and corelibs Foundation has no expressions for them, so a common SwiftData filter ($0.name.localizedStandardContains(search)) did not compile. SwiftData carries a copy of the macro (Sources/SwiftDataMacros/PredicateMacro.swift) that accepts them, with their expressions (Sources/SwiftData/ StringPredicates.swift). For an app that imports SwiftData, the CLI's generated _SwiftBrowserFoundation.swift declares macro Predicate pointing at that copy; a macro declared in the app module shadows Foundation's, and the type Predicate stays Foundation's.

Building. The macros need swift-syntax, and every app needs them (SwiftUI's @Entry is one): the CLI compiles them with the rest of the shim into its kit, once per version (packages/cli/src/kit.ts), and loads the kit's executable of them into each app's build. The package depends on 604.x, which swift.org publishes prebuilt for Swift 6.4 (Downloading package prebuilt …MacroSupport), so the macro target builds in seconds; elsewhere SwiftPM compiles swift-syntax once (minutes). SwiftPM takes the prebuilt only for a macro target whose dependencies are all swift-syntax's: one more (the macro once linked os) and a cold build compiles swift-syntax, 430 of a Counter build's 530 s. Compiled from source after the shim's OSLog module, swift-syntax logs through it (canImport(OSLog)) and the macro fails to link; the CLI's builds set SWIFT_BUILD_SCRIPT_ENVIRONMENT, which swift-syntax reads to leave OSLog out.

Not yet. @ModelActor, history tracking, CloudKit sync, undo, subclassed models, .deny blocking a delete, and includePendingChanges: false (pending inserts are always fetched). Nothing stops two tabs of one app from writing the same database; the last save of a model wins.

Sharing#

ShareLink is a button whose action sends a host request (Phase 13's channel) of kind share:

{ "op": "request", "id": 7, "kind": "share",
  "params": { "title": "Swift", "text": "The Swift programming language", "url": "https://www.swift.org" } }
param from
title the subject, else the SharePreview title
text the message, then each String item (and each URL after the first), one per line
url the first URL item (or the URL of an AsyncImage-style Image)
images asset-catalog names of the Image items; a symbol image has no file and is left out

The page shares with navigator.share. Images are fetched from the asset catalog and passed as files, when navigator.canShare({files}) allows it. Without the Web Share API, or when the browser refuses (no user activation, unsupported data), it downloads instead: each image as its file, or else the title, text and link, one per line, as <title>.txt (Shared.txt without a title). A share the viewer dismisses (AbortError) downloads nothing. The response value is { "outcome": "shared" | "downloaded" | "cancelled" }, which the app does not see, as SwiftUI reports none. Headless runs answer { "outcome": "headless" } at once.

Three framework stand-ins ship with the shim as their own small modules, linked only into apps that import them (STAND_IN_FRAMEWORKS in packages/cli/src/compat.ts):

  • StoreKit: RequestReviewAction (@Environment(\.requestReview)) and SKStoreReviewController.requestReview() are no-ops.
  • CoreLocation: CLLocationCoordinate2D (and CLLocationDegrees, CLLocationDistance, CLLocationCoordinate2DIsValid, kCLLocationCoordinate2DInvalid) as plain values. It has no protocol conformances, as on Apple platforms, so an app's own extension CLLocationCoordinate2D: Equatable compiles.
  • LocalAuthentication: LAContext. canEvaluatePolicy returns true, evaluatePolicy replies (true, nil) at once (the async form returns true), and biometryType is .faceID. LAPolicy, LABiometryType and LAError with its codes are there too. It is @unchecked Sendable, so an app awaiting it from the main actor compiles in Swift 6.

Phase 19: the app's files#

The app gets a writable home directory that the page keeps across launches, with the layout of an iOS app container. Nothing new crosses the op or event channels: the files live in the WASI filesystem the page provides.

Mounts and environment. Next to /bundle (Phase 11, read only) the loader (Web/src/wasm.ts) preopens:

  • /data, the home: Documents, Library, Library/Application Support and Library/Caches always exist, plus whatever the app saved;
  • /tmp, empty at every launch.

and sets HOME=/data, XDG_DATA_HOME=/data/Library/Application Support, XDG_CACHE_HOME=/data/Library/Caches and TMPDIR=/tmp (unless the page passes its own). With those, corelibs Foundation's FileManager.urls(for:in:) answers with the iOS directories (.documentDirectory → /data/Documents, .applicationSupportDirectory and .cachesDirectory → their Library folders), and FileManager.temporaryDirectory is /tmp. Without HOME, Foundation's search-path lookup recurses until the stack overflows; without a Documents directory, writing into it fails, as it never does on a phone.

FoundationBridge (Sources/FoundationBridge/FileSystem.swift) supplies what swift-foundation declares only in Apple's Foundation: URL.documentsDirectory, URL.libraryDirectory, URL.applicationSupportDirectory and URL.cachesDirectory, derived from the same environment. On WASI it also supplies Data.WritingOptions.atomic: corelibs marks its own unavailable there ("temporary files are not supported") and writes every file in place whatever the options say, and an unavailable declaration loses overload resolution to an available one, so try data.write(to: url, options: [.atomic, .completeFileProtection]) compiles and writes. (Natively both are available, so the bridge's is WASI-only.)

Persistence. One IndexedDB database per app, sb-files:<App>, version 1, with one object store, entries, keyed by path (relative to the home): {path, data} for a file, {path, directory: true} for a directory (Web/src/appFiles.ts). Before the module starts the page reads every row and builds the /data tree (?files=reset deletes the rows first). The loader wraps the WASI imports that can change a file (fd_write to a descriptor above 2, fd_pwrite, fd_allocate, fd_filestat_set_size, path_open with CREAT or TRUNC, path_create_directory, path_remove_directory, path_unlink_file, path_rename, path_link); after a drain in which one ran it calls onFilesWritten, and the page diffs the tree against what it last saved (files by their bytes, since a write in place keeps the same buffer) and writes the difference in one transaction. Writes to /tmp or /bundle set the flag too but find nothing to save in the home.

Headless. scripts/run-wasi.mjs mounts /data from SB_FILES_DIR (created with the standard directories if needed), so a second run sees what the first wrote, or from a fresh temporary directory; /tmp is a fresh temporary directory. CI runs Examples/Journal twice this way.

Not yet. File coordination and iCloud Drive from Swift (a @swiftbrowser/react app has them natively through fileManager, docs/native.md). (fileImporter is the file chooser, "Photos picker"; fileExporter is "Exporting files".) Nothing stops two tabs of one app from writing the same home; the last write of a file wins.

Core ML models#

No protocol change: a Core ML model runs inside the module. Xcode compiles each .mlmodel of a target's Sources into a Swift class (SleepCalculator, SleepCalculatorInput, SleepCalculatorOutput) and an .mlmodelc the class loads; @swiftbrowser/cli does the equivalent when it stages the app, for the model types Create ML makes from tables, and the CoreML module of the Swift package (Sources/CoreML) evaluates them.

Finding the models. The target's Sources build phase and its synchronized folders (models in @swiftbrowser/xcodeproj), every .mlmodel and .mlpackage under a plain folder, or the ones a swiftbrowser.json sources list names (a model file, or a folder holding some). An .mlpackage is read through its Manifest.json (the root model's specification under Data/).

Reading them. packages/cli/src/protobuf.ts reads the protocol buffers wire format (varints, fixed-width numbers, length-delimited fields, packed and unpacked repeated fields); packages/cli/src/coreml.ts reads Model from apple/coremltools' Model.proto with it, field by field, and checks what it finds. Supported, at any specification version:

Model.proto type What it is in Create ML
glmRegressor linear regression (MLLinearRegressor)
glmClassifier logistic regression (MLLogisticRegressionClassifier)
treeEnsembleRegressor, treeEnsembleClassifier boosted trees, random forests, decision trees
pipelineRegressor, pipelineClassifier, pipeline the wrapper every tabular model is
featureVectorizer, oneHotEncoder, imputer, normalizer, scaler, dictVectorizer, arrayFeatureExtractor, categoricalMapping, identity the feature engineering inside the pipeline

Anything else stops the build with the file, the step and the type named: Classifier.mlmodel: the model is a neural network (neuralNetwork), which the browser cannot run. Supported: …, or pipeline step 2 is a support vector machine regressor (supportVectorRegressor). So do image, sequence and state features, multifunction models, unreadable files, a tree whose branches name a missing node, and a GLM classifier whose weight rows do not fit its classes.

The generated class. <Class>.mlmodel.swift in the staged sources (the class is the file's base name, other characters as _), with Xcode's API: model: MLModel, urlOfModelInThisBundle, init(model:), init() (deprecated, as Xcode marks it), init(configuration:) throws, init(contentsOf:), init(contentsOf:configuration:), the four load(…) functions (completion handler and async), prediction(input:), prediction(input:options:), prediction(<one argument per input>) and predictions(inputs:options:). The input class stores one property per feature and the output class reads one per feature, typed as Xcode types them: Int64, Double, String, MLMultiArray, [String : Double] or [Int64 : Double]. SleepCalculator's inputs are all Double (prediction(wake:estimatedSleep:coffee:)). Feature names become identifiers the same way, keywords in backticks.

The model inside it. The class carries the model's specification as JSON in a raw string literal, which urlOfModelInThisBundle registers under the class name; MLModel(contentsOf:) finds it by the URL's base name (/bundle/SleepCalculator.mlmodelc) and decodes it once. JSON rather than Swift literals: the compiler type-checks a string in no time whatever the model's size (a boosted tree classifier has thousands of nodes; a Swift array literal of them is slow to type-check), the generator is one serializer, and one evaluator in the module serves every model, tested once. Rather than a resource file: nothing else to stage, serve or fetch, and check compiles exactly what runs. The JSON mirrors Model.proto: each model is {"specificationVersion", "description": {"inputs", "outputs", "predictedFeatureName", "predictedProbabilitiesName", "metadata"}, "model": {"kind": …}}, a feature {"name", "type", "optional", "shape", "dataType", "keyType"}. Trees are resolved by the CLI: per tree, columns of node behaviors, feature indices, thresholds, true and false children as positions (the root first, -1 for a leaf), missing-value directions and the leaves' (index, value) pairs. Keys of int64 maps are written in decimal; NaN and the infinities as "nan", "inf" and "-inf".

Evaluation (Sources/CoreML/Evaluation.swift), as Model.proto defines it:

  • A pipeline runs its models in order over one set of named values; the outputs are the values its description names.
  • GLM regressor: w · x + b per weight row, then the transform (none, logistic, probit). GLM classifier: one weight row is binary (the second label's probability is σ or Φ of it); one row per class is one-vs-rest (each σ, normalized to sum to 1); one row per class but the first is a reference-class multinomial (softmax over 0 and the rows).
  • Tree ensembles: from the base values, each tree adds its leaf's values; ≤ < ≥ > == ≠ branches, a NaN follows the node's missing-value direction. Regressors may apply a logistic; classifiers apply softmax, softmax with the first class at 0, a logistic (one dimension is binary), or nothing (one dimension is the second label's probability, as random forests have it). The predicted label is the most probable (the first on a tie).
  • x for a GLM or a tree ensemble is its inputs' numbers concatenated in declared order. A feature vectorizer does the same and also expands a sparse one-hot dictionary to its dimensions.
  • One-hot encoder: a 1 at the category's position, as an array or (sparse) a {index: 1} dictionary; an unknown category is all zeros or an error, as the encoder says. Imputer: a missing value, or NaN (or the value the model names), becomes the imputed one; arrays element by element, dictionaries key by key. Normalizer: divided by the largest magnitude, the L1 or the L2 norm. Scaler: scale × (x + shift).

MLModel.prediction(from:) checks the inputs against the description first: a required input missing is MLModelError.featureType ("Feature estimatedSleep is required but not specified."), an optional one may be absent, integers and doubles convert into each other, a string for a number is an error. Outputs come back as an MLDictionaryFeatureProvider of the declared outputs only. Predictions are synchronous; computeUnits and the other configuration is accepted and ignored.

Not provided. Image and sequence features (CVPixelBuffer, MLSequence), MLModel.compileModel(at:) (there is no compiler at run time), MLShapedArray, model updates (MLUpdateTask), and every model type outside the table, with Vision and Natural Language.

BetterRest. SleepCalculator.mlmodel (534 bytes) is a Create ML linear regressor: a feature vectorizer of wake, estimatedSleep and coffee into a GLM, actualSleep = 0.00008977302487916403 wake + 3601.4055324351725 estimatedSleep + 832.4267097286028 coffee + 461.66411230346455. At the app's defaults (wake at 7:00, i.e. 25 200 s; 8 hours; 1 cup) that is 30 107.6 s, 8 h 21 min 48 s, and the alert says "10:38 PM". CI builds the project and taps Calculate headless to check it.

Photos picker#

import PhotosUI gives PhotosPicker and .photosPicker(isPresented:) (Sources/PhotosUI). The browser has no photo library; the page's file chooser stands in for it. A pick is a host request (Phase 13's channel) of kind pickFiles:

{ "op": "request", "id": 3, "kind": "pickFiles",
  "params": { "accept": "image/*", "multiple": false } }
param from
accept the PHPickerFilter: image/* for the photo kinds (.images, .livePhotos, .screenshots, …), video/* for the video kinds, both for .spatialMedia; .any(of:), .all(of:) and .not(_:) combine them. No filter is image/*,video/*, what a library holds
multiple a [PhotosPickerItem] selection whose maxSelectionCount is not 1

The page answers with every chosen file:

{ "items": [
  { "name": "IMG_0001.png", "type": "image/png", "data": "iVBORw0K…",
    "url": "blob:https://…", "width": 1170, "height": 2532 }
] }

data is the bytes, base64; type is the browser's MIME type (empty when it has none). A picture the browser can draw also gets an object URL (url, never revoked: the app may show it for as long as it runs) and its pixel size. A dismissed chooser answers { "items": [] }.

A folder. public.folder among accept (SwiftUI's UTType.folder) asks for a folder: the page's folder chooser (webkitdirectory), the document picker opening a folder in place on iOS, an open panel that chooses directories on macOS. The answer holds the folder's files at any depth that the rest of accept allows (any when it names nothing else), each name its path from the folder, the folder's own name first (Bank/Leads/Saw.fxp).

The types, natively. A native app's host makes UTTypes of accept: an extension by UTType(filenameExtension:), a MIME type by UTType(mimeType:), image/*, video/* and audio/* as .image, .movie and .audio. An extension or MIME type that nothing on the device declares gives a dynamic type (dyn.…), which the document picker matches to no file, greying every one out; the picker is given .data in its place (any file) and the host logs a warning naming it. An app declares the types it opens in its Info.plist (UTImportedTypeDeclarations, which swiftbrowser native init --import-type writes), and the picker then offers those files alone. No type at all is .item. A folder's files are matched against the types as they are.

User activation. Browsers open a file chooser only during the user's tap (transient activation). The request is made inside it: the renderer delivers the tap from its click handler (sendEvent), the button's action starts the pick's task, the loader's runJobs() right after the event runs it, the request op is drained in the same call, and performHostRequest calls pickFiles before its first await, which creates a hidden <input type="file" data-sb-picker>, appends it to the document and calls click(). All of it happens before the click handler returns. The input answers on change (the files) or cancel (none) and removes itself. A browser without the cancel event never answers a dismissal, and the selection stays as it was. .photosPicker(isPresented:) opens from the render pass in which isPresented becomes true. That works within a button's action. Setting it from a timer or a task finds no activation, and the browser opens nothing.

Swift side. The answer's files are matched against the filter again (a chooser's "All files" lets anything through; a file with no MIME type is typed by its extension), cut to maxSelectionCount, and become PhotosPickerItems that hold the bytes. A non-empty pick replaces the selection (the first item for a single selection); an empty one leaves it alone, as a cancelled picker does on iOS. Items are Hashable by pick: the same file picked twice gives two different items, so onChange(of:) sees both. loadTransferable(type: Data.self) returns the bytes at once; loadTransferable(type: Image.self) returns an image of url at its pixel size (scale 1), or nil for a file the browser could not draw (HEIC outside Safari). Any other Transferable type imports through its representations: a FileRepresentation(importedContentType: .image) receives a temporary copy of the picked file; a type with no representation for the file's type loads nil. itemIdentifier is nil unless the picker was given a photoLibrary, as on iOS. PHPhotoLibrary is Photos' (which PhotosUI re-exports): .addOnly is .authorized (saving downloads) and .readWrite is .limited (the library shows the app nothing). preferredItemEncoding and selectionBehavior are accepted and ignored. Data is Transferable (in CoreTransferable). The completion-handler loadTransferable returns a finished Progress. Corelibs Foundation has no Progress on WASI, so FoundationBridge declares a small one there.

UniformTypeIdentifiers. supportedContentTypes are UTTypes (Sources/UniformTypeIdentifiers, its own stand-in module). The common image, movie, audio, text and PDF types are declared with their MIME types and extensions, and conformance follows Apple's hierarchy (.heic conforms to .image, .data, .content, .item). An undeclared MIME type or extension makes a dynamic type (dyn.…) conforming to the supertype asked for.

Executor (changed). A render can start tasks: an onChange(of:) action that loads the selected item in a Task, as Instafilter's does. When the render ran at the end of an executor run (sb_run_jobs, or a step of the headless clock), that task used to wait for the next event or timer, so a picked photo appeared only on the viewer's next tap. The runtime now runs the executor again, up to 16 rounds per call, while a render left jobs queued.

Headless mode. SB_RESPONSES entries with a pick answer the pickFiles requests in order, one entry per request. Each file has name, type, body (text) or bodyBase64, and for a picture width and height (url defaults to a data: URL of the bytes). Once the entries run out, a request answers with no items, as a dismissed chooser does.

[{ "pick": [{ "name": "red.png", "type": "image/png", "bodyBase64": "iVBORw0K…", "width": 4, "height": 3 }] }]

Example. Examples/PhotoPicker: a single-photo picker whose photo is shown (Image.self) and measured (Data.self), a three-item picker for photos and videos, and .photosPicker(isPresented:) opened from a button with .not(.videos). The snapshot replays the three picks from responses.json and then a fourth tap whose chooser is dismissed. The Playwright test (Web/e2e/photopicker.spec.ts) picks files through the real input, and fires its cancel event.

Exporting files#

.fileExporter(isPresented:document:contentType:defaultFilename:onCompletion:) (Sources/FoundationBridge/FileExporter.swift) saves a FileDocument where the viewer chooses. The shim declares FileDocument, its read and write configurations and the regular-file subset of FileWrapper (corelibs Foundation has none). When isPresented turns true the document's fileWrapper(configuration:) is written to a folder of its own under the temporary directory (Exports/<UUID>/<name>, the name from defaultFilename or the wrapper, with the type's extension when it has none) and its bytes go to the page as a host request of kind exportFiles:

{ "op": "request", "id": 4, "kind": "exportFiles",
  "params": { "files": [{ "name": "Notes.txt", "type": "text/plain", "data": "aGVsbG8=" }] } }

The page answers with where the files went:

{ "outcome": "saved" | "downloaded" | "cancelled", "urls": ["file:///…"] }

A browser with the File System Access API (Chromium) shows its save dialog for each file (showSaveFilePicker, the name and type offered); the viewer dismissing it answers cancelled. Another browser downloads the files, as a download link saves them (downloaded). The native app shows the document picker (UIDocumentPickerViewController(forExporting:asCopy:), "Save to Files"; NSSavePanel on macOS) and answers saved with the picker's URLs. onCompletion gets the URL of the file written in the temporary directory (the copy's place is the host's); a cancellation calls onCancellation, if given, as on iOS. The documents: overload exports each document under its wrapper's name. Opening a dialog needs a tap, as the file chooser does: set isPresented from a button's action. fileExporter in @swiftbrowser/react is the same request from a React tree, with a string, bytes or a Blob as the document.

Bitmaps and Core Image#

UIImage, CGImage and Core Image (import CoreImage, import CoreImage.CIFilterBuiltins) as Hacking with SwiftUI's Instafilter and Hot Prospects use them. The design has one rule: Swift never holds decoded pixels. A UIImage, CGImage or CIImage is a recipe, the shim's _ImageRecipe: a source (an image file's bytes, or a small pixel buffer a generator made) and the Core Image steps to apply to it, in order. The page decodes the source with the browser and runs the steps on a canvas when it draws the image.

Why not decode in Swift: UIImage(data:) is synchronous and the browser's decoders are asynchronous, so decoding in Swift would mean compiling JPEG, PNG, WebP and HEIC codecs into every module that shows a picture (megabytes of Wasm), then copying every frame of every slider drag back out of linear memory. Swift needs only sizes, which it reads from the file's header, so UIImage(data:) returns at once with the right size, and outputImage.extent is right before anything is drawn. Filters then run where the pixels are, at the resolution the image is shown at, not the photo's.

Where the types live. On iOS, import SwiftUI re-exports UIKit's UIImage and Core Graphics' CGImage (Hot Prospects' MeView imports SwiftUI and CoreImage.CIFilterBuiltins only), so both are in the shim (Sources/SwiftUI/API/Bitmaps.swift, with the recipe and header parsing in Runtime/ImageSource.swift); import UIKit stays unsupported. Core Image is a module of its own (Sources/CoreImage), linked only into apps that import it, like the StoreKit, Core Location and LocalAuthentication stand-ins (STAND_IN_FRAMEWORKS). CoreImage.CIFilterBuiltins is a Clang submodule on Apple platforms; a Swift module has no submodules, so the CLI stages import CoreImage.CIFilterBuiltins as import CoreImage (one line for one, so diagnostics keep their line numbers). The module imports Data and NSNumber from Foundation by name only, so Foundation's own CGRect and CGPoint never meet the shim's.

imagedata op#

{ "op": "imagedata", "key": "f4725a1d3ebc93652", "width": 160, "height": 120, "mime": "image/jpeg", "data": "<base64>" }
{ "op": "imagedata", "key": "p0d565cf280fa70f5", "width": 27, "height": 27, "format": "gray", "pixels": "<base64>" }

A bitmap's source, sent once per run before the first element that draws it (and before a ShareLink shares it). key is a content hash (FNV-1a, 64 bits; f for a file, p for pixels), so the same bytes are sent once however many images and filter chains use them. A file carries its media type and bytes (base64 as printed; from the browser build, beside the JSON: see "Bytes"); a pixel buffer its format (gray: one byte per pixel; rgba: four, straight alpha) and bytes, rows from the top. width × height is the size in pixels as drawn, a JPEG's EXIF rotation applied. The renderer keeps every source for the rest of the run (Web/src/bitmapStore.ts, through bitmapStore in Web/src/bitmaps.ts); headless runs print the op like any other.

image props: the bitmap form#

{ "bitmap": { "source": "f4725a1d3ebc93652", "steps": [ { "op": "sepiaTone", "intensity": 0.5 },
                                                         { "op": "render", "x": 0, "y": 0, "width": 160, "height": 120 } ],
              "width": 160, "height": 120 },
  "resizable": true, "width": 160, "height": 120, "interpolation": "none" }

Image(uiImage:) and Image(_:scale:orientation:label:) with a CGImage. bitmap.source is an imagedata key, or null for an empty image (UIImage()); bitmap.width × bitmap.height is the result in pixels. bitmap.frame, when present, is a frame of an animated GIF source, composed over the frames before it, which the steps start from; without it the source is the file as the browser decodes it, a GIF's first frame ("Animated GIFs"). bitmap.version, when present, is for a live source: RGBA pixels the page itself holds and changes in place (Web/src/bitmaps.ts addLiveBitmap; liveBitmapSource in @swiftbrowser/react), registered by the host rather than sent as an imagedata op, as a worker's or a WebAssembly module's output is. The pixels are read afresh at each drawing, and a changed version is what draws them again; over a SharedArrayBuffer the drawing worker reads the page's memory itself, over plain memory each version is copied to it once. A native app has no live sources yet. The outer width × height is the image's size in points (pixels ÷ the UIImage's scale), the intrinsic size the layout engine uses as for the remote form (the proposal when resizable). A UIImage(systemName:) or UIImage(named:) becomes the existing systemName or name form (a catalog set's dark image, which the page does not draw by name, the bitmap form from its file).

interpolation: "none" (.interpolation(.none), on any form but symbols) sets data-sb-interpolation="none" on the element, and the <img> or <canvas> inside draws with image-rendering: pixelated, so a QR code's modules stay square when scaled up. The other levels are omitted and drawn as the browser smooths.

Drawing. The element holds a <canvas> filling its frame. Once the layout engine has placed it, the page picks a working scale (raster pixels per source pixel): enough for the frame in device pixels, never above 1 (the source's own resolution), rounded up to a power of √2 so that a frame that animates does not redraw the picture on every step, and capped at 16 million pixels. It decodes the source (createImageBitmap, which applies EXIF rotation), draws it at that scale, runs the steps (Web/src/imageOps.ts) and puts the result on the canvas. A recipe of geometry and tints only (no steps, place, crop, render, roundedClip, tint; the images Nuke resizes are place + render) skips the raster: Web/src/bitmapPlan.ts works out where the source lands in the output, at the size the steps would give, and the browser draws it in one drawImage (smoothed, clipped to the rounded rectangles, tinted with a source-in fill). The raster pipeline, which ran every step in JavaScript, was a quarter of Ice Cubes' main thread at startup; filters and clamp still take it. The store, decoding and drawing included, runs in a worker (Web/src/bitmapWorker.ts) where the browser has OffscreenCanvas: the worker answers each drawing with an ImageBitmap the canvas takes without a copy (a bitmaprenderer context). That took about 1.3 s of Ice Cubes' startup off the page's thread, which Swift shares. Without worker canvases, or with ?bitmaps=main in the page's URL, the store runs on the page. One drawing per canvas runs at a time; a change that arrives meanwhile waits and takes the newest recipe, and the canvas keeps showing the previous picture until the next is ready, so dragging a slider never blanks it. The canvas gets data-sb-bitmap="ready" (or "error" when the browser cannot decode the file, such as HEIC in Chromium and Firefox) and dispatches a bubbling sb:bitmap event after each drawing.

Steps#

Coordinates are Core Image's: units of source pixels, origin at the bottom left, y up. A raster is premultiplied RGBA, as Core Image works, so a blur fades to clear and not to black. Every length is scaled with the working scale. center is [x, y].

step fields output extent (Swift) what the page does
crop x, y, width, height the overlap with the input (cropped(to:)) keeps that rectangle
render x, y, width, height (whole pixels) (0, 0, width, height) the rectangle as an image of its own, clear where the input does not reach (createCGImage(_:from:), CGImage.cropping(to:), UIImage(ciImage:))
clamp infinite outside its rectangle the image repeats its edge pixels (clampedToExtent())
sepiaTone intensity same the sepia matrix (r′ = .393r + .769g + .189b, g′ = .349r + .686g + .168b, b′ = .272r + .534g + .131b, as CSS sepia()), mixed with the input by intensity
edges intensity same per color channel, the Sobel gradient's magnitude × intensity, capped at 1, on black; alpha kept
crystallize radius (at least 1), center same a Voronoi diagram: one seed per cell of a grid radius wide through center, at a fixed pseudo-random point of its cell; each pixel takes the input's color at its nearest seed
pixellate scale (above 1; at most 1 adds no step), center same square cells scale wide on a grid through center, each the input's color at its middle
gaussianBlur radius (above 0) grown by ⌈3 · radius⌉ on every side (infinite stays infinite) a Gaussian of σ = radius as three box blurs per axis, fading to clear past the edges; a clamped image blurs against its repeated edges
unsharpMask radius (above 0), intensity same input + intensity × (input − its Gaussian blur of σ = radius against repeated edges); alpha kept
vignette intensity, radius, center and size (the input's middle and half its diagonal, from Swift) same with d = distance from center ÷ size, color × (1 + intensity · (cos⁴(atan(d · radius)) − 1)): radius 0 changes nothing (Core Image's identity value), radius 1 leaves a quarter of the light in the corners, a negative intensity brightens
tint r, g, b, a (0…1, straight) same every pixel the color, at its own alpha × a (UIImage.withTintColor)
colorControls saturation, brightness, contrast same on straight color: mixed with its luma (Rec. 709: .2125, .7154, .0721) by saturation, brightness added, then (c − ½) × contrast + ½; clamped to 0…1 (CIColorControls)
exposureAdjust ev same each channel × 2^ev in linear light (sRGB decoded and encoded again), capped at 1 (CIExposureAdjust)
vibrance amount same each channel moved toward the brightest by (max − mean) × −3 × amount: muted colors gain saturation, vivid ones keep (CIVibrance)
highlightShadowAdjust shadowAmount (−1…1, 0 keeps), highlightAmount (0…1, 1 keeps) same the luma l becomes l + shadowAmount · 1.5 · l(1 − l)³ − (1 − highlightAmount) · 1.5 · (1 − l)l³, the color scaled with it so hues keep (CIHighlightShadowAdjust)
colorMatrix r, g, b, a, bias (four numbers each) same on straight color: each channel the dot product of RGBA with its vector, plus its bias (CIColorMatrix)
photoEffect effect: chrome, fade, instant, mono, noir, process, tonal or transfer same Photos' looks (CIPhotoEffect…), approximated: Mono the luma; Tonal a flatter gray; Noir a harder, darker gray; Chrome saturation 1.25 and contrast 1.12; Fade muted with lifted blacks; Process cooler shadows; Transfer and Instant warmer
transform a, b, c, d, tx, ty the moved rectangle's bounds every point p goes to (a·p.x + c·p.y + tx, b·p.x + d·p.y + ty) (CIImage.transformed(by:)); each output pixel samples the input bilinearly where it came from, at the input's resolution over the transform's scale, so quarter turns and flips keep every pixel; a singular matrix gives an empty image

The page skips a step it does not know. The formulas approximate Core Image's; they are not its kernels. A SwiftBrowser Native app draws every step with Core Image itself (Native/Sources/SwiftBrowserNative/Views/Kinds/Bitmaps.swift). The adjustments, photo effects and transform are sent by @swiftbrowser/react's bitmap images (packages/react/README.md, "Bitmaps"); the Swift shim's CIFilter does not make them yet. The QR code generator adds no step: its output is a pixel source.

Filters (Swift). CIFilter holds key-value inputs with Core Image's names (kCIInputImageKey, kCIInputIntensityKey, kCIInputRadiusKey, kCIInputScaleKey, kCIInputCenterKey, …), defaults and inputKeys order (CISepiaTone: image, intensity 1; CICrystallize: image, radius 20, center (150, 150); CIEdges: image, intensity 1; CIGaussianBlur: image, radius 10; CIPixellate: image, center (150, 150), scale 8; CIUnsharpMask: image, radius 2.5, intensity 0.5; CIVignette: image, intensity 0, radius 1; CIQRCodeGenerator: message, correction level "M"). Numbers may be any numeric type, a center a CIVector or a CGPoint. outputImage appends the step and works out the extent; without an input image it is nil. The typed CIFilterBuiltins protocols are class-bound, so let filter = CIFilter.qrCodeGenerator() is configured from a non-mutating method, and read and write the same inputs. CIFilter(name:) knows the eight names; any other is nil, and applyingFilter with it returns the empty image.

QR codes#

CIQRCodeGenerator encodes in Swift (Sources/CoreImage/QRCode.swift, after Project Nayuki's reference encoder): byte mode, the smallest version 1 to 40 that holds the message at the level, the mask with the lowest penalty score. The output is one pixel per module with a one-module light margin, black on white, as a gray pixel source: "Anonymous\nyou@yoursite.com" at level M is version 2, 27 × 27 pixels. A message too long for version 40 gives a nil outputImage. The tests compare the matrices with a reference encoder's (node-qrcode, same masks) for versions 1, 2, 3, 7 and 15 across the four levels; codes of every level up to version 27 were also checked to decode with jsQR.

Sources and sizes#

UIImage(data:) and CIImage(data:) read the header of PNG, JPEG, GIF, WebP (lossy, lossless, extended), BMP, HEIC and AVIF files; anything else is nil, as on iOS for data that is not an image. A JPEG's EXIF orientation 5 to 8 swaps width and height and a HEIF's irot does the same, as browsers draw them; the UIImage reports .up, and CIImage(image:) sees the picture upright (iOS's CIImage(image:) drops the orientation). UIImage(data:scale:) divides the size by the scale. UIImage(systemName:) is never nil (the shim cannot tell which names exist); its cgImage is nil and CIImage(image:) of it is nil. UIImage(named:) reads the catalog's file ("Asset catalog files for Swift"): its cgImage and CIImage(image:) are that file's, and it is nil for a name neither the catalog nor the bundle has. UIImage() is 0 × 0.

Sharing#

ShareLink with an Image(uiImage:) item (or several) sends the recipes as bitmaps in the share request, after their sources' imagedata ops. The page draws each at full resolution (within the 16-million-pixel cap) into a PNG file named after the title (My QR Code.png) and shares or downloads it like a catalog image.

Encoding in Swift#

UIImage.pngData() and jpegData(compressionQuality:) answer at once, so they are computed in Swift, not on the page (Sources/ImageIO/ImageEncoding.swift): a PNG asked for as PNG, or a JPEG as JPEG, is the file as it is (a JPEG keeps its own quality); PNG files (any colour type, depth and interlacing), baseline and progressive JPEG files (Exif orientation applied, as the page draws them) and pixel buffers are decoded and encoded again: PNG as 8-bit RGB or RGBA, JPEG as baseline 4:2:0 at the quality libjpeg would use, transparency over black. Recipes whose steps are render (crops: CGImage.cropping(to:), CIContext.createCGImage, a renderer's canvas), place (an image drawn scaled into a rectangle: UIImage.draw(in:), CGContext.draw), roundedClip (a context's clip to a rectangle, rounded rectangle or ellipse) and tint (withTintColor) are drawn in Swift first, sampling the nearest pixel at pixel centers as the page's raster pipeline does; they must end on the image's own pixel grid (a render last). A graphics renderer's pngData / jpegData and CGImageDestination (public.png, public.jpeg, with kCGImageDestinationLossyCompressionQuality) encode the same way, as do asset catalog images, whose files Swift reads ("Asset catalog files for Swift"). Other file formats (GIF, WebP, HEIC, BMP), Core Image filters, and Core Graphics fills and strokes are only drawn by the page: their encoding is nil (an empty Data from a renderer, a failed CGImageDestinationFinalize).

Not yet#

Encoding filtered bitmaps and Core Graphics fills (above), other Core Image filters, custom kernels, CIImage.transformed(by:) and oriented(_:), CIColor and CIImage(color:); the orientation of UIImage(cgImage:scale:orientation:) and Image(_:scale:orientation:label:) is recorded, not applied. Sources stay in the page's memory for the run.

Swift package dependencies#

An Xcode project's Package Dependencies are XCRemoteSwiftPackageReference (a repository URL and a dependency rule) and XCLocalSwiftPackageReference (a folder) objects in project.pbxproj, listed in the project's packageReferences; a target links products of them through XCSwiftPackageProductDependency objects (packageProductDependencies). @swiftbrowser/xcodeproj reads both: XcodeProject.packages and, per target, packageDependencies (each product with its package). The CLI used to read only the product names and drop them, so an app that imported a package failed with "no such module" (or, for CodeScanner, was reported as an unsupported framework).

A local package can also be in the project without a package reference: a folder dragged into the navigator, a PBXFileReference with no file type, or the wrapper/folder type, whose folder holds a Package.swift. Xcode links its products by name alone (the XCSwiftPackageProductDependency has no package). Ice Cubes adds its 13 packages this way. When a product names no package, the reader looks in those folders. It takes the one whose manifest declares .library(name: "<product>", or failing that the one named after the product, and plans it as a local package.

The CLI (packages/cli/src/packages.ts) plans each package the app target links:

Plan When In the staged Package.swift
dependency a remote package with a rule, or a local package .package(url:…) with the rule (from: for up to next major, .upToNextMinor(from:), exact:, "a"..<"b", branch:, revision:) or .package(path:), and a .product(name:package:) per product; package is SwiftPM's identity (the URL's last component without .git, lower-cased)
stand-in the package's identity is in PACKAGE_STAND_INS nothing: the shim's module of the same name is linked when a source imports it, like the framework stand-ins
unresolved a rule this reader does not know, or a product whose package the project does not name nothing; check warns and the build reports the import

SwiftPM fetches a dependency and compiles it for the host (check) and for WASI (dev, build) like the app's own code, so a pure-Swift package works if it builds for WASI (swift-algorithms does). One that needs a platform framework fails to compile, and the error names it. Packages known not to work in the browser could be stood in for instead (PACKAGE_STAND_INS); none is today. Gifu, which Ice Cubes' avatars use, CodeScanner, RevenueCat, which Ice Cubes' app target links, and WrappingHStack were stood in for; they now build from their own sources: "Animated GIFs", "Code scanning", and RevenueCat (with a patch) and WrappingHStack below.

WrappingHStack (2.2.11, which Ice Cubes depends on through its own packages) builds from its own sources. It measures each item with UIHostingController(rootView:).sizeThatFits(in:) and breaks the lines from those widths before laying them out with stacks and spacers in a GeometryReader; its height comes back through an anchor preference. The hosting controller answers from the page's measurements ("Views measured for synchronous sizes", below): the first render has no widths, so the items are hidden; the page measures them off screen, and the next render breaks the lines with their real widths.

RevenueCat (purchases-ios-spm, product RevenueCat), the in-app purchase SDK Ice Cubes' app target links for its tip jar, is built from its own sources with a patch. The source adjustments cover most of what it takes from the Objective-C runtime (@objc protocols with optional requirements, overrides in extensions, #keyPath; packages/cli/src/objc.ts), and the shim the frameworks it calls (StoreKit with no products, Core Text's font registration, CryptoKit's Ed25519 and ChaChaPoly, zlib). Eight passages are left that no general adjustment can take, and packages/cli/src/packagePatches.ts replaces them before the adjustments: the advertising identifier and the tracking authorization, which it reads by calling methods on classes found by name (here there are none: no identifier, not determined); opening the subscription management page through UIApplication's openURL method implementation (here UIApplication.open); three overloads on [NSError.UserInfoKey: Any], which is [String: Any] here (NSError.UserInfoKey is String), so each would redeclare its [String: Any] twin; and a purchase's presentation context, whose window is under an #elseif after canImport(UIKit) but whose sheet window reads it under canImport(AppKit) alone: both hold in a build for macOS since the shim has AppKit (no Apple platform has both; an iOS build keeps the AppKit module off its search path, docs/notes/macos.md), so there the sheet window takes the #elseif's condition too. Each edit names the exact passage it replaces, in the release the patch was written for (5.102.3). The CLI checks every passage before copying the package: when one is not in the resolved release exactly once, the build stops with an error naming the file and the edit, and the patch has to be updated for that release (or the package pinned to 5.102.3). check reports the package as built against the shim (…), with SwiftBrowser's patch (8 edits, …). Its backend is reached through the page's fetch (RevenueCat's API answers CORS preflights from any origin, allowing the headers asked for); StoreKit has no products, so offerings have no packages to sell and a purchase fails as StoreKit refuses the payment. RevenueCatUI is not linked by Ice Cubes.

swiftui-introspect (SwiftUIIntrospect) is built from its own sources, as on iOS. It finds the UIKit view or controller SwiftUI draws a view with (the UICollectionView of a List) by adding two hidden view controllers next to the view (UIViewControllerRepresentable) and searching the UIKit hierarchy between them. The page draws SwiftUI without UIKit, so the search finds nothing, a normal outcome in the library (as for an OS version not listed in on:): customize is never called. The UIKit module declares the classes its tables name (Sources/UIKit/Introspectable.swift: scroll, table and collection views, text inputs, controls, windows, view and presentation controllers), keeping their state and drawing nothing, and makes views and controllers equal by identity as NSObject does (UIKit/Identity.swift). The library tags its probes with associated objects keyed by selectors: import ObjectiveC becomes import FoundationBridge, which has objc_setAssociatedObject, and unsafeBitCast(Selector(#function), to: UnsafeRawPointer.self) becomes the selector's _uniquePointer, one address per name as the runtime's uniqued selectors have (packages/cli/src/stage.ts). Its public import SwiftUI (the package makes imports internal by default) brings the companions in with the same access level.

A stand-in for a package of a package takes its place through a redirect package (vendor.ts, below). check reports each package and the path it took:

✓ package purchases-ios-spm (github.com/RevenueCat/purchases-ios-spm, up to next major from 5.86.0): SwiftBrowser's stand-in, not fetched (the SDK needs the Objective-C runtime, and the browser has no App Store to buy from)
✓ package swift-algorithms (github.com/apple/swift-algorithms, up to next major from 1.2.0): a SwiftPM dependency of the build (Algorithms)

and an import of a dependency's product counts as supported ("from package swift-algorithms") instead of unknown. The project's own Package.resolved is not copied: SwiftPM resolves the rule afresh into the staging package's.

Packages that import SwiftUI#

SwiftPM builds a dependency as its own manifest says, and no manifest says to depend on SwiftBrowser: on iOS, import SwiftUI finds the system framework. Built as declared, such a package fails with "no such module 'SwiftUI'". So the CLI builds it from a copy (packages/cli/src/vendor.ts), when the toolchain is there, before staging:

  1. Resolve. .swiftbrowser/<App>/Packages/.resolve/ is a package that declares only the app's package dependencies (the dependency plans above) and links their products. swift package show-dependencies --format json --output-path dependencies.json resolves it and lists the whole graph: each package's identity, version and folder (SwiftPM's checkout, or a local package's own folder).

  2. Choose. A package is copied when a Swift file of its own (manifests and Tests/ aside; only its Sources folder when it has one, so a demo app beside the package does not count) imports a module SwiftBrowser provides in Apple's place (SHIM_MODULES: SwiftUI, Charts, SwiftData, FoundationBridge and the stand-in frameworks), and so is every package that depends on a copied one. A package that is plain Swift all the way down is left to SwiftPM.

  3. Copy. swift package dump-package gives the package's targets (cached in the copy by the manifests' hash); a regular or executable target whose sources import a shim module is built against the shim. The package's folder goes to Packages/<identity>/ (dot folders left out). Its Swift sources get the app's adjustments (transformSource: Foundation and the bridge next to import SwiftUI, #Preview blocks and PreviewProvider structs blanked, with the attribute lines just above them); in a shim target's sources, as in the app's, import Foundation brings FoundationBridge too, since a public default argument (session: URLSession = .shared) may only use a member of a module its own file imports, and the alias file's URLSession is the bridge's. Each shim target gets the generated _SwiftBrowserFoundation.swift (the app's alias file, made public) in its folder, with a Bundle.module on the bridge's Bundle: SwiftPM's own accessor puts module on Foundation's, which a staged Bundle.module or bundle: .module does not look at. It is the folder SwiftPM names the target's resources (<package>_<target>.bundle) in the app's bundle, or the app's bundle while package resources are not copied there.

  4. Patch the manifest. Package.swift and any Package@swift-*.swift keep everything they declare, with lines appended to the end. package is a class, so the appended code changes it after the manifest made it:

    package.dependencies.append(.package(name: "SwiftBrowser", path: "…"))
    let _swiftBrowserProducts: [String: [String]] = ["Shimmer": ["SwiftUI", "Charts", "FoundationBridge"]]
    for target in package.targets {
        guard let products = _swiftBrowserProducts[target.name] else { continue }
        target.dependencies += products.map { .product(name: $0, package: "SwiftBrowser") }
        target.swiftSettings = (target.swiftSettings ?? []) + [.define("SWIFTBROWSER")]
    }
    

    A package that depends on another copy also maps its package.dependencies: a .sourceControl dependency whose identity has a copy becomes .package(path:) to it (with its name:, when it had one). Reading Package.Dependency.kind takes tools version 5.6; an older manifest keeps its URL.

  5. Stage. The staging manifest depends on each copy by path, in place of the URL or folder; a copy that is a dependency of a dependency is declared there too. That declaration is what covers a manifest too old to repoint: SwiftPM lets the root's dependency take the place of a deeper one with the same identity (with a warning that a future version will make it an error). A copy's folder name is its identity, so .product(name:package:) keeps resolving.

Errors in a copy of a local package are mapped back to the package's own files, as the app's are; a remote package's name the copy under .swiftbrowser/. check says which packages were copied:

✓ package Tags (/work/Tags): built against the shim (Tags imports SwiftUI) (Tags)
✓ package SwiftUI-Shimmer 1.5.1, a dependency of a dependency: built against the shim (Shimmer imports SwiftUI)

Vendoring runs before the import report, so an app's import of a module from a dependency of a dependency counts as supported too. Ice Cubes imports Nuke, which only its DesignSystem package declares.

Packages also meet APIs apps rarely use; two came with this: EnvironmentValues.layoutDirection (always .leftToRight; a view may set it for the views it contains, and the layout does not mirror), and DispatchQueue (FoundationBridge/Dispatch.swift; the WASI SDK has no Dispatch). Every queue is the main queue: async runs the work on the main actor's next turn, asyncAfter(deadline:) after a Task.sleep, so headless runs keep their virtual clock, and sync runs it in place. DispatchTime (with +/- of seconds or a DispatchTimeInterval) and DispatchQoS come with it; work items, groups and memory-pressure sources came later ("The frameworks under SwiftUI"), semaphores and other sources do not. The generated alias file points the four names at the bridge, so a host check, where Foundation re-exports Dispatch, type-checks the same API.

Packages written against Apple's SDK in Swift 5 mode lean on two things Swift without Objective-C lacks. SwiftUI's modifiers are nonisolated in Apple's SDK, so a nonisolated helper can call content.environment(…) (EmojiText's namespace does); the shim's View extensions are nonisolated too, except the few whose work is the main actor's (modifier, onReceive, swipeActions, labelStyle, alerts, sheets, onChange, photosPicker, @Query's). And (dict[key] as? AnyObject)?.doubleValue finds doubleValue on any object through Objective-C: in a file that reads a number that way (doubleValue, intValue, boolValue…), staging turns as? AnyObject into as? _AnyObjectValue, FoundationBridge's protocol for the numbers, booleans, strings and NSNumbers a dictionary of Any holds, whose members are optional as the dynamic lookup's are.

packages/cli/test/fixtures/Packages is an Xcode project with two local packages: Badges (a view and #if SWIFTBROWSER) and Tags (a view that shimmers), which depends on SwiftUI-Shimmer by URL. CI builds it and runs it headless: the tag reads "Loading" until a DispatchQueue.main.asyncAfter sets its title.

Notifications#

import UserNotifications links a stand-in module (Sources/UserNotifications) over the browser's Notification API. UNUserNotificationCenter.current() keeps the pending requests and schedules each with an executor timer of its own (Task.sleep, at most a day at a time, since setTimeout cannot wait longer than 24.8 days); when one runs out, it asks the page to show the notification. The page schedules nothing, so notifications are delivered only while the page is open: one due tomorrow appears tomorrow if the tab is still open (a background tab's timers may run late, by up to a minute in Chrome), and never if it was closed. Repeating triggers are rescheduled after each delivery.

Every exchange is a host request (Phase 13's channel) of kind notification:

action params page value
status reads Notification.permission { "permission": "default" | "granted" | "denied" | "unsupported" }
request Notification.requestPermission() when the permission is default, else the standing answer same
show id, title, subtitle, body, silent, badge new Notification(title, { body, tag: id, silent }) with the subtitle and body as the text, one line each (through the service worker registration where the constructor is refused, as on Android); navigator.setAppBadge(badge) { "shown": bool }
close ids closes the notifications shown with those tags {}
badge badge navigator.setAppBadge (0: clearAppBadge) {}
pushSubscribe applicationServerKey registers the site's service worker and subscribes to the push service (asking for the permission first when it is open) { "subscription": { "endpoint", "keys": { "p256dh", "auth" } } }
pushUnsubscribe ends the subscription {}
receive the next push or click the service worker reported { "type": "push", "payload" } or { "type": "click", "payload", "action" }

unsupported means the page has no Notification API (Safari on iPhone shows notifications only for a site added to the Home Screen). It maps to UNAuthorizationStatus.denied; default is .notDetermined, granted .authorized. requestAuthorization answers true for granted, false for a refusal, and fails with UNError(.notificationsNotAllowed) when unsupported. A click on a notification focuses the page and closes it.

The module has UNUserNotificationCenter (getNotificationSettings / notificationSettings(), requestAuthorization and add in both forms, getPendingNotificationRequests / pendingNotificationRequests(), removePendingNotificationRequests(withIdentifiers:), removeAllPendingNotificationRequests(), the delivered notifications and their removal, setBadgeCount, delegate), UNMutableNotificationContent (title, subtitle, body, badge, sound, userInfo and the identifiers; the request keeps a copy), UNNotificationSound (.default, named and critical sounds: the browser plays its own or, without a sound, none), UNTimeIntervalNotificationTrigger (positive, and at least 60 s when repeating, as on iOS), UNCalendarNotificationTrigger (the next date matching the components in their calendar and time zone, else the current ones; nextTriggerDate()), UNNotificationRequest, UNNotification, UNNotificationSettings, UNAuthorizationOptions, UNAuthorizationStatus, UNNotificationPresentationOptions and UNError. A UNUserNotificationCenterDelegate's willPresent decides how a delivery is presented (without .banner, .alert or .list nothing is shown; .badge sets the badge). A center without a delegate shows every delivery, since the app is necessarily open when one fires (iOS would show none in the foreground). didReceive is never called: the page gets no answer from a notification.

Headless runs answer from the app itself: the permission is default until the app requests it, then granted; show answers { "shown": true } once granted; deliveries happen on the virtual clock (SB_RUN_MS), so a 5-second trigger's show op follows the "ms": 5000 clock event in the log. _Runtime._hostRequest(kind:params:headless:) takes that answer as its headless argument.

Push notifications#

Remote notifications are Web Push. UIApplication.registerForRemoteNotifications() (UIKit's RemoteNotifications.swift, over UserNotifications' RemoteNotifications.swift) sends pushSubscribe with the app's application server key, the server's VAPID public key: SB_WEB_PUSH_KEY in the environment, which the page sets from the app's registry entry (webPushKey in swiftbrowser.json), unless the app sets _RemoteNotifications.applicationServerKey. The page registers the service worker the site serves next to the page (sw.js, Web/public/sw.js; Service-Worker-Allowed in _headers lets its scope be the site), subscribes through it with userVisibleOnly, and answers with the subscription as PushSubscription.toJSON() gives it. The app delegate's didRegisterForRemoteNotificationsWithDeviceToken gets that JSON as UTF-8 bytes: a server that sends through APNs on iOS sends through the push service here, to the subscription's endpoint, encrypted with its keys (web-push on npm). Without a push service (Safari before 16.4, an iPhone tab not on the Home Screen), a key, or the permission, the request fails (unsupported: …, push: …, denied: …) and the delegate's didFailToRegisterForRemoteNotificationsWithError gets the error, as on a simulator. isRegisteredForRemoteNotifications is whether a subscription was made; unregisterForRemoteNotifications sends pushUnsubscribe.

The worker shows every push as a notification, reading the payload in APNs' shape (aps.alert.title, aps.alert.body, aps.badge) or the web's (title, body, badge), so one payload serves both platforms; a tag or id replaces an earlier notification with the same one. It tells the open pages about each push and each click (swiftbrowser:push and swiftbrowser:notificationclick messages), opening the page when none is open: navigator.serviceWorker queues a message until the page listens, so a click that launched the page is not lost. Once subscribed, the app sends receive requests one after another; each answers with the next event. A push that arrived while the page is open goes to the app delegate's didReceiveRemoteNotification(userInfo:) with the payload. A click goes to the notification center delegate's didReceive, with a UNNotificationResponse whose notification carries the payload as userInfo, the title and body read as above, a UNPushNotificationTrigger, and actionIdentifier of UNNotificationDefaultActionIdentifier (the worker shows no action buttons). The notification is among the delivered ones. Nothing is received until the app registers: the page keeps what the worker reported until then.

Headless runs have no push service: pushSubscribe fails with headless: no push service, so the delegate's failure method is called, and no receive is sent.

The frameworks under SwiftUI#

Packages that serve SwiftUI apps are written against more than SwiftUI: UIKit's UIImage, Core Graphics contexts, Image I/O, Combine, CryptoKit, os, and the parts of Darwin's Foundation that Linux and WASI lack (Operation queues, Dispatch work items, the Objective-C runtime's associated objects). The shim has each of them as a Swift module of the SwiftBrowser package, linked when a source imports it (STAND_IN_FRAMEWORKS). The measure is Nuke 13.2.0, which builds from its own sources, unchanged, and loads, decodes, resizes and caches images in the browser (packages/cli/test/fixtures/NukeApp).

Module What it has
UIKit UIImage (the SwiftUI shim's, re-exported, with pngData/jpegData encoded in Swift, "Encoding in Swift"), UIColor (RGBA, HSB, the system colors, cgColor), Color(uiColor:) and Color(_: UIColor), UIScreen.main (scale 3), UIApplication (state, lifecycle notification names; open opens web and mail URLs in a new tab, "Rich text", and the app's own schemes go to onOpenURL, "Signing in"), UIFont (below), drawing with UIGraphicsImageRenderer (below), the views (UIView, UIImageView, UILabel, UITextView, UIScrollView, UIActivityIndicatorView, CALayer, NSLayoutConstraint and its anchors), view controllers, UIHostingController, and UIViewRepresentable / UIViewControllerRepresentable; UIPasteboard (in memory; the general pasteboard's writes also go to the system clipboard), UIActivityViewController (presenting it shares through the page), paste delegates, UIImageWriteToSavedPhotosAlbum (a download) ("Sharing and media"). A representable's view tree is drawn by translating it into SwiftUI views ("UIKit views in SwiftUI"); a view no representable shows keeps its state and draws nothing. UIKit brings Foundation, Core Graphics, Image I/O and UniformTypeIdentifiers along, as on iOS.
CoreGraphics The shim's CGFloat, CGPoint, CGSize, CGRect, CGImage (re-exported), their integer initializers, CGAffineTransform, CGColor, CGColorSpace, CGImageAlphaInfo, CGBitmapInfo, CGPath/CGMutablePath (rectangles, rounded rectangles, ellipses), and CGContext (below)
ImageIO CGImageSource (from data, incremental, properties, images, thumbnails; an animated GIF's frames, delays and loop count, "Animated GIFs"), CGImagePropertyOrientation, the kCGImage… keys, CFData/CFString/CFDictionary as Swift's Data/String/[String: Any], and CGImageDestination for PNG and JPEG ("Encoding in Swift")
Combine OpenCombine (MIT), built as the module Combine with the SwiftUI shim's ObservableObject, ObservableObjectPublisher and @Published in place of its own (Sources/Combine/SwiftUIObservation.swift), and its single-threaded locks (#if WASI) on every platform; NotificationCenter.Publisher is a Combine publisher (with demand) as well as what onReceive takes
CryptoKit SHA256, SHA384, SHA512, Insecure.SHA1, Insecure.MD5 in plain Swift, with HashFunction and Digest; P-256 key agreement (below); Curve25519.Signing (Ed25519: keys, deterministic signatures, verification that refuses S ≥ l) and Curve25519.KeyAgreement (X25519, refusing an all-zero secret); ChaChaPoly (ChaCha20-Poly1305: nonces, sealed boxes and their combined form, authenticated data, CryptoKitError.authenticationFailure) with SymmetricKey and SymmetricKeySize. Checked against RFC 8032, 7748 and 8439's vectors; not constant-time.
os os_unfair_lock and OSAllocatedUnfairLock<State> (never wait: there is one thread; taking either twice traps), OSLog, os_log (to standard error), Logger, and signposts (dropped)
OSLog Re-exports os (on Apple platforms Logger is OSLog's; EmojiText imports it)
CommonCrypto CommonDigest's CC_MD5, CC_SHA1, CC_SHA256, CC_SHA384, CC_SHA512, their …_DIGEST_LENGTH constants and CC_LONG, and the …_CTX contexts with Init/Update/Final, over CryptoKit's hashes (TelemetryDeck hashes with CC_SHA256)
Security The keychain: SecItemAdd, SecItemCopyMatching, SecItemUpdate, SecItemDelete for generic and internet passwords, with Apple's kSec… keys (and their values: "acct", "svce", …), kSecReturnData/Attributes/PersistentRef, kSecMatchLimitOne/All, kSecAttrSynchronizable (with …Any), and the errSec… codes. Items live in $HOME/Library/Keychains/keychain.json, a file in the app's home that the page keeps across launches. That makes them as private as the page's other storage, not encrypted, in one access group. Real KeychainSwift builds against it unchanged.
Accelerate vImage's vImage_Buffer and box convolutions (vImageBoxConvolve_ARGB8888, _Planar8). A CGContext's data (zeroed memory, made on first use) identifies the context. A convolution between two contexts becomes a recipe step: the box's variance as a gaussianBlur (σ² = (k² − 1) / 12, so passes add up as vImage's do), after a clamp for kvImageEdgeExtend. Buffers of real memory are convolved on the spot. Nuke's GaussianBlur runs this way.
MobileCoreServices Re-exports UniformTypeIdentifiers (iOS's MobileCoreServices brings UTType along; Gifu relies on it) and the old kUTType… constants, as identifier strings
AVFoundation Players over the page's media elements: AVPlayer, AVQueuePlayer, AVPlayerLooper, AVPlayerItem, AVAudioPlayer (with no view, from a timer too once the viewer has tapped the page); AVAudioEngine with player nodes, files, buffers and the stock effects over the page's Web Audio engine ("An audio engine"); AVAsset/AVURLAsset (metadata from a media probe), CMTime and Core Media's time functions, AVPlayerLayer (a UIKit layer that draws its player), AVAudioSession (kept, succeeds); image generation fails, exports copy the file ("Video and audio"). Capture sessions with the page's camera, a metadata output that reports the codes the page reads, a photo output and a preview layer ("Code scanning"). Re-exports AudioToolbox.
AVKit VideoPlayer(player:) and (player:videoOverlay:), AVPlayerViewController (through a representable), as a video element with the native controls; Picture in Picture is unsupported (isPictureInPictureSupported() is false) ("Video and audio").
AppIntents AppIntent, @Parameter (IntentParameter, a class as on Apple), IntentResult and its .result(…) forms (dialog, value, snippet view, opened intent), IntentDescription, IntentDialog, IntentFile, AppEntity, EntityQuery, AppEnum, DisplayRepresentation (with Image), TypeDisplayRepresentation, AppShortcutsProvider and its builder and phrases, and SwiftUI's Button(intent:) and Toggle(isOn:intent:). The browser has no Shortcuts, Siri, Spotlight or widgets: shortcuts, titles, descriptions and queries are declarations nobody reads. The app's own intents still run: a button with an intent performs it when tapped (in a main-actor task; a thrown error is dropped), with the parameters the app set. An unset optional parameter reads nil; an unset non-optional one stops the app with a message naming it, since there is no Shortcuts to ask for it.
CoreHaptics The engine, patterns (with AHAP dictionaries), events, parameters, curves and players. CHHapticEngine.capabilitiesForHardware() reports neither haptics nor audio, as an iPad does, so code that checks it (Ice Cubes' HapticManager) skips haptics; code that does not still runs, and plays nothing. UIKit's feedback generators (impact, selection, notification) are there and do nothing: the Vibration API that some Android browsers have only buzzes.
NaturalLanguage NLLanguage and NLLanguageRecognizer with a real, small identifier (LanguageIdentifier.swift). Each letter's script settles languages with a script of their own (Greek, Hebrew, Thai, Korean, Georgian…). Within a shared script, a language scores points for its frequent words and distinctive letters: Latin (23 languages), Cyrillic, Arabic/Persian/Urdu, Hindi/Marathi, and Han with kana (simplified or traditional Chinese, Japanese). The points become probabilities through a softmax (e^(1.5 × points)), weighted by the script's share of the letters and by n / (n + 0.5) for its n letters. About four common words give ≥ 85% (Ice Cubes' threshold for tagging a post or asking before posting); short or unknown text stays unconfident, and text without letters has no dominant language.
AudioToolbox System Sound Services: AudioServicesCreateSystemSoundID registers an existing file, and playing it is silent (system sounds are not played; AVFoundation's players are, "Video and audio"). AVFoundation re-exports it, as on iOS.
Symbols SF Symbols' effect types (.bounce, .pulse, .variableColor, .scale, .appear, .replace, .breathe, .rotate, .wiggle, .drawOn…) with their options. They are declared in SwiftUI, whose .symbolEffect(_:isActive:), .symbolEffect(_:value:) and .contentTransition(.symbolEffect(…)) take them; this module re-exports them. The page draws symbols as still glyphs, so the modifiers leave the view as it is.
QuickLook .quickLookPreview(_:) and (_:in:) open the URL in a new tab (a file of the app's as a blob, downloaded when the browser blocks the tab) and reset the binding; QLPreviewController does the same for its current item when presented, then dismisses itself.
CoreTransferable Transferable and its representations (DataRepresentation, FileRepresentation, ProxyRepresentation, CodableRepresentation, the builder, suggestedFileName, exportingCondition), SentTransferredFile/ReceivedTransferredFile, exported(as:), init(importing:contentType:), and String, Data, URL, AttributedString as transferable values. The representations run: export takes the first one that can, import the first that accepts the content type, and a received file is a temporary copy removed once the closure returns. SwiftUI sits on it and re-exports it (and UTType), as on iOS ("Sharing and media").
Photos PHPhotoLibrary (.addOnly is authorized, .readWrite limited), performChanges with PHAssetChangeRequest/PHAssetCreationRequest: each created photo or video is downloaded through the page. Fetches (PHAsset, PHAssetCollection) return nothing and PHImageManager answers nil. PhotosUI re-exports it ("Sharing and media").
LinkPresentation LPLinkMetadata (declared in UIKit, which the share sheet needs, and re-exported), LPMetadataProvider, which fetches the page with URLSession and reads its title and Open Graph tags, failing with LPError.metadataFetchFailed where the site does not allow CORS (most do not), and LPLinkView, which draws nothing.
Translation TranslationSession, .translationTask, .translationPresentation and LanguageAvailability over Chrome's built-in Translator and LanguageDetector (a translate host request); elsewhere every pair is unsupported ("Translation and the on-device language model").
FoundationModels The whole API, with @Generable and @Guide; the model is unavailable (.deviceNotEligible), as on an iPhone without Apple Intelligence, so responses fail with assetsUnavailable ("Translation and the on-device language model").
AuthenticationServices ASWebAuthenticationSession and SwiftUI's WebAuthenticationSession (\.webAuthenticationSession): the provider's page opens in a popup and the redirect to the app's scheme comes back through the page's callback page ("Signing in").
SafariServices SFSafariViewController: presenting it opens its URL in a new tab, then dismisses it and calls the delegate ("Signing in").
CoreText The font manager's registration: CTFontManagerRegisterFontsForURL / Unregister… succeed for a file that exists (the page registered the bundle's fonts before the app started, "Custom fonts"; a font file elsewhere is not loaded) and fail with CTFontManagerError.fileNotFound in kCTFontManagerErrorDomain otherwise; CTFontManagerScope. Fonts, lines and frames are not here.
WebKit WKWebView and the types around it keep their state and draw nothing; load fetches nothing and evaluateJavaScript fails ("Signing in").

CryptoKit also has P-256 key agreement (P256.KeyAgreement private and public keys in their raw, x9.63 and compressed forms, and ECDH shared secrets) in plain Swift, with Montgomery arithmetic over four 64-bit limbs; it is checked against RFC 5903's test vector and is not constant-time. Ice Cubes registers its push key with it. Foundation brings SecRandomCopyBytes and ObservableObject/@Published along, as Darwin's does, and has LocalizedStringResource and String(localized:), which look keys up in the app's string tables ("Localized strings"). SwiftUI's @Entry is a macro of the shim's SwiftDataMacros plugin that expands as Apple's does, so every app now builds that plugin (in seconds, from the prebuilt swift-syntax). App types can conform to ToolbarContent with a body: their @Environment properties are resolved from the environment where the toolbar is.

Objective-C without its runtime. Swift on Linux and WASI has no Objective-C interop, and WebAssembly could not host the runtime anyway: its indirect calls check the callee's exact type, which objc_msgSend's signature-agnostic jump violates. Packages mostly use Objective-C for target/selector APIs, so the staging rewrites those (rewriteObjC in stage.ts):

  • @objc, @objc(name), @objcMembers and the Interface Builder attributes are dropped.
  • #selector(handle(_:)) and #selector(self.handle(_:)) become Selector(Self.handle(_:), name: "handle(_:)"). That is the unbound method, which the selector calls on the API's target. It dispatches dynamically, so an override runs.
  • #selector(Type.method) keeps its type; #selector(model.refresh) (a method of another object) is called bound; getter:/setter: selectors only have a name.

NotificationCenter is FoundationBridge's (NotificationCenter.swift), aliased into every module like Timer. On WASI, Swift 6.4's Foundation keeps only the new message-based center: no addObserver(forName:object:queue:), no post(name:object:), no selectors. Code that observes notifications would type-check in check and then fail the browser build. The bridge's center has the classic API: block and selector observers, removeObserver (a token, or every observation of an observer, optionally by name and object), post, notifications(named:) as an async sequence, and publisher(for:) for onReceive. Observers run synchronously when a notification is posted, whatever queue they were added with.

NSAttributedString() and NSMutableAttributedString() (also written let text: NSMutableAttributedString = .init(), as Ice Cubes' composer does) make empty strings. corelibs Foundation has no init() on them, and an extension cannot redeclare NSObject's. So FoundationBridge (AttributedStrings.swift) adds init(_empty: Void = ()), which the call .init() resolves to and the mutable subclass inherits. The source is not rewritten.

Locks (FoundationBridge/Locks.swift). On Apple platforms import Foundation brings Darwin's os_unfair_lock along, and the bridge re-exports the os module's, so a package's #if os(iOS) branch that locks with it after import Foundation alone compiles (SwiftSoup's Mutex). WASI's libc module leaves pthread.h out, so a POSIX branch finds no mutex functions; on WASI the bridge declares pthread_mutex_init/lock/trylock/unlock/destroy and the pthread_mutexattr_ ones, which succeed at once (the page has one thread). A package whose sources call them is built from a copy against the shim (check says it "uses POSIX mutexes"), like one that uses selectors.

Dispatch. The WASI SDK has no Dispatch module; the bridge's queues stand in (FoundationBridge/Dispatch.swift: every queue runs its work on the main actor, in order). The staging turns import Dispatch into import FoundationBridge, and a package that imports Dispatch is built from a copy (check: "uses Dispatch"). DispatchSpecificKey with setSpecific(key:value:) and getSpecific(key:) is there: DispatchQueue.getSpecific(key:) reads the queue whose sync/async work is running (the main queue outside any), which is how SQLite.swift's connections tell they are already on their queue.

Core Foundation's types (CFString, CFURL, CFData, CFDictionary, CFIndex, OSStatus…) are plain Swift values (String, URL, …) declared once, in the shim's CoreFoundationTypes module, which Security, Image I/O, Audio Toolbox and FoundationBridge re-export (as each brings CoreFoundation along on Apple platforms), so a file that imports several sees one of each. CFURLCreateWithString parses as Core Foundation does: characters a URL may not hold are percent-encoded, escapes already in the string are kept (not encoded again), and square brackets are kept only in the host.

SQLite. SQLite.swift (Bodega's storage, Ice Cubes' timeline cache) builds with its own copy of SQLite's C source (the CSQLite package), which compiles for wasm32-wasip1 as it is: SQLite's WASI build is single-threaded, without loadable extensions, and locks nothing. Its database files are ordinary files of the app's home, read and written through the page's WASI file system (with the rollback journal beside them), so the page keeps them across launches like the app's other files.

Selector (FoundationBridge/Selector.swift) compares by name. The APIs that take one are NotificationCenter.addObserver(_:selector:name:object:), which holds the observer weakly as iOS 9 and later do, Timer's target:selector: forms, UIKit's CADisplayLink, which fires 60 times a second on the executor's clock while it is added and not paused, and UIControl.addTarget(_:action:for:). A method the file declares @MainActor is bound to its target in a closure instead, Selector(name: "tick", isolated: { (target: Proxy) in target.tick }): Swift 6 rejects naming a main-actor method of a class that is not Sendable unapplied (Proxy.tick), as Gifu's display link proxy would. A package that uses selectors or @objc is built from a copy even when it imports nothing of the shim's. KVO (@objc dynamic observation), perform(_:with:afterDelay:), responds(to:) and @objc optional protocol requirements are not covered; code that uses them fails to compile.

StoreKit 2's Transaction, Product's types, VerificationResult, Storefront and AppStore are declared too. A web app sells nothing through the App Store, so the transaction sequences end at once and latest(for:) answers nil, which lets TelemetryDeck's purchase tracking compile.

With #if os(iOS) on, packages read the device: UIKit answers as an iPhone (UIDevice: iOS, .phone, portrait, and an identifierForVendor made once and kept in the app's defaults), with UIAccessibility's settings off, UITraitCollection in light mode, and background tasks that are only tokens (the page gets no background time). FoundationBridge has DispatchSource.makeTimerSource, which fires on the executor's clock, ProcessInfo.isiOSAppOnMac (false), Bundle.appStoreReceiptURL (nil) and Darwin's sysctlbyname, for which every name is unknown. Real TelemetryDeck builds against these, unchanged.

The browser is an iPhone. The staging treats an app's and its packages' code as iOS code:

  • #if os(iOS) holds. Each os(iOS) in a #if or #elseif line becomes (os(iOS) || SWIFTBROWSER), since the build's real OS is WASI, or Linux for check.
  • import SwiftUI brings UIKit along, as it does on iOS (UIColor, UIApplication.shared and Color(uiColor:) need no import), and UIKit is linked wherever SwiftUI is. That costs a small app about 0.5 MB raw, 0.15 MB gzipped.
  • #if canImport(UIKit) therefore holds too.
  • UIKit re-exports Core Image, as on iOS (CIImage, CIFilter with only import UIKit).

UIColor has iOS's semantic colors (labels, fills, grouped backgrounds, the system grays and tints). Their components are the light-mode values; Color(uiColor:) sends them by name, so on the page they follow the color scheme.

Darwin's Foundation also brings what corelibs Foundation lacks on Linux and WASI: RelativeDateTimeFormatter (FoundationBridge, aliased into each module like OperationQueue) phrases an interval in English in the four unit styles ("2 hours ago", "2 hr. ago", "2h ago", "in two hours") and, with dateTimeStyle = .named, as "now", "yesterday" or "next week". It takes the largest unit with a nonzero amount, counting weeks of 7 days, months of 30 and years of 365. FileManager.containerURL(forSecurityApplicationGroupIdentifier:) answers Shared/<group> in the app's home (/data, kept across launches), since the browser runs the app alone.

AttributedString(markdown:options:baseURL:) comes from FoundationBridge too (Sources/FoundationBridge/Markdown.swift). It parses Markdown's inline syntax the way CommonMark and GitHub define it, into the attributes Apple's parser sets:

  • inlinePresentationIntent (a FoundationBridge attribute, since swift-foundation declares it only for Apple platforms) for emphasis, strong emphasis, code spans, strikethrough and hard line breaks;
  • link for [text](url) and <…> autolinks;
  • imageURL on the alt text of ![alt](url).

Escapes and HTML entities are decoded. Block syntax is not interpreted: .full concatenates paragraphs, .inlineOnly turns line breaks into spaces, and .inlineOnlyPreservingWhitespace keeps the text's whitespace. Ice Cubes turns every post's HTML into Markdown and parses it this way. EmojiText marks custom emoji as images with an emoji:// URL.

Image I/O and Core Graphics over recipes. A CGImage is a recipe the page runs (Bitmaps and Core Image, above). CGImageSourceCreateWithData reads the file's header (format, size) without decoding it, and CGImageSourceCreateImageAtIndex makes a CGImage whose recipe is the file. The page decodes it when it draws it, with its EXIF rotation applied, so the properties report orientation 1 (up). A CGContext records too. Drawing an image in a rectangle adds a place step (sx, sy, tx, ty: each point p goes to (p.x × sx + tx, p.y × sy + ty), Core Graphics' y-up space, the same as Core Image's). A clip to a rectangle, a rounded rectangle or an ellipse adds a roundedClip step (x, y, width, height, rx, ry). makeImage() renders the canvas (render). An image drawn at its own size at the origin, with no clip, comes back as it was, which is Nuke's decompression pass. Only the last image drawn is kept; fills and strokes are accepted and not drawn; data stays empty. In the page, place with equal scales only relabels the raster (the same pixels cover the new rectangle); unequal scales resample it at the finer resolution. roundedClip multiplies each pixel by its coverage, from its distance to the edge, over one raster pixel.

What Darwin's Foundation brings along. Files that import only Foundation use names Linux's and WASI's Foundation do not have. The generated _SwiftBrowserFoundation.swift, which every file of the app and of each package built against the shim sees, settles them:

  • typealiases to FoundationBridge's OperationQueue, Operation and BlockOperation (operations run on the main actor, in order, each on a later turn; an asynchronous operation, which overrides start(), isExecuting and isFinished, finishes when it calls didChangeValue(forKey: "isFinished") as it would for key-value observing: that runs its completion block and lets a serial queue start the next one); DispatchWorkItem, DispatchWorkItemFlags, DispatchGroup (notify runs once everything that entered has left), DispatchSource and DispatchSourceMemoryPressure (never fires); URLCache (the browser's HTTP cache; this object stores nothing), CachedURLResponse, URLSessionTaskMetrics, URLAuthenticationChallenge, URLCredential, URLProtectionSpace; CFAbsoluteTime; and os's os_unfair_lock types (os is always linked for them);
  • functions that forward to FoundationBridge: CFAbsoluteTimeGetCurrent, autoreleasepool (runs its body), objc_setAssociatedObject and objc_getAssociatedObject (a table that holds each object weakly), class_getInstanceSize (an estimate: 8 words), the os_unfair_lock_… functions, and DispatchTime's + and -, which Dispatch declares globally so that .now() + 0.5 finds them (a static operator is not considered when the left operand is an implicit member).

FoundationBridge also fills in what NSObject and Objective-C bring along on Apple platforms: NSError.UserInfoKey (here a typealias of String, so [NSError.UserInfoKey: Any] is [String: Any], and two overloads that differ only in it collide), UserDefaults.value(forKey:), UserDefaults and URLResponse as Hashable by identity, URLResponse.description, DispatchTime.distance(to:), qualityOfService on operations and queues (ignored), and URLError's connectivity codes (dnsLookupFailed, internationalRoamingOff, callIsActive, dataNotAllowed). UIKit's UIDevice and UIApplication are @preconcurrency @MainActor, as Swift imports them from Objective-C: code in the Swift 5 language mode that reads them off the main actor gets a warning, not an error.

Also there, for SDKs written against Apple's frameworks: bytes and lines as async sequences (FileHandle.bytes, read in chunks; URLSession's bytes(for:) and bytes(from:), whose body arrives whole; .lines on any sequence of bytes, split at \n, \r\n and \r), URLSession.data(from:) and data(for:) without a delegate (Apple declares both forms, and a protocol may require the short one), NSObject.responds(to:) (there is no runtime to find a method by name: always false, so code takes its fallback), gethostbyname and hostent on WASI (no resolver: nil), and in CoreFoundationTypes CFError (NSError) and CFGetTypeID with the …GetTypeID() functions, where a boolean NSNumber (objCType c, as JSONSerialization makes them) is a CFBoolean. UIKit adds UIColor(dynamicProvider:) and resolvedColor(with:) (the page has one appearance, light), UIApplication.value(forKey: "sharedApplication") (how SDKs that may run in an app extension reach the application), UIAlertController and UIAlertAction (presenting one records it and shows nothing, like any presented controller; SwiftUI's .alert is what the page shows), and a sheet presentation controller's detents. SwiftUI's styles have the lower levels of any style (Color.blue.gradient.quaternary), at the secondary, tertiary and quaternary label colors' opacities.

URL loading with a delegate. URLSession(configuration:delegate: delegateQueue:) and dataTask(with:) without a completion handler report to the delegate, on its queue: didCreateTask, then didReceive response with a completion handler (.allow goes on, anything else ends with URLError(.cancelled)), the whole body in one didReceive data, didFinishCollecting metrics and didCompleteWithError. On Apple platforms the delegate methods are @objc optional; here they are protocol requirements with default implementations that do what URLSession does without them (allow, follow the redirect, default handling, cache). The staging rewrites the optional calls, delegate?.urlSession?(…), to delegate?.urlSession(…). Tasks are Hashable by identity, and the session retains its delegate until it is invalidated.

Two more rewrites. ProcessInfo.processInfo.physicalMemory becomes _swiftBrowserPhysicalMemory (4 GiB on WASI, the most a wasm32 module can address; Foundation's answer elsewhere): swift-foundation answers 0 on WASI, the getter is reached through the class's vtable, out of a linker wrap's reach, and Nuke caps each download at a tenth of it, so every image would fail. Submodule imports of the shim's frameworks (import UIKit.UIImage, import os.log) import the module.

SwiftUI. NukeUI also needed withTransaction (both forms), and .onDisappear, now in the runtime: a node keeps its action, and when a pass removes it (unmounting cancels its task as before) the action runs after the render, innermost first, before the pass's onAppear actions.

Nuke in the browser. A LazyImage load is Nuke's own pipeline: its DataLoader downloads with URLSession (the page's fetch, so the image host must allow CORS), ImageDecoders.Default decodes with CGImageSource, the decompression pass draws in a CGContext (a no-op, above), ImageProcessors.Resize draws in a smaller one (a place step), and the memory cache and task coalescing are Nuke's. Nuke 13 decodes at the request's scale, 1 unless the app sets ImageRequest.scale (on every platform), so a 300 × 200 px photo is 300 × 200 points. A GIF shows its first frame, as Nuke does without an animated-image view.

packages/cli/test/fixtures/NukeApp links Nuke and NukeUI 13.2.0 from the app and from a local package, Avatars, that depends on Nuke by URL. CI builds it and runs it headless with the pictures' bytes as fetch answers (responses.json): the photo is 300 points wide, each avatar is a 300 px picture Nuke resized to 64 points (place then render; 192 pixels, at the 3x scale of the iPhone the page stands for), the GIF is reported as one, a 404 fails, and onCompletion counts the photo.

Stand-ins deeper in the graph. When a package depends on one the shim stands in for (PACKAGE_STAND_INS) by URL, the graph gets a redirect in its place, Packages/<identity>/, whose libraries are each an empty target (_<Product>StandIn) that depends on SwiftBrowser's module of that name; the dependent's manifest is pointed at it like at any copy.

Compression and StoreKit#

Compression. import Compression links a stand-in (Sources/Compression) that computes DEFLATE in Swift (Deflate.swift): a complete decoder (stored, fixed and dynamic Huffman blocks, zlib and gzip wrappers with their Adler-32 / CRC-32 checks) and an encoder that writes a fixed-Huffman block over a hash-chain LZ77 search, or stored blocks when that would be larger. Its output is valid DEFLATE, though larger than zlib's. COMPRESSION_ZLIB is raw DEFLATE, as on Apple platforms, and is the only algorithm with a codec: compression_encode_buffer / compression_decode_buffer (a decode longer than dst_size is truncated to it), the compression_stream functions, and the overlay's InputFilter / OutputFilter work for real. LZFSE, LZ4, LZMA, Brotli and LZBitmap have their constants, Algorithm(rawValue:) answers nil for them, and using one fails as a failed call does (0 bytes, COMPRESSION_STATUS_ERROR, FilterError.invalidState). zlib's inflate API (z_stream, inflateInit2_ with zlib / gzip / raw / automatic window bits, inflate, inflateEnd, adler32, crc32) lives in the same module (Zlib.swift), and import zlib links a module that re-exports it (Sources/zlib). Streams hand out output once their input holds the whole stream (decoding is retried only when the input has doubled, so the work stays linear), then in as many pieces as the caller's buffers need.

StoreKit without an App Store. StoreKit (Sources/StoreKit) covers StoreKit 1, StoreKit 2 and the StoreKit views, with nothing behind them. StoreKit 1's classes are NSObject subclasses as in the SDK; the @objc optional requirements of SKPaymentTransactionObserver, SKPaymentQueueDelegate and SKRequestDelegate are ordinary requirements with empty defaults. A products request answers no products (every identifier invalid); SKPaymentQueue.canMakePayments() is false; a payment added to the queue becomes a failed transaction (SKError.paymentNotAllowed) that stays in transactions until finished; restoring finishes at once with nothing; a receipt refresh fails with SKError.unsupportedPlatform. Observers and delegates hear on the main actor's next turn. In StoreKit 2, Product.products(for:) finds none, so no Product exists (its purchase methods throw PurchaseError.productUnavailable); subscription statuses are empty and intro offers ineligible; AppStore.canMakePayments is false; Storefront.current is nil; Transaction's sequences, Storefront.updates, PurchaseIntent.intents, Message.messages and Status.updates end at once; AppTransaction.shared, AppStore.showManageSubscriptions(in:) and presentOfferCodeRedeemSheet(in:) throw StoreKitError.unsupported; ExternalPurchaseCustomLink.isEligible is false. As on iOS, StoreKit re-exports UIKit, which now has UIScene / UIWindowScene and UIApplication.connectedScenes (the page is the one scene, always foreground-active, with no UIWindows). StoreView, SubscriptionStoreView (its marketing content, then a note) and ProductView show StoreKit's "unavailable" state, which a custom ProductViewStyle receives as .unavailable; manageSubscriptionsSheet, offerCodeRedemption and refundRequestSheet set their binding back to false (the latter two report a failure); onInAppPurchaseStart / Completion never run. SwiftUI gained .containerBackground(for:), drawn behind the view itself.

UIKit drawing and fonts#

Drawing. UIGraphicsImageRenderer(size:format:) makes a Core Graphics recording context (Sources/CoreGraphics) of size × the format's scale (the screen's 3 by default) pixels, with UIKit's coordinates (points, origin at the top left: the transform flips y and scales), pushes it as the current context while its image { context in … } actions run, and returns the canvas as a UIImage of size points. UIImage.draw(in:) draws the image's bitmap into the current context: a place step that scales and moves it, then the canvas's render (Sources/UIKit/Graphics.swift). As in the context itself, the image drawn last is the canvas; fills and strokes draw nothing. UIGraphicsBeginImageContextWithOptions / GetImageFromCurrentImageContext / EndImageContext and UIGraphicsPush/PopContext use the same stack. A catalog image draws its file; a symbol (or an SVG catalog image) has no bitmap in Swift and draws nothing. The drawing's pngData is computed in Swift ("Encoding in Swift"). This is how EmojiText sizes a custom emoji to the text: the downloaded image, drawn at the font's height.

Rendering mode and tint. UIImage keeps a renderingMode (withRenderingMode); withTintColor(_:renderingMode:) adds a tint step to a bitmap, which paints its shape in the color. Image.renderingMode(_:) returns the image unchanged: a bitmap draws its own colors, a symbol the foreground color. Image.symbolRenderingMode(.palette) draws a symbol's layers in the foreground styles' levels (see ShapeStyle); other modes draw it in the foreground color.

UIFont. A point size, a name, a weight and a design, with SF Pro's metrics per point (ascender .952, descender −.241, cap height .705, x-height .53), and iOS's line height, the ascender plus the descender (17 → 20.29). preferredFont(forTextStyle:compatibleWith:) follows Dynamic Type with the page's size table (Web/src/layout/typography.ts) for the trait collection's preferredContentSizeCategory (Large unless one says otherwise), and UIFontMetrics.scaledValue(for:) scales by the text style's ratio to its Large size. UIFontDescriptor.withDesign(.rounded), Font(UIFont) and NSKeyedArchiver coding (Ice Cubes keeps the chosen font that way) come with it. A font made by name (UIFont(name:size:), never nil) keeps the name, and Font(UIFont) makes it Font.custom(name, fixedSize:) with its weight, which the page draws in the app's font of that name ("Custom fonts"); its metrics in Swift stay SF Pro's.

Environment. .font(_:) with a text style or a size sets the environment's font for the views below (@Environment(\.font), nil without one; a weight alone leaves it), as SwiftUI's does, and displayScale is 3. ProcessInfo.isLowPowerModeEnabled is false.

Custom fonts#

An app ships its own fonts as .ttf / .otf files in its bundle (listed under UIAppFonts in its Info.plist, or registered with CTFontManagerRegisterFontsForURL) and names them with Font.custom(_:size:). The page loads them the same way.

Files. The CLI publishes an Xcode target's font files with its other resources: those in its Copy Bundle Resources phase, and those of its synchronized folders, where every file not compiled is a resource as in Xcode (packages/xcodeproj); a folder of sources publishes the font files it holds unless resources in swiftbrowser.json lists its resources. Before the module loads, the page reads every font file in the bundle (Web/src/appFonts.ts) for what Core Text knows it by: its family (name ID 16, else 1), PostScript name (6) and full name (4), its weight (OS/2 usWeightClass, or a variable font's wght range), whether it is italic (OS/2 fsSelection) and its vertical metrics (hhea ascender, descender and line gap, OS/2 cap height). Each face is added to document.fonts under its family with its weight and slant, and under its PostScript and full names, which name that face alone, and the page waits for them to load, so the first layout already measures in them (text laid out before fonts register is laid out again). WOFF files are skipped; a .ttc registers its first font. Every font file in the bundle is registered, listed under UIAppFonts or not.

Font object. Font.custom adds name (the family or PostScript name, as given), with size and relativeTo (.custom(_:size:) scales like body, .custom(_:size:relativeTo:) like that style, .custom(_:fixedSize:) not at all); Font.italic() adds italic: true. A weight alone (.bold(), .fontWeight) keeps the name and the slant; a new font without them is the system font, upright.

{ "size": 18, "relativeTo": "body", "name": "Literata", "italic": true }

Drawing and measuring. The CSS family list starts with the name (a CSS string) and goes on with the design's stack, so a name the app has no font for draws in the system font, as SwiftUI does. The engine measures the same font shorthand on its canvas. For a name the app does have, a line is as tall as that font makes it, its ascender, descender and line gap rounded up to a 3x pixel (Literata at 18: 27), and a paragraph's lines are that far apart; its capitals start its ascender less its cap height below the line's top (--sb-cap-inset on the text). Bold and italic pick the family's bold and italic files as Core Text does (a slanted or emboldened face where it has none). italic is part of the font in the font shorthand: a View .italic() above (a styled italic) slants every font inside, one set further in too, and the engine measures it so.

Signing in#

An iOS app signs in to a web service (OAuth) by registering a redirect URI in its own URL scheme (icecubesapp://) and letting ASWebAuthenticationSession, or SwiftUI's WebAuthenticationSession, show the provider's page and catch the redirect. A page cannot receive a redirect to a custom scheme, so the shim swaps the scheme for a page of its own and turns the result back into the app's URL. Nothing in the app changes.

The app's schemes. The CLI reads CFBundleURLSchemes from each CFBundleURLTypes entry of the target's Info.plist (INFOPLIST_FILE). urlSchemes in swiftbrowser.json replaces them, and is the only source for a folder of sources. The registry entry carries them to the page (AppSpec.urlSchemes), and the page passes them to the app as SB_URL_SCHEMES (comma-separated). It also passes SB_WEB_AUTH_CALLBACK: its callback page, <base>/app/oauth-callback.html. A session's callbackURLScheme is added once it starts.

The rewrite (FoundationBridge, _WebAuthRedirects). A redirect URI in one of the app's schemes becomes the callback page. The scheme goes in sb_scheme, and anything after scheme: other than // goes in sb_target:

icecubesapp://          → …/app/oauth-callback.html?sb_scheme=icecubesapp
myapp://auth/done?x=1   → …/app/oauth-callback.html?sb_scheme=myapp&sb_target=%2F%2Fauth%2Fdone%3Fx%3D1

Only the parameters redirect_uri and redirect_uris are rewritten (a space- or newline-separated list item by item, a JSON array item by item), in the query of a URLSession request, in a JSON object (top-level keys) or application/x-www-form-urlencoded body of 64 KiB or less, and in the authorize URL a session opens. The app's registration, the authorize request and the token exchange therefore agree. On the way back, the callback page's URL becomes scheme:target, with the provider's query items (code, state, …) added and the fragment kept: icecubesapp://?code=….

webAuth request (Phase 13 request kind; params WebAuthRequestParams, value WebAuthResult).

action Params Answer
start url (the rewritten authorize URL), callbackScheme, callbackPage, ephemeral {url}: the URL the sign-in window ended at (the callback page's)
cancel none {}. The window closes; a pending start fails with cancelled: …

The page opens url in a popup at once (window.open, before any await, while the tap's activation may still count). When the browser blocks it, the page shows a dialog ("Sign in to ", Continue / Cancel) and opens the popup from the Continue click. One sign-in runs at a time; a new start cancels the previous one. A popup the viewer closes (checked every 500 ms, with one extra tick for a callback that is just arriving) fails with cancelled: …, as does a dismissed prompt. A page that cannot open windows fails with unsupported: ….

The callback page (Web/public/app/oauth-callback.html, served as is) sends {type: "sb-web-auth-callback", url: location.href} by postMessage to its opener (same origin) and on BroadcastChannel("sb-web-auth"), which still reaches the page when a provider's Cross-Origin-Opener-Policy cut the popup off from it. It then removes the code from its history entry and closes.

The app's side. WebAuthenticationSession.authenticate(using:callbackURLScheme:preferredBrowserSession:), the additionalHeaderFields: and callback: variants, and ASWebAuthenticationSession (start, cancel, canStart, completion handler on the main actor) all return the rebuilt app URL. cancelled: … and headless: … become ASWebAuthenticationSessionError.canceledLogin; anything else, or a URL that is not http(s), becomes .presentationContextInvalid. cancel() does not call the completion handler. Limits: a popup shares the browser's cookies, so ephemeral sessions are not private; a page cannot add headers to a window's navigation, so additionalHeaderFields are not sent; a Callback.https redirect lands on another site, which the page cannot observe; and the provider must allow the page's origin (CORS) on the endpoints the app calls with URLSession (mastodon.social answers /oauth/token with access-control-allow-origin: *).

Headless. An SB_RESPONSES entry whose url or prefix matches the authorize URL plays the provider: with callback, its value is the answer; with code, the answer is the authorize URL's redirect_uri with code (and the request's state) added. With no matching entry, the sign-in fails as cancelled: headless, ….

onOpenURL. A URL in one of the app's schemes that the app opens itself (a link, openURL, UIApplication.open) goes to the onOpenURL handlers of the views on screen instead of the page, as on iOS. Other URLs open as before. Universal links and NSUserActivity are not delivered.

SafariServices. Presenting an SFSafariViewController opens its URL in a new tab (an openURL request), then dismisses the controller and calls the delegate's safariViewControllerWillOpenInBrowser and safariViewControllerDidFinish. A URL that is not http(s) is not opened. Configuration and tints are kept, with nothing to style.

WebKit. WKWebView and the types around it keep their state and draw nothing. load records the URL and fetches nothing, no navigation delegate method is called, and evaluateJavaScript fails with WKError.javaScriptExceptionOccurred.

Sign in with Apple#

ASAuthorizationAppleIDProvider, its request and credential, and SwiftUI's SignInWithAppleButton (Sources/AuthenticationServices/AppleID.swift). An ASAuthorizationController given an Apple ID request, the environment's AuthorizationController, or the button sends a host request of kind appleSignIn:

{ "op": "request", "id": 5, "kind": "appleSignIn",
  "params": { "action": "signIn", "scopes": ["fullName", "email"], "nonce": "…", "state": "…" } }

The answer is the credential as ASAuthorizationAppleIDCredential has it: user (the stable identifier), email and fullName (shared the first time only, as on iOS), identityToken (a JWT whose sub is the user), authorizationCode, realUserStatus and state; a dismissed sheet fails cancelled: … (ASAuthorizationError.canceled). On a page Apple's JS (appleid.auth.js) shows its popup once the app named its Services ID and return URL with configureSignInWithApple, both registered with Apple for the page's domain; before that the request fails unsupported: … (.notHandled). The native app shows the system sheet (ASAuthorizationController, Host/AppleSignInBridge.swift) when it has the entitlement (swiftbrowser native init --sign-in-with-apple). { "action": "credentialState", "user": "…" } answers { "state": "authorized" | "revoked" | "notFound" | "transferred" | "unknown" }: natively from the provider, unknown on a page, which cannot ask Apple (the shim's credentialState(forUserID:) answers .authorized, leaving the app's own session to decide). The button is drawn from the button, image (apple.logo) and text views in the black, white or white-outline style of .signInWithAppleButtonStyle(_:); @swiftbrowser/react has the same SignInWithAppleButton, signInWithApple() and appleCredentialState().

UIKit views in SwiftUI#

UIViewRepresentable and UIViewControllerRepresentable put UIKit views on the page. On Apple platforms they are SwiftUI API that needs UIKit's types; here they are declared in UIKit (Sources/UIKit/Representable.swift), which import SwiftUI brings along. They are built from public SwiftUI alone: the reconciler has no special case for them, and no element kind was added.

Lifecycle. A representable's body is _UIViewRepresentableHost<Self> (or _UIViewControllerRepresentableHost<Self>), a view whose @State holds the coordinator and the view for as long as the node is mounted. Its body runs makeCoordinator() and makeUIView(context:) the first time and updateUIView(_:context:) on every pass (the runtime skips a representable whose value is unchanged, as SwiftUI does). An .onDisappear calls dismantleUIView(_:coordinator:); mounting it again makes a new coordinator and view. The Context has the coordinator, the environment and a transaction. A controller representable's controller loads its view (loadView, viewDidLoad), hears viewWillAppear on its first pass and viewDidAppear after it, and viewWillDisappear / viewDidDisappear when it leaves. dismiss(animated:) on it calls the environment's dismiss, so a picker that dismisses itself closes the sheet it is in.

Drawing. A second view, _UIKitTranslationHost, translates the UIKit view tree into SwiftUI views on every pass (Sources/UIKit/ViewTranslation.swift); the reconciler diffs the result like any body, so an unchanged view sends no ops.

UIKit Drawn as
UIImageView Image(uiImage:) of image (or highlightedImage): .resizable() for scaleToFill, plus .aspectRatio(contentMode: .fit/.fill) for the aspect modes; unscaled and aligned for center, top, topLeft…. A symbol takes tintColor. A GIF file shows its first frame; Gifu's GIFImageView shows each frame as its image ("Animated GIFs").
UILabel Text: attributedText's runs when set (font, color, underline, strikethrough, kerning, baseline offset, link, inline presentation intent), else text; font, textColor, numberOfLines (0: no limit), textAlignment.
UITextView, editable TextEditor, below.
UITextView, read-only Text of attributedText's runs inside textContainerInset + lineFragmentPadding, in a ScrollView when isScrollEnabled.
UIActivityIndicatorView ProgressView() tinted with color, while it animates.
UIHostingController's view Its rootView, inline, whose state lives as long as the hosting view keeps its place.
UIScrollView Its subviews in a ScrollView of contentSize when that is larger than its bounds and isScrollEnabled, else a container offset by contentOffset. A zoom draws the delegate's viewForZooming(in:) with .scaleEffect(zoomScale, anchor: .topLeading).
a view whose layer (layerClass) or a sublayer is an AVPlayerLayer The player's video element filling the view, with videoGravity, no controls (AVPlayerViewController's view: with them).
any view Subviews in a ZStack(alignment: .topLeading), each at its frame; backgroundColor, layer.cornerRadius, clipping, the layer's border, alpha × layer.opacity, isUserInteractionEnabled = false. A hidden view draws nothing.

UIColor.label and the secondary, tertiary and placeholder label colors are drawn as .primary / .secondary text, so text follows the page's color scheme. Not drawn: shadows, layer contents and other sublayers, transforms, draw(_:), attachments, paragraph styles, and the controls (UISwitch, UISlider… draw as plain views).

Size. The translation sits in a custom Layout (_UIKitViewLayout), measured by the page like any other (Phase 6). It answers the representable's sizeThatFits(_:uiView:context:) when that returns a size, else its content's own size; a view with no intrinsic size fills the proposal. Placing it sets the root view's frame and lays the tree out: autoresizingMask by UIKit's proportional rule, simple constraints (per axis, equalities to the superview or a placed sibling: two of edge, center and length settle it; inequalities and priorities are kept and ignored), and layoutSubviews() (viewWill/DidLayoutSubviews for a controller).

Changes outside a pass. A change to a drawn property (frame, hidden, alpha, colors, subviews, an image view's image, a label's text, a text view's text and focus, a scroll view's offset and zoom, a hosting controller's root view, setNeedsLayout, a constraint's constant…) bumps the translation host's @State revision, and that node renders again without updateUIView.

Text views. An editable UITextView is a texteditor showing its text in its font, color and alignment, inside its insets. A user's edit is worked out by comparing the old text with the new (UTF-16 NSRange); the delegate is asked textView(_:shouldChangeTextIn:replacementText:), the text changes (new characters take typingAttributes), selectedRange moves to the end of the replacement, and the delegate hears textViewDidChange and textViewDidChangeSelection. A refused edit stays on the page until the text next changes. Focus is shared both ways through the texteditor's focused prop and focus events (SwiftUI's TextEditor takes .focused(...) too): becomeFirstResponder() focuses the text area, and the delegate hears textViewDidBeginEditing / textViewDidEndEditing. The page does not report the caret, so selectedRange is that guess; an editable view's attributes are kept, not drawn; label and text view sizes are estimates from the font's size. UITextViewDelegate and UIScrollViewDelegate have defaults for every method; delegate?.textViewDidChange?(textView) compiles through optional function-typed properties of the methods' base names.

Attributed strings. UIKit declares the attribute keys corelibs Foundation lacks (.font, .foregroundColor, .link, .underlineStyle, .kern, .paragraphStyle, .attachment…) with Apple's raw values, and converts between NSAttributedString and AttributedString, links and inline presentation intents included.

Windows. A representable's view is in no window: window is nil and willMove(toWindow:) / didMoveToWindow() are never called (Ice Cubes' WindowReader never hears from it).

Controllers. UIHostingController(rootView:) keeps rootView, sizingOptions and safeAreaRegions; shown by anything but a representable, it draws nothing. Its sizeThatFits(in:) (and its view's sizeThatFits(_:) and intrinsicContentSize) answers from the page's measurement of the root view, zero until there is one.

Views measured for synchronous sizes (SwiftUI/Runtime/Measurements.swift). Code that asks for a SwiftUI view's size and needs the answer at once (UIHostingController.sizeThatFits(in:)) gets the page's measurement, a render late. A view without one answers nil (the hosting controller: zero) and joins a pending list. The render that asked adds one more root-level element: a styled wrapper (opacity 0, hitTesting false) around a layout element whose children are the pending views, in the root's environment. The page's pass asks it as it asks a custom layout (sb_layout), and it asks for its children's sizes at a zero, unspecified and infinite proposal; given them, it stores them by the view's reflected description and asks for a render, after the pass, in which no body is skipped as unchanged (the code that measured keeps the sizes in objects of its own, which only a body that runs again makes anew). The measured view then answers what LayoutSubview.sizeThatFits would for the proposal (the ideal for an unbounded axis, otherwise the proposal clamped to the minimum and maximum), and the element goes away until another view is pending. A call about children that are not the pending views (more were added since) answers nothing; the next one carries them. After four rounds in a row that only brought new views (one whose description changes on every render), measurements no longer re-render. Headless runs have no page to measure: such views stay at zero there. UIImagePickerController.isSourceTypeAvailable is false for every source; a picker shown by a representable draws a "Camera Unavailable" notice whose Cancel calls imagePickerControllerDidCancel.

texteditor (added prop). focused: bool, as textfield's (Phase 12).

Scrolling to a view, multi-line fields, view section headers#

Lazy stacks. LazyVStack / LazyHStack (alignment, spacing, pinnedViews) emit the vstack / hstack elements of VStack / HStack. Their rows are built lazily, as a List's are (below). pinnedViews puts pinned on the element and the page holds the section headers and footers at the visible area's edges ("Pinned views", below).

Lazy rows. SwiftUI builds the rows of a List (and a Form), LazyVStack or LazyHStack as they come into view; building them all made long lists slow and, on phones, ran the page out of memory (a timeline of real posts is tens of thousands of elements). A lazy container's rows are its content seen through groups (ForEach, Group, conditionals, modifiers spread over a ForEach such as .onDelete or .listRowSeparator), Sections and views with a body of their own; any other view is part of one row, and a group inside it is built with the row. A keyed group (ForEach) of more rows than a batch (12) mounts the first batch, then a lazyspacer element:

kind props children
lazyspacer axis: "vertical" | "horizontal", remaining: number (rows not built); a leading one: edge: "leading", extent, estimated?, built, batch (below) none

It takes no space (in a list, a row of no height without a cell or separator; the row before it ends the card). After every layout pass and on every scroll, the page reports each spacer within one screen of the visible area of its scrollview or list (the viewport outside one), along its axis, once: {"type": "lazy", "id": n}. Swift mounts the next batch; the spacer after it is a new element (its key counts the rows before it), so a spacer still in view asks again. A list's built rows stay built (their state, tasks and onAppear too), and onAppear of a row runs when it is built, as on iOS when it scrolls in (pagination at the last row works the same way). A scrollTo(x) whose target is the id of a row of a lazy group builds the rows up to it first. The keyed rows of a lazy container are scroll targets by their ForEach identity, each in a scrollID element as a view with .id(_:) is (ScrollViewReader, below), so scrollTo(item.id) and .scrollPosition(id:) work on ForEach(items) without an .id on the rows; a row with an .id of its own under another value is a target under both, its own inside. Headless runs, which have no page to scroll, show the first batch.

On the page, a LazyVStack's or LazyHStack's rows far from the visible area are unbuilt again, as SwiftUI's are: in a Swift app whose page said so at launch (SB_LAZY_WINDOW=1) and in a React app on the page (@swiftbrowser/react's mount). The group's first child is then a leading lazyspacer (edge: "leading", with built, the rows after it, batch, and extent, how long the rows unbuilt before them were along its axis; it is that long, and no gap follows it, the gap before it being the one before the row after it). After a layout or a scroll, the page asks to drop whole batches of the rows more than two screens before the visible area ({"type": "lazy", "id": n, "drop": 24, "extents": [610, 598]}, extents what each batch took, which the spacer then stands for) or after it ("dropEnd": 12), keeping a batch; and when the spacer, standing for rows, comes within a screen, it asks for the last batch dropped back (lazy alone). Each spacer is asked once: the app answers with a new one. Lists, grids and other renderers keep every row they build.

A row a Swift app unbuilds is unmounted: its onDisappear runs, its tasks are cancelled and its @State is gone, and built again it is a new view whose onAppear runs (SwiftUI's lazy stacks do not promise a row's state past the screen either; state to keep belongs in the model). The page counts a row as one element, so a Swift group whose rows are several (a row and its Divider) keeps the rows it built. A scrollTo (or a .scrollPosition(id:) set) to a row far outside the built ones moves the window to that row's batch without building the rows between: a book of some hundred pages opens at its bookmark with twelve pages built. The batches skipped were never laid out, so the spacer counts them apart ("estimated": 6, left out of extent) and the page sizes each as a batch of that stack's rows as long as the ones it last laid out are on average (Web/src/renderer.ts, estimateLazyExtents; the pass that first lays a stack's rows out is laid out twice). When such a batch is built its real length takes the place of the reckoned one, and the average moves with the rows on the page; the page scrolls the difference away (keepLazyAnchors), so the rows in view stay where they are.

A LazyVGrid / LazyHGrid builds its cells the same way (@swiftbrowser/react), 48 at a time, as a batch of cells is a few rows of a grid. Its lazyspacer is the grid's last child; the page lays the grid's cells out without it and puts it at the grid's end (below its last row, or after its last column), where it takes no space.

A picker that is one of a menu's items (SwiftUI's Menu { Picker(…) }, an inline picker listed as a checked section) is drawn by the menu's popover from its options: the page builds no rows of its own for it, so a menu of hundreds of choices is one element until it opens.

Lazy menus. A Menu's items and a .contextMenu's are built when the menu opens, as on iOS, and dropped when it closes: a timeline's rows each carry a menu or two, whose items were half of Ice Cubes' page. Until it opens, the menu element has its label only (the contextmenu element its content) and "deferred": true. The page sends {"type": "menu", "id": n, "open": true} when the viewer taps the menu (or long-presses the context menu's content); the app answers with the items and "deferred": false, and the page opens the popover then (at once, as the event's ops come back with it, or at the commit that brings them). When the popover closes the page sends "open": false, after any tap of the item chosen. Headless runs, whose event scripts tap menu items, and the mock apps build the items eagerly and send no deferred.

The native host (SwiftBrowserNative's MenuElement and ContextMenuElement) asks when SwiftUI presents the menu. SwiftUI builds a menu's items as it presents it and lets them go as it dismisses it, so the items' appearance is the signal: until the items arrive, a deferred menu lists one disabled row in their place, whose appearance as the menu opens sends "open": true. The app answers inside that call (the host's calls into JavaScript are synchronous, docs/native.md), and the presented menu shows the items in the row's place. A second after the last item went, the host sends "open": false (an item appearing meanwhile, the menu opened again, keeps it), so that a chosen item's tap, which a context menu may send only as its dismissal ends, comes first. That is iOS; on macOS the host still asks a deferred menu for its items as the menu comes on screen and keeps them, as it is not known there that a menu's items are built at its presentation and that items arriving while it is open are shown. A context menu does the same on iOS: it presents with a preview, and its animation showed the row standing in for the items (Loading…) before the app's answer reached the open menu. So ContextMenuElement asks for the items as its content comes on screen and keeps them; a context menu's items are few (a file's rename and delete), unlike a Menu's.

@swiftbrowser/react's Menu and contextMenu defer their items the same way (packages/react/src/lazyMenu.tsx): the element answers the menu event itself, rendering the items while it is open. A phone's Codon had a thousand hidden elements in its sixteen menus (the wavetables, the samples, the programs), rebuilt whenever their plate rendered. A Menu builds its items eagerly, and sends no deferred, with lazy={false}, among an open menu's items (a submenu, whose rows the popover lists with no event of its own), and in a headless host (swiftbrowser-shot, which sets __sbHeadless), so that scripts still tap a menu's items without opening it. A native app's menus defer too, the host asking for the items as it presents the menu on iOS (above). The in-memory renderer (@swiftbrowser/raster), like the page, sends the chosen row's event before "open": false.

ScrollViewReader. Inside a reader, .id(x) wraps its view in a styled element whose style carries "scrollID": true (outside a reader .id adds nothing, as before). proxy.scrollTo(x, anchor:) queues a request with a serial number, increasing across all readers, and re-renders the reader; in that pass the marked element whose id is x gets "scrollTo": {"anchor": {"x": 0.5, "y": 1} | null, "serial": n} in its style ("axes": "horizontal" | "vertical" | "both" limits the scroll to those axes; .scrollPosition(id:) names its scroll view's, so setting it moves that view alone and not a list the view sits in). After laying out a pass that brings a new serial, the page (Web/src/scrollTo.ts) scrolls every scrolling ancestor (scrollview on its axes, list vertically) so the element's anchor point meets the same point of the visible area; anchor: null scrolls as little as shows the element. A command for a scroll view the pass laid out in no room along the axis (a pane not opened yet, a view sized from a measurement the app does not have yet) waits: nothing of the view shows, and an offset set on it is lost when it gets its size. The page keeps the command (the mark may be gone from the element by then) and carries it out after the first pass that gives the view some room, without animation, unless a newer command for the same element came or the element went; the view reports no position while it has no room. The in-memory renderer (@swiftbrowser/raster) does the same. The scroll is smooth when the pass's commit has an animation: the browser's smooth scrolling, except on a snapping scroll view (scrollTargetBehavior) along one axis, which runs as a finger's page does (Web/src/touchPaging.ts, animateTo): the snap off, an eased run whose last frame writes the offset itself, the snap back on, and its position reported once it rests (not before, as for a finger's drive). A browser animating a scroll-snapped container may snap it again once the animation ends or the content moves under it; Safari does, which made a calendar's chevrons jump half a page after the slide while a swipe of the same pager did not. .scrollPosition(id:anchor:) calls scrollTo when the view appears with a value and when the binding changes, and reads back: the first scrollview below it (not the scroll views inside that one: a pager's pages that scroll on their own) carries "reportsPosition": true (and "positionAnchor": {x, y} when an anchor was given), and when its scrolling settles (no scroll event for 120 ms, or the browser's scrollend; not while a finger is on the view, whose lifting starts the wait; a snapping view that settled off its snap points, between a swipe and the browser's snap animation, waits up to six settles more to be carried onto one) the page (Web/src/scrollPosition.ts) finds the marked element at the anchor point of the visible area along the scroll axis (the leading edge by default: the one whose extent holds the point, else the next one after it) among the marked elements whose nearest scroll view it is, and sends {"type": "scrollposition", "id": n} to that element, once per change of target (a scrollTo command on the view starts that over: the app set its binding itself, and where the view rests may not be it); the app sets the binding to that view's id without scrolling to it. A target wider than the view (a page the viewer pans within) stays the position until the point leaves it. Headless: scrollposition:31. Not supported: a ForEach's own ids as targets (views need .id), and .id resetting identity and state.

Scroll visibility. .onScrollVisibilityChange(threshold:_:) (iOS 18) wraps the view in a styled with "scrollVisibility": {"threshold": t} (0.5 by default) and a handler. After each layout and on scrolling (once a frame) the page (Web/src/scrollVisibility.ts) measures the share of the box inside its nearest scroll view's visible area: the scroll view's box less the bar it runs under (topInset) and a bar covering its bottom (bottomInset), as content under a bar is not in view; outside a scroll view, the root's box. The box is visible when some of it is in view and the share is at least t (along both axes, so a box off to the side is not in view). The page sends {"type": "scrollvisibility", "id": n, "visible": b} when that changes, and once when the box is first checked. An inline title given to an empty bar fades in over 0.15 s, as a collapsing large title does, for a header that hands its name to the bar this way (a logo beside a name is better a .largeTitle toolbar item, which collapses on its own). Headless: scrollvisibility:31:false.

Default scroll anchor. .defaultScrollAnchor(.bottom) above a ScrollView (iOS 17; the for: .initialOffset | .sizeChanges | .alignment overload sets the same thing) emits "defaultScrollAnchor": {"x": 0.5, "y": 1} on the scrollview. After the pass that creates it the page (Web/src/scrollAnchor.ts) scrolls it so that point of the content meets the same point of the viewport: the end in view, as a chat opens on its latest message. After every later pass that changed the content's or the viewport's extent on an axis the view scrolls on, the anchor is kept if the viewer was at it before the pass (within 2 px of the anchored offset, judged by the offset scrollSync.ts read before the pass's writes, so a clamp the pass itself caused does not count): new lines at the end keep the end in view, a viewer who scrolled up to read stays where they are, and a viewport the keyboard shortens keeps the end. A pass that changed no extent leaves the offset alone, whatever it is. .defaultScrollAnchor(nil) emits nothing. SwiftBrowser Native hands the anchor to SwiftUI's defaultScrollAnchor.

Multi-line text fields. TextField(_:text:axis: .vertical) is a textfield with "axis": "vertical": the page creates a <textarea> and the engine measures the text (or the placeholder) wrapped at the proposed width in the context font, at least the style's lineLimitMin and at most its lineLimit lines. Return inserts a line break, except with submit, where Return submits and Shift-Return breaks the line.

Line-limit ranges. .lineLimit(2...4), .lineLimit(...4) and .lineLimit(2...) set the style's lineLimit to the upper bound and, when the lower bound is above 1, lineLimitMin. Text uses the upper bound only.

textCase. .textCase(.uppercase | .lowercase) sets the environment's textCase; texts below are cased when emitted.

Section view headers and footers. A Text (or optional Text) header or footer stays the section's header / footer string. Any other view becomes a child of the section: a sectionheader before the rows and a sectionfooter after them (props {}). In a list each is laid out in the content width, a header in the headline font (17 semibold) lifted 8 into the gap above the card and 10 above it, a footer in the footnote font 7.33 below the card, both in the secondary color. As in iOS 26, header texts keep their case (neither the shim nor the engine upper-cases them; a .textCase(.uppercase) still does). Outside a list, header, rows and footer stack.

List and scroll view props. .scrollContentBackground(.hidden): list gets "background": "hidden". .scrollDismissesKeyboard(…): list and scrollview get "dismissesKeyboard": true; scrolling blurs the input being edited inside. .scrollEdgeEffectStyle(_:for:) / .scrollEdgeEffectHidden(_:for:) (iOS 26): list and scrollview below get "edgeEffect": {"top": …, "bottom": …}, each edge "hard", "soft" or "hidden" (absent when both are automatic); the closest modifier wins per edge and hidden wins over a style. The page draws the effect where the view runs under a bar (see navscreen and tabview in the layout table): soft blurs the content and fades it into the background, hard is an opaque backing exactly behind the bar with a dividing line, hidden is none.

Custom detents. .presentationDetents([.height(300), .fraction(0.4)]) send "height:300.0" and "fraction:0.4", smallest first; a sheet whose first detent is one of these is that tall (at most the large height) and floats like a medium one (inset 8 from the sides and 15 from the bottom, 38 pt corners; Liquid Glass: --sb-sheet-glass over a 40px backdrop blur, with the glass rim). .popover presents as a sheet, as on an iPhone.

Liquid Glass (approximated). .glassEffect(glass, in: shape) is the shape filled with the glass material (.clear: glassClear) behind the view, under the glass's tint; .identity draws nothing. The renderer paints glass as the bar buttons' fill (--sb-glass-background, glassClear at half of it) over a blurred backdrop and marks the element data-sb-glass, which gives it the glass shadow and the 1pt glass rim (styles.css). Interactive glass, GlassEffectContainer merging and glassEffectID morphs are not drawn. .buttonStyle(.glass) is a glass button: a Liquid Glass capsule sized like bordered, in the tint; .glassProminent draws as borderedProminent.

Smaller additions. Color(.sRGB | .sRGBLinear | .displayP3, …) (P3 taken as sRGB); Color.Resolved and resolve(in:); @GestureState and Gesture.updating; Text(date, style:) (formatted when the body runs); .safeAreaInset / .safeAreaBar as a stack (approximation); .border; .edgesIgnoringSafeArea; bindings to collections; onTapGesture with a location (always .zero); Bundle.preferredLocalizations, localizations, developmentLocalization; NSEC_PER_SEC and friends. Accepted without effect: contentShape (since a style hint, "Gesture spaces and composition"), onHover, help, keyboardShortcut, hoverEffect, buttonBorderShape, truncationMode, lineSpacing, scrollIndicators, controlGroupStyle, searchScopes, the presentation… modifiers, interactiveDismissDisabled, navigationTransition, matchedTransitionSource, accessibilityRepresentation / accessibilityAction.

Tabs (iOS 18)#

SwiftUI's iOS 18 tab API (TabView(selection:) { Tab(…) }, TabSection, TabRole, .sidebarAdaptable) builds on the Phase 4 tabview / tab elements. Each Tab is one tab and its value is its tag, so selection works exactly as .tabItem + .tag + selection. .tabItem tabs emit exactly the Phase 4 props.

tab prop (added) meaning
badge?: string Tab(…).badge(_:): a non-zero count or non-empty text
role?: "search" Tab(…, role: .search)

The bar item draws a badge as a red capsule, 18px high, over the icon's trailing half; a search item carries data-sb-role="search".

  • Tab order: declaration order; TabSections, ForEach, if/else and custom TabContent bodies flatten into their tabs; .search tabs move to the trailing end (a search tab without a title / symbol is "Search" / magnifyingglass). .hidden() drops a tab.
  • Compact width (and .automatic / .tabBarOnly / .page): a tabview with every tab in the bar; .tabPlacement is ignored there.
  • Regular width with .sidebarAdaptable (unless the default placement is .tabBar): a Phase 7 navsplit whose sidebar is a List(selection:) of the tabs, one section per TabSection, each row a Label with the tab's badge; the detail is the selected tab's content. Approximations: iPadOS 18 starts with a floating top tab bar; here regular width always shows the sidebar, and only the selected tab is mounted (switching resets an unselected tab's state).
  • Recorded only: .tabPlacement, .customizationID, .defaultVisibility, .customizationBehavior, .sectionActions, .tabViewCustomization (TabViewCustomization is never applied), the sidebar header / footer / bottom bar. .tabViewStyle(.page) still shows a tab bar. EnvironmentValues.symbolVariants is stored; symbols draw as named.
  • LocalizedStringResource lives in FoundationBridge, so the Tab / TabSection resource initializers take any CustomStringConvertible (disfavored) and use its description.

Preferences#

PreferenceKey values pass up the tree, the way environment values pass down (Sources/SwiftUI/API/Preferences.swift). .preference(key:value:) sets a key's value for its view, replacing what its content set, and .transformPreference changes it. After a node's children reconcile, the runtime merges their values in order with each key's reduce, then applies the node's own modifier, and keeps the result on the node. A subtree a pass skips keeps the values it produced last time, so preferences cost nothing where nothing changed.

  • .onPreferenceChange(key) { value in } (the value Equatable) runs its action after a pass in which the combined value differs from the last one it saw. It also runs after the first pass, with the initial value. Like onAppear, it runs once the ops are applied, so state it sets renders in the next pass.

  • .overlayPreferenceValue and .backgroundPreferenceValue reconcile their content first, then make the decoration from its combined value, as a decorated element (role overlay or background).

  • .anchorPreference(key:value:transform:) and .transformAnchorPreference wrap their view in a zstack whose props set reportsSize: true. The renderer reports that element's laid-out size with geometry events, as it does a GeometryReader's. An Anchor resolves against the reported size in the view's own coordinates: .bounds is CGRect(origin: .zero, size: reported) and .center its middle. A GeometryProxy subscript returns the anchor's value, without converting it to the reader's coordinates, since the Swift side has no layout. Before the first report the size is zero; when the report arrives, the wrapper re-runs and the preference updates. This is how WrappingHStack learns its height:

    GeometryReader { geo in
        content.anchorPreference(key: HeightKey.self, value: .bounds) { geo[$0].size.height }
    }
    .frame(height: height)
    .onPreferenceChange(HeightKey.self) { height = $0 }
    
  • .onGeometryChange(for:of:action:) (iOS 18) wraps its view in the same zstack with reportsSize: true, makes its value from the reported size (transform gets a GeometryProxy of it) and, like onPreferenceChange, runs the action after a pass in which the value differs from the last one it saw: the one-value form also with its first value, the (oldValue, newValue) form only on a change. For a host that lays out the first value is made of the first size it reports, and nothing runs before that ("laidout", above); the two-value form hears that value as a change from what no size makes. A headless run's first value is made of a zero size.

Code scanning#

CodeScanner (Paul Hudson's package, a SwiftUI wrapper of an AVFoundation capture session) builds from its own sources: its CodeScannerView is a UIViewControllerRepresentable whose ScannerViewController sets up an AVCaptureSession with the camera, an AVCaptureMetadataOutput and an AVCapturePhotoOutput, and shows an AVCaptureVideoPreviewLayer. Its sources are behind #if os(iOS), which holds in the staging, and its device branch is the one that runs (targetEnvironment(simulator) is false on WASI). (It used to be a stand-in module with the package's API, which showed the simulator's screen.)

Capture sessions (Sources/AVFoundation/Capture.swift). The page owns the camera:

  • AVCaptureDevice is the page's back or front camera: default(for: .video) and the wide-angle camera of a DiscoverySession (no ultra-wide, so CodeScanner's bestForVideo is the default camera). Authorization is .authorized (the browser asks when the camera opens). Torch, focus, exposure and zoom settings are kept; the torch is asked of the page; minimumFocusDistance is -1 (unknown), so CodeScanner applies no zoom.
  • startRunning() asks the page to scan when the session has a camera input and a metadata output with a delegate and code types: a scanner host request, { "action": "scan", "formats", "torch", "vibrate": false, "facing": "environment" | "user" }, with the BarcodeDetector formats of the output's metadataObjectTypes (qr_code, ean_13, …). The code it answers with reaches the delegate on its queue as one AVMetadataMachineReadableCodeObject (stringValue, the type among the requested ones for the format, corners), as a frame with a code does on iOS. One scan per request: afterwards, or when the viewer closed the camera, the session keeps running and its preview layer offers to scan again; a failure (permission: … for a refused camera) is shown with Try Again.
  • capturePhoto(with:delegate:) delivers, on the main queue, the camera frame the code was read in (a JPEG the page sent with it), or a one-pixel PNG when there was none (a typed code, a headless run). CodeScanner waits for that photo before reporting a code (requiresPhotoOutput), so ScanResult.image is the frame.
  • AVCaptureVideoPreviewLayer draws black, as a preview starts, with "Scan a Code" / "Scan Again" (or the failure and "Try Again") in the middle; the page's camera is over the page while it scans.
  • The delegate protocols are main-actor isolated (the page has one thread), so a view controller conforms in Swift 6 as it does to Objective-C's.

The page (Web/src/scanner.ts) answers scan:

  • with BarcodeDetector (Chrome on Android and macOS today) and a camera, it opens the camera (getUserMedia with the request's facingMode) full screen over the page with a viewfinder and Cancel, runs the detector every 120 ms, and answers with the first code, { "string", "format", "corners": [{ "x", "y" }], "image" } (image: the frame, a base64 JPEG);
  • without one (Safari, Firefox, Chrome on Linux and Windows), or when no camera starts, it asks the viewer to type or paste what the code holds (a multi-line field: QR codes often hold lines), and answers with that string, the first requested format and no corners;
  • { "cancelled": true } when the viewer cancels; a refused camera fails with permission: ….

probe ({ "action": "probe", "formats" } → { "camera": bool }) is still answered. Headless runs answer scan from the next SB_RESPONSES entry with a scan ({ "scan": { "string": "…", "format": "qr_code" } }), and { "cancelled": true } when none is left.

UIKit for camera screens (Sources/UIKit/Controls.swift). UIButton (titles, colors, images and background images per state) is drawn as a Button whose tap sends .touchUpInside; layout guides (safeAreaLayoutGuide, layoutMarginsGuide) are the view's own edges; touchesBegan(_:with:) and the other touch methods exist to be overridden and are not called (taps reach buttons and SwiftUI views); supportedInterfaceOrientations, UIWindowScene.interfaceOrientation (portrait), UIAdaptivePresentationControllerDelegate and UIImage(named:in:with:) (the app's catalog, which holds its packages' catalogs too; loose image files are looked for in the bundle given). Core Image's CIDetector finds no features (its call is synchronous; the page's detector is not), so CodeScanner's gallery path reports .badOutput.

CodeScanner applies its scan modes to the codes the session reports. Each scan after the first is a tap of "Scan Again", so the continuous modes deliver a code per tap, and .manual, which takes a code only within half a second of a tap on its capture button, rarely gets one.

Examples/HotProspects (Hacking with SwiftUI project 16 without its Me tab, whose QR code Examples/Filters draws) depends on CodeScanner 2.5.2 through its swiftbrowser.json (packages). Its snapshot scans a code from responses.json and schedules a reminder that is shown at 5000 ms; its Playwright test types a code (Cancel, then Scan a Code, then Done) where the browser cannot scan, checks the notification on a real timer, and scans with a stubbed camera and detector.

@AppStorage#

AppStorage is declared in FoundationBridge (Sources/FoundationBridge/ AppStorage.swift), next to the UserDefaults it reads, rather than in the SwiftUI shim, which cannot see that class; apps reach it through the FoundationBridge import the CLI adds. On iOS it is SwiftUI's, so the example apps type-check against Apple's SDK unchanged. Nothing new crosses the boundary: a write is UserDefaults.set, which sends the defaults op (Phase 11), and a launch reads SB_DEFAULTS as before.

The wrapper holds the key, the default, the store (.standard unless store: names one) and a read and a write closure chosen by the initializer: Bool, Int, Double, String, URL, Data and Date go through UserDefaults' typed getters (so a Double saved as a whole number, which comes back from JSON as an Int, still reads as a Double); RawRepresentable values store their rawValue; the optional forms (init(_:store:)) read nil for a missing key and remove the key when set to nil. A missing key reads the default, which is never saved.

Observation. Each key has a _DefaultsKey, an Observable object with a registrar. wrappedValue's getter calls its access, which registers with the withObservationTracking the runtime runs each body under (Phase 9); UserDefaults.set (and so removeObject) calls withMutation on the key's object, register(defaults:) on each key it registers, and removePersistentDomain on every key read so far. A write therefore invalidates exactly the nodes whose bodies read that key, however it was made. Direct UserDefaults reads register nothing, as on iOS.

Stale caches below a clean ancestor. An action that sets state while a body is evaluated (onChange(of:)'s) marks its node dirty in the middle of a pass: markDirty clears the cached elements of the node and its ancestors, but the same pass then produces and caches their elements again. In the next pass the ancestors are clean with a dirty descendant, and the reconciler used to clear the cache only of nodes whose body re-ran, so the page got the descendant's new elements only when every ancestor's body re-ran too. Hot Prospects' MeView, in a TabView tab, regenerated its QR code and the page kept the old one. The reconciler now clears the cache of every node it enters: it enters a clean node only for a dirty descendant, whose elements are part of its own.

Rich text#

A Text holds segments: strings and interpolated images, each with its own style. Text + Text joins the segments; Text("Hi \(name)") with an interpolated Text keeps that text's segments and style, and an interpolated Image is a segment of its own. The modifiers that return Text (font, fontWeight, bold, italic, monospaced, fontDesign, foregroundColor / foregroundStyle, strikethrough, underline, kerning / tracking, baselineOffset) style every segment that does not set the same thing already, so the innermost style wins, as in SwiftUI.

Two forms on the wire. A text of one string whose only modifiers are the ones that have View forms too (font, weight, foreground color) is the plain text it always was, inside the styled boxes those modifiers make: the ops of every existing app are unchanged. Anything else is a text with runs beside text (the plain content):

{ "text": "Read the docs", "runs": [
    { "text": "Read the " },
    { "text": "docs", "font": { "weight": "bold" }, "italic": true,
      "link": "https://swift.org" },
    { "image": { "systemName": "star.fill" } } ] }

A run has text or image (an image element's props), and optionally font (a Font object applied over the text's font, as styled font), italic, foreground (a ShapeStyle), strikethrough / underline ({} for the run's own color, or { "color": … }), kerning (px after each character), baselineOffset (px up), background (a Color behind the run's glyphs, an AttributedString's backgroundColor) and link (a URL). Before the element, the runtime sends the sources of inline bitmaps, as for an image.

Layout. The engine wraps the runs as one paragraph flow (wrapRuns, Web/src/layout/text.ts): each run measured in its own font (plus kerning), lines broken at spaces (a word may span runs) and around images, a word wider than the line broken by characters, and lineLimit truncating the last kept line with an ellipsis in its last run's font. A line is as tall as its tallest font's line height or image. An inline symbol is a square of its run's line height; a bitmap or URL image keeps its own size. TextLayout.rich carries the lines as fragments of runs, each line's height and each run's font; lines holds the same lines as plain strings (an image as U+FFFC).

Rendering. The renderer makes a template per run when the props arrive: a span.sb-text-run with the run's color, decoration, letter spacing, baseline offset (relative top) and link (.sb-link, tinted unless the run has a foreground), or the image element of an inline image (.sb-text-image; a symbol is centered on the line, a bitmap stands on the baseline). The layout pass draws a block (.sb-text-line) per engine line, at the engine's height, holding a clone of the run's span with the run's font per text fragment and the image elements themselves (Web/src/ richText.ts).

Links. A tap on a link run sends { "type": "link", "id": <text>, "value": <url> }. The text calls the environment's openURL (FoundationBridge: OpenURLAction, EnvironmentValues.openURL) with the URL; an action that answers .systemAction, or no action at all, opens it on the page: a request of kind openURL with { "url": … }, which the page answers by opening a web, mail, tel: or sms: URL in a new tab (null value) and refuses for any other scheme. Headless runs answer it with null. Link is a button that calls openURL; UIApplication.open opens the same schemes through the same request (canOpenURL is true for them).

Text(AttributedString) (FoundationBridge) maps each run's inline presentation intent (strong emphasis to bold, emphasis to italic, code to monospaced, strikethrough), its link and its SwiftUI attributes (font, foregroundColor, backgroundColor, kern, tracking, baselineOffset, Sources/FoundationBridge/TextAttributes.swift) onto segments, so Markdown from AttributedString(markdown:) renders styled with working links. It is @_disfavoredOverload, since AttributedString is string-literal expressible and a literal is a LocalizedStringKey.

Video and audio#

AVFoundation's players play in the page's media elements. One element kind, video, carries everything a view of a player shows, and the element reports back with video events. Swift holds no decoded media.

The player is state. AVPlayer (and AVQueuePlayer, AVPlayerLooper) keeps the item, the rate, mute and volume, the last seek and the views showing it in an observed state object (Sources/AVFoundation/Player.swift). A view that shows a player (_AVPlayerVideo: AVKit's VideoPlayer, AVPlayerViewController, an AVPlayerLayer in a UIKit view) attaches on appear and detaches on disappear; its body reads that state, so a change of rate, mute, item or seek draws it again, and the position (reported several times a second) draws nothing. Of the views showing a player the newest plays it; the others are paused and muted, and the one that takes over seeks to where the player is (a full-screen cover over an inline video). A player shown nowhere that plays with its sound on (not muted, volume above 0) plays through a hidden element, as iOS plays a player's sound with no layer (audio, or a video whose view went away): the runtime keeps a background view for it (_BackgroundViews, Sources/SwiftUI/Runtime/BackgroundViews.swift), a video element at zero size after the app's own elements, transparent and not hit-testable, until a view shows the player, it pauses or it is muted. It is the oldest surface, so a view that shows the player takes over from it, and it takes over again, where the player is, when that view goes. A muted player shown nowhere plays nothing (muted autoplay videos scrolled out of a list cost nothing); it keeps its rate and position. The browser's autoplay rules apply as for a view: the first unmuted play needs a tap on the page.

Sound without a tap. Safari plays sound only in an element that a tap once played, and a hidden element is made when its player starts, so a play a Timer starts (an alarm's bell, a chapter's chime) would be a fresh element it refuses. A player of sound (an item whose URL is an audio file, any AVAudioPlayer, or a player that once needed its hidden element) asks the page, once, to unlock (a media request): from then on each tap on the page readies two spare elements, unlocked by playing half a second of silence in them inside the tap, and a hidden element (background) takes a spare instead of a fresh <video>. An element that played with its sound on goes back to the spares when it is removed (four at most), so the next play reuses it. A page whose app has no player of sound never plays the silence (on an iPhone, sound from a page pauses other apps' audio). A play the browser refuses all the same (no tap since the page loaded) is reported as pause with reason: "blocked": the player's rate goes back to 0 and it posts AVPlayer.rateDidChangeNotification with AVPlayer.rateDidChangeReasonKey .setRateFailed (every other rate change carries .setRateCalled), and an AVAudioPlayer stops and tells its delegate audioPlayerDidFinishPlaying(_:successfully: false).

video element#

prop meaning
url the media (remote, data or blob URL); null while there is none
playing the player plays here (rate above 0, this is its newest view, the item has not failed)
muted, volume mute (always for a view that does not play the player) and 0…1
rate the playback rate (the default rate while paused)
loop an AVPlayerLooper loops the item
gravity resizeAspect / resizeAspectFill / resize: object-fit contain / cover / fill
controls the browser's native controls (VideoPlayer, AVPlayerViewController; not a bare AVPlayerLayer)
seek {time, serial}: the page seeks once per serial (the first props carry the player's position)
report seconds: report the position this often while playing (a periodic observer shorter than timeupdate's pace; 1 / 60 is once per animation frame on the page and a periodic time observer of a frame natively, the floor there). useAVPlayer(url, { report }) sets it; Voice Memos' scrubber moves with the sound by it. The page's frame reports are the media clock smoothed (smoothTime): between the clock's updates the position advances with the page's clock at the rate and is pulled toward the media clock over 0.3 s, so a hold of the clock while the sound plays on (Safari's, a tenth of a second or more at the start of playback) does not hold the position; a jump over 0.5 s (a seek) is taken at once, and a seek, pause, new source or the end starts afresh
width, height the video's pixel size once known (the aspect ratio for an open axis)
stream a live camera picture instead of url (CameraPreview): the id of a stream the page's video recorder opened (liveStreams, videoRecorder.ts), shown muted as it comes; no seeks or reports. The native app draws it with an AVCaptureVideoPreviewLayer over the session its recorder (videoRecord, VideoRecorderBridge.swift) opened under that id, filling the frame
mirrored flipped left to right (a front camera's preview)
background the hidden element of a player no view shows: its <video> is an unlocked spare when the page has one, and goes back to the spares when removed ("Sound without a tap")
texture a 3D material draws this element's pictures (RealityKit's VideoMaterial, docs/realitykit.md "Video"): the player's number, which the <video> carries as data-sb-video-texture; the element is at zero size, transparent, and its video is fetched with CORS (crossOrigin="anonymous"), which WebGL needs for a remote one

Layout. No children. Like a resizable image: a finite proposal is taken as is (a player view is greedy, as in SwiftUI); an open axis follows the video's aspect ratio (16:9 before the metadata); with both open it is the video's size, or 320 × 180. VideoPlayer is a zstack of the element and its videoOverlay; with no player it is a black color.

Rendering (Web/src/video.ts). A <video playsinline> filling the box on black. Mute and volume are applied before any play(), so a muted video starts on its own; browsers refuse unmuted playback until the viewer has interacted with the page, and a refused play() is reported as pause with reason: "blocked" (the player's rate goes back to 0; the native controls or the app's button start it). An ended video plays again only after a new seek. A removed element's video is paused and its source dropped; so are all of them when the renderer resets.

video events#

{"type": "video", "id": N, "event": …}, routed to the element's handler:

event fields the player
ready url, duration (null for a stream), width, height (upright: a phone's portrait video is taller than wide), time item readyToPlay, duration, the video track's naturalSize turned by its preferredTransform; the asset learns its metadata
time time the position (extrapolated at the rate between reports while playing); periodic observers fire when an interval has passed
status status: playing / waiting / paused, time timeControlStatus (observers fire when playback starts or stops)
seeked serial, time the seek's completion runs with true (a seek replaced by a later one finishes false)
play time the viewer started it: rate = defaultRate
pause time, reason? the viewer paused it, or the browser refused to start (blocked): rate 0; rateDidChangeNotification with the reason .setRateFailed for blocked
volume muted, volume the viewer changed them
rate rate the viewer picked a speed
ended url, time posts .AVPlayerItemDidPlayToEndTime (object: the item), then actionAtItemEnd: .pause rate 0, .advance next item (none for a plain player), .none nothing
error url, code (MediaError), message item failed with an AVError (network → contentIsUnavailable, decode → decodeFailed, format → fileFormatNotRecognized); posts .AVPlayerItemFailedToPlayToEndTime

Events about another URL than the current item's are dropped; a view that does not play the player only reports ready and error. A looping element ends no pass: a time that jumps back past half the duration counts a loop (AVPlayerLooper.loopCount) and posts didPlayToEndTime.

media requests#

action params answer
file name, type, data (base64); or path, type {url}: an object URL of the bytes (an asset at a file: URL; once per URL). With path, a resource of the app's bundle (Bundle.main, the files served under /bundle/<App>/): the URL the page serves it from, so the browser streams it and nothing is copied; unsupported when the page did not load that resource, and the app sends the bytes instead
probe url {duration, width, height} from a detached <video>'s metadata (asset.load(.duration), .tracks, a track's .naturalSize); fails network: …
release url {}: revokes an object URL
open url, or name / type / data {opened}: the URL, or the file as a blob, in a new tab; a file whose tab the browser blocks (no tap just before) is downloaded instead (opened: false)
unlock {}: from now on each tap readies unlocked spare elements for hidden ones ("Sound without a tap"); sent once per page, by the first player of sound

Headless: file answers blob:headless/<id>, open {opened: false}, unlock {}, and probe the duration / width / height of the SB_RESPONSES entry whose url or prefix matches and that has a duration (else it fails).

A file URL is resolved once per URL for the session: a file the app rewrites at the same path plays its old bytes in a player made later. A bundle resource (Bundle.main.url(forResource:withExtension:)) is never read in Swift: the page already serves it, so an album of audio files costs the app no memory and no base64.

What AVFoundation has#

AVPlayer (init(url:), init(playerItem:), play, pause, rate, defaultRate, playImmediately(atRate:), isMuted, volume, currentItem, replaceCurrentItem, seek(to:) with and without tolerances, completion handlers and async, currentTime(), status, error, timeControlStatus, reasonForWaitingToPlay, actionAtItemEnd, rateDidChangeNotification with its RateDidChangeReason, addPeriodicTimeObserver / removeTimeObserver, and kept settings: audiovisualBackgroundPlaybackPolicy, preventsDisplaySleepDuringVideoPlayback, external playback); AVQueuePlayer (items(), advanceToNextItem, insert(_:after:), remove, removeAllItems); AVPlayerLooper (loopCount, status, disableLooping; timeRange kept, the whole item loops); AVPlayerItem (status, error, duration, presentationSize, currentTime(), seek, the notifications); AVAsset / AVURLAsset (url, load(.duration / .isPlayable / .tracks / .preferredTransform …), loadTracks(withMediaType:), loadValuesAsynchronously, statusOfValue(forKey:error:)); AVAssetTrack (one video track when the page reports a size; audio tracks are not reported); Core Media's CMTime (rational, compared and hashed by value, sums in a common timescale, the special values; CMTimeMake, CMTimeMakeWithSeconds, CMTimeAdd, …, CMTimeRange) — AVFoundation re-exports them, and there is no CoreMedia module; AVLayerVideoGravity; AVPlayerLayer (player, videoGravity, isReadyForDisplay, videoRect); AVAudioSession (category, mode, options and activation are kept and succeed: the browser mixes audio its own way; recording is denied). AVAssetImageGenerator fails with operationNotSupportedForAsset (Swift holds no decoded frames); AVAssetExportSession copies a file asset unchanged, as the passthrough preset does, whatever the preset. Not covered: KVO on players (observe(\.status)), boundary time observers, reverse playback.

AVAudioPlayer (Sources/AVFoundation/AudioPlayer.swift) plays a sound file or sound data with no view, through a player of its own and so through a hidden element: init(contentsOf:) and init(contentsOf:fileTypeHint:) (a file that is not there throws; a bundle resource plays from the URL the page serves it at), init(data:) and init(data:fileTypeHint:) (the bytes go to the page once as a blob, of the type the hint names or the first bytes show: WAV, AIFF, CAF, MP3, MPEG-4 audio, Ogg, FLAC; anything else throws), prepareToPlay, play (true once asked; the browser's answer comes a moment later), play(atTime:) on deviceCurrentTime's clock, pause (play goes on from there), stop (as on iOS, currentTime stays), isPlaying, currentTime (setting it seeks), duration (from a media probe when the player is made: 0 until the page answers), volume and setVolume(_:fadeDuration:), numberOfLoops (below 0 the element loops itself; a count plays again from the start after each end), rate with enableRate (0.5…2), url, data, and its delegate: audioPlayerDidFinishPlaying(_:successfully:) (true at the end, after which the player is back at the start; false when the browser refused the play or the page could not load the sound) and audioPlayerDecodeErrorDidOccur(_:error:) (the page's error). pan, metering (averagePower and peakPower answer -160 dB), numberOfChannels (2) and settings (empty) are kept or answered without a media element to measure them.

CALayer.init() is required, so a view can make its layerClass: a CALayer subclass that declares its own designated initializers needs a required init() too.

Now playing#

import MediaPlayer links a stand-in module (Sources/MediaPlayer) over the browser's Media Session API: what the app says is playing goes on the lock screen and the system's media controls, and their buttons (and hardware media keys) come back as the app's remote commands. iOS Safari keeps a page's audio playing with the screen locked when the page has set a media session, which is also what makes this matter for an audio app.

MPNowPlayingInfoCenter.default() keeps nowPlayingInfo (the keys: MPMediaItemPropertyTitle, Artist, AlbumTitle, AlbumArtist, Artwork, PlaybackDuration, MPNowPlayingInfoPropertyElapsedPlaybackTime, PlaybackRate, and the rest, kept but not sent) and playbackState; MPMediaItemArtwork(boundsSize:requestHandler:) is asked for its image once, encoded as PNG. MPRemoteCommandCenter.shared() has the commands (playCommand, pauseCommand, stopCommand, togglePlayPauseCommand, nextTrackCommand, previousTrackCommand, changePlaybackPositionCommand, skipForwardCommand and skipBackwardCommand with preferredIntervals, and the others, kept and never sent), each with isEnabled, addTarget(handler:), addTarget(_:action:) and removeTarget. A change to either center sends one mediaSession request per turn, and nothing when the result is what the page already has.

Every exchange is a host request (Phase 13's channel) of kind mediaSession:

action params page value
update metadata (title, artist, album, artwork a URL; null clears), playbackState (none / playing / paused), position (duration, position, rate, seconds; null clears), commands (the names below), skip (forward, backward: the preferred intervals) navigator.mediaSession.metadata, playbackState, setPositionState (the browser extrapolates at the rate, so the app sends the position when it changes: a play, a pause, a seek), and setActionHandler for exactly the commands named (none for the rest; an action the browser lacks is skipped). A field left out stays as it was {}
receive the next command the viewer gave: waits for one; commands that arrive with nobody receiving wait in a queue, in order { "command", "position"?, "interval"? }

The commands and their Media Session actions: play, pause, stop, nextTrack (nexttrack), previousTrack (previoustrack), seekTo (seekto, answered with position in seconds), skipForward and skipBackward (seekforward / seekbackward, answered with interval: the offset the system asked for, else the app's preferred one). The page listens for a command the app handles (enabled, with a target). togglePlayPause has no action of its own: it makes the page listen for play and pause, and each goes to the toggle when the app handles no play or pause itself. While some command is handled the app keeps one receive open; the handlers run on its answer and the next receive goes out. A page without the Media Session API answers update with {} and fails receive (unsupported), which ends the listening. Headless runs answer update at once and refuse receive, so nothing waits on the virtual clock.

Not covered: the music library (MPMediaQuery, MPMediaItem), MPMusicPlayerController, MPVolumeView, seeking by press-and-hold (seekForwardCommand / seekBackwardCommand), the feedback, rating and language commands (kept, never sent), and MPNowPlayingSession.

Sharing and media#

Transferable. CoreTransferable (Sources/CoreTransferable) is a module under SwiftUI, which re-exports it with UniformTypeIdentifiers, so struct Photo: Transferable compiles with import SwiftUI alone. Representations are walked as a list, in order: the builder flattens blocks, if and if #available. A value exports through the first representation that exports the wanted type (or anything) and whose exportingCondition holds. A type imports through the first representation whose imported type the content conforms to (a .png file to .image). A proxy exports or imports its proxy value's representations. FileRepresentation's importer receives a copy in /tmp (isOriginalFile false) that is removed once the closure returns, as on iOS; bytes are written to such a file first. The app's closures are not @Sendable, so a closure written in a main-actor type may call that type's initializers. Visibility is kept and ignored.

share request (extended). A ShareLink item other than a String, a URL or an Image is exported when tapped: a String or URL proxy joins text/url, and bytes or a file join files:

{ "op": "request", "kind": "share", "params": { "title": "Photo",
  "files": [{ "name": "Photo.jpeg", "type": "image/jpeg", "data": "/9j/…" }] } }

The page passes them to navigator.share as Files when canShare({files}) allows it, and downloads them otherwise. An export that awaits (Ice Cubes' image fetches its bytes) sends the request after that await. Chromium's activation lasts about five seconds; past it the share becomes a download. Image is Transferable: the original file of a UIImage(data:) image, or any image file imported. .draggable, .dropDestination and FoundationBridge's onDrop, onDrag, DropDelegate and DropInfo drag and drop for real ("Drag and drop", below). .copyable, .cuttable and .pasteDestination are accepted; the browser's own copy, cut and paste act on the page's text. PasteButton is not there.

NSItemProvider (FoundationBridge/ItemProvider.swift; corelibs has none) keeps its registrations in memory: data, files, objects (String, URL, UIImage are NSItemProviderReading/Writing), items and Transferable values (register). Loads run as tasks; loadFileRepresentation hands the handler a temporary copy removed afterwards; loadItem answers the object, a file URL, a string for text, a URL for a link, a UIImage for image data, else the data; loadTransferable(type:) imports through the type's representations. PhotosPickerItem.loadTransferable does too, for types other than Data and Image.

download request. Saving: PHPhotoLibrary.performChanges with a creation request, UIImageWriteToSavedPhotosAlbum, UISaveVideoAtPathToSavedPhotosAlbum.

{ "op": "request", "kind": "download",
  "params": { "title": "Photo", "files": [{ "name": "Photo.png", "type": "image/png", "data": "iVBOR…" }] } }

files carries an image's own file or a video file; bitmaps (recipes the page draws into <title>.png) and images (catalog names) as in share. The page downloads each; the value is { "outcome": "downloaded" }; nothing to save, or no way to download, fails with unsupported: …, which fails the change block. The completion selector of UIImageWriteToSavedPhotosAlbum is not called. Headless answers { "outcome": "headless" }.

The photo library. .addOnly authorization is .authorized (saving works, as a download); .readWrite is .limited (iOS's answer when the viewer shared some photos, here none). PHAsset/PHAssetCollection fetches return an empty PHFetchResult; PHImageManager answers nil with PHImageErrorKey; change observers are never called. NSSortDescriptor(key:ascending:) (corelibs has no key-value coding) exists where Photos is imported, for PHFetchOptions.sortDescriptors, and sorts nothing.

clipboard request. UIPasteboard keeps items in memory (a page cannot read the clipboard synchronously): what the app copied, it reads back; a URL reads as text and text that is a link as a URL. Each write to the general pasteboard is also sent to the page:

action Params Answer
write text, or a picture's files / bitmaps / images {}; the page calls navigator.clipboard.writeText, or write([ClipboardItem({"image/png": …})]) with the first picture converted to PNG, started before any await so the tap's activation still counts
readText none { text } (navigator.clipboard.readText; the browser may ask the viewer or refuse)

Named pasteboards stay in the app. Headless answers {}.

Paste delegates. UITextView.pasteDelegate, UITextPasteDelegate, UITextPasteItem, UITextPasteConfigurationSupporting and UIPasteConfiguration compile and can be called. The viewer's paste into an editable text view is the browser's own (text only), reaching the app as an edit; pasted images are not handed to the app yet, so the delegate is not consulted.

The share sheet. Presenting a UIActivityViewController (by present, or a representable in a sheet) sends a share request built like ShareLink's: strings as text, the first URL as the link, images as files/bitmaps/images; an item source gives its item for no activity, and its activityViewControllerLinkMetadata title (or subject) is the title. When the page answers, the controller dismisses itself and calls completionWithItemsHandler(nil, completed, items, nil). Custom UIActivitys are kept and never shown.

Link metadata. LPMetadataProvider fetches the page with URLSession and reads og:title (or <title>), og:image and the icon (as item providers that download the picture) and og:video. A site that does not allow the page's origin (CORS) fails the fetch: LPError.metadataFetchFailed; non-web URLs are metadataFetchNotAllowed.

Translation and the on-device language model#

Apple Intelligence's two frameworks have stand-ins (Sources/Translation, Sources/FoundationModels).

Translation translates with the browser's own translator where the page has one: Chrome (138 and later, on desktop) has a built-in Translator API, which translates on the device with a model it downloads per language pair, and a LanguageDetector. Every exchange is a host request of kind translate (Web/src/translation.ts):

action params page value
availability source (null: detected from text), target, text? Translator.availability({sourceLanguage, targetLanguage}) { "status": "installed" | "supported" | "unsupported" } (available / downloadable or downloading / unavailable)
translate source (null: detected), target, texts, allowDownload Translator.create(…) once per pair, then translate(text) for each { "source": "en", "texts": [...] }

Languages travel as BCP 47 tags: a Locale.Language's language code, and zh-Hant for traditional Chinese (a Hant script or a TW, HK or MO region). A failed translate rejects with a tagged message: unsupported: … (no translator, or the pair is unavailable) is TranslationError.unsupportedLanguagePairing, unidentified: … (no source given and none detected) .unableToIdentifyLanguage, download: … (the pair's model is not downloaded and the session may not ask for it) .notInstalled, anything else .internalError. A page without a translator, and headless runs, answer { "status": "unsupported" }, so availability is .unsupported and translations fail with .unsupportedLanguagePairing, as on a device without the pair.

  • TranslationSession: translate(_:), translations(from:) (in the requests' order, with their clientIdentifiers), translate(batch:) (an async sequence), prepareTranslation(), cancel(), isReady, sourceLanguage, targetLanguage, canRequestDownloads, and iOS 26's init(installedSource:target:), which never downloads. A nil target is the viewer's first preferred language.
  • TranslationSession.Configuration (source, target, version; invalidate() runs the task again), Request, Response, TranslationError (with ~=), LanguageAvailability (status(from:to:), status(for:to:), supportedLanguages: Apple's list).
  • .translationTask(_:action:) runs the action with a session when the view appears with a configuration and each time the configuration changes (a .task(id:)); a nil configuration runs nothing. .translationTask(source:target:action:) runs it on appear. Their sessions may download (Chrome lets a page start a download within a tap).
  • .translationPresentation(isPresented:text:…) is a sheet, as on an iPhone: the original text, its translation into the viewer's language (or "Translation is not available in this browser for this text."), Done and, with replacementAction, "Replace with Translation". The popover anchor and arrow edge are ignored.

Ice Cubes guards Apple's translation with #if canImport(_Translation_SwiftUI), the overlay module Apple's SDK has when SwiftUI and Translation are both imported. No module of that name exists here, so Ice Cubes translates with its instance's translation endpoint, then DeepL (its own fallbacks), and hides the Apple option. WishKit's WishTranslateSection (behind canImport(Translation)) uses .translationTask.

Foundation Models has no model to run: Chrome's Prompt API (LanguageModel) is offered to extensions and origin trials, not to pages. SystemLanguageModel.default.availability is .unavailable(.deviceNotEligible) (isAvailable false, no supported languages), what an iPhone without Apple Intelligence reports, and every LanguageModelSession.respond / streamResponse fails with GenerationError.assetsUnavailable (a stream fails on its first iteration). Apps check availability first: Ice Cubes' composer hides its assistant. The API is there for them to compile and run unchanged: sessions with instructions (InstructionsBuilder, strings, arrays), prompts (PromptBuilder), GenerationOptions with sampling modes, prewarm, transcripts, tools, GenerationError and its context, Response and ResponseStream (collect()), and structured output:

  • Generable (ConvertibleFromGeneratedContent & ConvertibleToGeneratedContent, with generationSchema; PartiallyGenerated is the type itself), with conformances for String, Bool, Int, Double, Float, Decimal, arrays, optionals and GeneratedContent.
  • GeneratedContent: null, bool, number, string, array or a structure with ordered keys; init(json:) (a small parser that keeps key order), jsonString, value(_:), value(_:forProperty:).
  • GenerationSchema and GenerationGuide (.count, .minimumCount, .maximumCount, .range, .minimum, .maximum, .anyOf, .constant, .element); a schema's debugDescription is its JSON Schema.
  • @Generable and @Guide are macros of the shim's SwiftDataMacros plugin (Sources/SwiftDataMacros/GenerableMacro.swift). On a struct @Generable adds an extension with the schema (each stored property with its @Guide description and guides; a let with a value is left out), an init(_: GeneratedContent) that reads each property by name and generatedContent; on an enum of plain cases, the case names as choices. Its members are nonisolated, so a type of a main-actor module conforms without isolation. @Guide adds nothing itself. Its guides are GenerationGuide<Any> (a macro argument cannot infer the property's type).

UIKit appearance proxies and the app delegate#

UINavigationBar.appearance().barTintColor = … styles every navigation bar on iOS. The page draws its own bars from SwiftUI's elements, so a proxy only records (Sources/UIKit/Appearance.swift): appearance(), appearance(whenContainedInInstancesOf:), appearance(for:) and the combination return an instance of the class kept per class and scope (made once with init?(coder:) and an empty archive, the initializer every view has), whose properties read back what the app set. Nothing is copied to other instances. UIAppearance and UIAppearanceContainer are declared; views and view controllers are containers.

@UIApplicationDelegateAdaptor (Sources/UIKit/AppDelegate.swift) makes the delegate once, when the app is created, sets it as UIApplication.shared.delegate, and calls application(_:willFinishLaunchingWithOptions:) then application(_:didFinishLaunchingWithOptions:) with no options, as UIKit does before the first scene. Then the page's one scene connects: the delegate's application(_:configurationForConnecting:options:) names the scene delegate class (configuration.delegateClass = SceneDelegate.self), which is made and sent scene(_:willConnectTo:options:), sceneWillEnterForeground and sceneDidBecomeActive; UIScene.delegate is it. A scene delegate that is Observable or an ObservableObject goes in every view's environment, as SwiftUI does (Ice Cubes reads it with @Environment(SceneDelegate.self)). UIKit makes the delegate through the Objective-C runtime; without it Swift can make an instance from a metatype only through a required initializer, so the staging rewrites the assignment into configuration._setDelegateClass(SceneDelegate.self) { SceneDelegate() } (same line). The later scene lifecycle (background, disconnect) is not reported. UIApplicationDelegate's other methods have defaults and are not called (no device token, remote notifications or background fetches). UIResponder is what a delegate inherits; views do not form a responder chain. UIMenuBuilder, UIMenu, UICommand, UIBackgroundFetchResult and UIApplication.LaunchOptionsKey are declared; buildMenu(with:) is never called. Alternate icons are not supported: supportsAlternateIcons is false, alternateIconName nil, and setAlternateIconName fails. A view's safeAreaInsets are zero. UIKit re-exports UserNotifications, as iOS's does.

The app's own state#

The runtime used to evaluate an App's body once. Now an app with @State or @Environment properties is watched: its state boxes re-evaluate body when they change, and an environment event (scenePhase, color scheme, Dynamic Type, size class) resolves its environment properties and evaluates body again; the new root view replaces the old and renders. TabView(selection: $selectedTab) with the app's @State and .onChange(of: scenePhase) on a scene work. @StateObjects are left to the views they are handed to, and an app with neither kind of property is evaluated once, as before.

More of SwiftUI, from the Ice Cubes sweep#

Scenes. A body may list several scenes (SceneBuilder with several parts, if/else, #available): the page shows the first window group that is not for a value. WindowGroup(id:), WindowGroup(for:) (declared, never opened: openWindow does nothing), .onChange(of:) on a scene (a root view modifier), and accepted .commands { } (Commands, CommandsBuilder, CommandGroup, CommandMenu, CommandGroupPlacement and the standard command sets: there is no menu bar), .defaultSize, .windowResizability, .handlesExternalEvents.

Effects. Animatable (VectorArithmetic, AnimatablePair, EmptyAnimatableData; CGPoint, CGSize, CGRect conform), AnimatableModifier, GeometryEffect and ProjectionTransform (.projectionEffect, .transformEffect with Core Graphics' CGAffineTransform). The page animates styles, not Swift values, so an animatable modifier or effect is evaluated at its final animatableData and the page animates between the styles of the old and new values: a shake that comes back to rest at each whole unit does not move. A geometry effect's effectValue(size:) is asked with a zero size (the Swift side does not know the laid-out size) and its affine part is drawn as an offset, a rotation and a scale about the top-leading corner, decomposed from the matrix; a shear and the perspective row are not drawn. Color effects are style keys the page draws as CSS filters on the box: .saturation (saturate()), .contrast, .grayscale, .hueRotation (hue-rotate()), .colorInvert (invert(1)) and .brightness, which SwiftUI adds to each component and CSS brightness(1 + amount) scales instead (an approximation).

styled style (added) meaning
brightness, saturation, contrast, grayscale: number the modifiers' amounts
hueRotation: number degrees
colorInvert: true
underline, strikethrough, italic: bool View .underline() / .strikethrough() / .italic(): the texts below get the decoration (inherited CSS custom properties .sb-text reads) or the slant; false turns an ancestor's off. Italic text is measured upright.
blendMode: string .blendMode: the CSS mix-blend-mode (screen, multiply, color-dodge, plus-lighter…); the Porter-Duff modes and plusDarker draw normally. .drawingGroup() changes nothing (the browser composites already).
colorMultiply: Color .colorMultiply(_:): each component and the alpha multiplied by the color's, through an SVG feColorMatrix filter the page adds to the document once per color (a semantic or catalog color resolved when applied).
zIndex: number .zIndex(_:): the box's CSS z-index (× 1000, so fractional indices stay apart). The stack it is in stacks its children on its own (isolation: isolate), so the index orders the box among its siblings only, as SwiftUI's does: a negative one stays in front of what is behind the stack, and takes its taps. The modifiers' boxes between the box and its stack pass the index through.
scrollTransition: {configuration, axis?, identity, topLeading, bottomTrailing} .scrollTransition(_:axis:transition:): the closure's effects in each phase (the visual-effect fields of a style: offset, scale, scaleAnchor, rotation, rotationAnchor, rotation3D, opacity, blur, brightness, contrast, saturation, grayscale, hueRotation), drawn by the renderer as the box moves through its scroll view, with no round trip per scroll step. The progress is how far the box is out of the scroll view's visible area as a share of its own length (laid-out positions; the transition's own offset does not count), negative past the top or leading edge; interactive draws between the identity phase and that edge's by it, animated the edge's (animated) once the box is partly out, identity the identity phase's. The page draws it after each layout and in each scroll event (src/scrollTransition.ts); SwiftUI Native hands it to SwiftUI's own .scrollTransition.

Shapes. Shape.trim(from:to:) sends "trim": {"from", "to"} in the shape element's props; the page masks the box with a conic gradient from 3 o'clock clockwise, which is exact for a circle (a progress ring) and keeps the angles, not the outline's length, for other shapes. .stroke(_:style:), .stroke(style:) and .strokeBorder(_:style:) draw the StrokeStyle's line width (a built-in shape's caps and joins are not drawn, and its dash pattern, sent as stroke.dash, draws as a CSS dashed border whose dash lengths are the browser's; a custom shape's are exact, see "Custom shapes"). A custom shape's trim is exact. UnevenRoundedRectangle (and .rect(topLeadingRadius:…)) is drawn with its largest radius at every corner. TintShapeStyle (.tint as a style) is the semantic color tint: the nearest .tint(_:), else the accent color.

Controls and containers.

  • Custom ButtonStyles: the button's label is replaced by makeBody(configuration:) inside the same button element, sent with the plain style; the style's @Environment is resolved like a view's (the runtime reflects into a stored ButtonStyle as into a ViewModifier). isPressed is always false (the page reports no press in progress). A nearer .buttonStyle, custom or built in, wins.
  • ColorPicker: its label and a swatch; a tap sends a pickColor host request ({ "color": "#rrggbb" }), which opens the browser's color chooser (<input type="color">, clicked within the tap) and answers { "color": "#rrggbb" } or {} when closed (Web/src/colorPicker.ts). Colors are opaque; headless runs answer {}.
  • LabeledContent (the label, a spacer, the content in the secondary style), GroupBox (the label in the headline font over the content, in 16 points of padding on a secondary-system-background rounded rectangle), ControlGroup (a group: one item each in a menu, flowing in the stack elsewhere; its label is not drawn), ImageRenderer (uiImage and cgImage are nil: only the page draws views).
  • VStackLayout, HStackLayout, ZStackLayout used as containers are the stacks themselves (the same elements); AnyLayout is the wrapped stack, or a layout element for a custom layout. Their Layout methods also compute the stacks in Swift. Switching an AnyLayout's kind rebuilds its content.
  • ForEach($items) { $item in … } and ForEach($items, id:); Binding(projectedValue:) (declared in Binding itself, where the compiler looks for it).
  • .navigationDestination(isPresented:) and (item:) present their destination as a sheet in a stack of its own with a Back button (an approximation: the runtime pushes only what links and paths name). Dismissing it clears the binding.
  • .presentationDetents(_:selection:) puts the selected detent first, so the page presents the sheet at it; the page reports no resizing.
  • iOS 13's TextField(_:text:onEditingChanged:onCommit:) (onCommit on Return, as .onSubmit), Picker(selection:label:content:), Menu with a localized title, .searchable(text:isPresented:…) (the field is always shown), .navigationBarDrawer(displayMode:).
  • Toolbars: ToolbarSpacer (an empty toolbar with "spacer": "flexible" | "fixed" of its placement; it splits a bottom bar's glass groups, see toolbar above), and if/else and if #available in toolbar builders (both branches build one type).
  • Toolbars: .secondaryAction items, as a toolbar with placement: "secondary". As on an iPhone they are collapsed into the More button: the engine hides them (no frames) and gives the navscreen a more chrome rect, a 44 glass circle at the trailing end of the bar, the trailing items 8 before it; a tap on it opens a menu of the collapsed items, listed as a menu's are, and choosing one sends tap with the item's id. A navscreen with toolbarRole: "editor" (.toolbarRole(.editor)) in a regular width (a root at least 700 wide) shows them inline before the trailing items instead, each toolbar's items in its own glass capsule and separate toolbars 12 apart, clear of the centered title; those that do not fit collapse into the More button, the first ones staying. The Swift shim sends secondary for .secondaryAction; its .toolbarRole sends nothing yet, so Swift apps always collapse them.
  • Accepted: .focusable, .focusEffectDisabled, .onKeyPress (never called: the page sends no key events outside text inputs), @AccessibilityFocusState (kept, moves nowhere) and .accessibilityFocused, .accessibilityActions { }, .minimumScaleFactor, .allowsTightening, .fontWidth, .groupBoxStyle, .labeledContentStyle.

Text. .fontDesign and .monospaced on any view set the fonts' design; .navigationTitle takes a LocalizedStringKey; a localized string interpolates \(date, style:) as Text(date, style:) formats it; push transitions (.push(from:)) are an asymmetric move and fade.

Environment. locale, calendar and timeZone (FoundationBridge; the current ones unless a view sets them, which views below read back), defaultMinListRowHeight, defaultMinListHeaderHeight (recorded), GeometryProxy.safeAreaInsets (zero). Environment is Sendable when its value is, so a Sendable style may hold one. .refreshable's action runs in the caller's actor context, as .task's does.

Charts. ChartProxy (no plot geometry on the Swift side: positions, values and plotFrame are nil), .chartOverlay / .chartBackground (the content over or under the chart with that proxy), accepted .chartXSelection / .chartYSelection (the page reports no chart taps), AxisValueLabel(format:) (the tick's value converted to the format's input type and formatted), and accepted scale ranges (.chartXScale(range: .plotDimension(startPadding:endPadding:))).

More of Foundation, Combine and Image I/O#

  • Key-value observation (FoundationBridge/KeyValueObserving.swift): corelibs Foundation has none, and its classes' setters (Progress's) are out of reach, so object.observe(\.keyPath, options:changeHandler:) polls: once per frame (1/60 s on the executor's clock) it reads the key path on the main actor and calls the handler when the value changed (== for Equatable values, identity for objects, else the description), a frame late at most. .initial, .new and .old are honoured; .prior sends nothing. NSKeyValueObservation ends when invalidated, released or when the object goes away. ButtonKit follows a Progress this way.
  • Asset resources: ImageResource and ColorResource (name and bundle), Image(_:), Image(decorative:), Color(_:), Label(_:image:) and UIImage(resource:) with one: the catalog entry of that name (the page's catalog is the whole app's). Xcode's generated static members (ImageResource.avatar) are generated by the CLI (see "Backyard Birds").
  • ListFormatter (English: "a, b, and c").
  • .fileImporter(isPresented:allowedContentTypes:…): the photo picker's pickFiles request with an accept made from the types (image/*, video/*, a MIME type or an extension; any file for .item/.data); the chosen files are written to a folder of their own under the temporary directory and onCompletion gets their file URLs. With .folder among the types, the chooser is the folder chooser and onCompletion gets one URL, the folder's, written out with the files in it the other types allow. A dismissed chooser calls onCancellation (if given), not onCompletion. URLs' startAccessingSecurityScopedResource() answers true.
  • Combine: the shim's ObservableObjectPublisher is a Combine Publisher of Void (objectWillChange.sink { }); FoundationBridge's DispatchQueue and RunLoop are Schedulers (actions on the main actor's next turn, later ones after a sleep on the executor's clock, repeating ones until cancelled), so .debounce(for:scheduler: DispatchQueue.main) and .receive(on: RunLoop.main) work; View.onReceive takes Combine publishers (disfavored next to the shim's own).
  • Image I/O: CGImageSourceCreateWithURL reads a file URL (the app's own files; nil for another scheme), CGImage.utType is the type of the file an image is (nil once drawn or filtered), CFURL is URL.
  • SwiftData: Query() is declared without a constraint, so @Query var items: [Item] gives a view's memberwise initializer a default for items, as Apple's does.
  • AppIntents: AppEntity is Sendable, as Apple's is, so an entity of a main-actor module conforms without isolation.

Localized strings#

Apps keep their text in string catalogs (Localizable.xcstrings) or in <language>.lproj/*.strings and .stringsdict files. Xcode compiles them into string tables in the app bundle, and the CLI does the same (packages/cli/src/strings.ts):

  • Sources. The Xcode target's catalogs and tables come from its resources and its synchronized folders. A folder of sources uses the catalogs and .lproj folders it holds. resources in swiftbrowser.json, when given, replaces both lists.
  • Output. Each source compiles to <language>.lproj/<Table>.strings (keys to format strings) and .stringsdict (keys to plural rules), written as XML property lists. The tables sit in the staging directory (Localization/) and are published with the bundle, so they are mounted at /bundle/<language>.lproj/.
  • Catalog entries. A stringUnit becomes a string. A plural variation becomes a rule, %1$#@count@, with one case per category. A string with substitutions becomes a rule whose tokens are the substitutions' plural variations, each numbered with its argNum; %arg in a case is that argument. A device variation is settled at compile time for the iPhone the page stands for. Entries with shouldTranslate: false, and keys with no localization, are left out, so the key is its own text.
  • Languages. The app's locales (default ["en"]) plus the catalog's source language are compiled. A catalog language is included when its language part matches a locale, so pt-BR is included for pt; ["*"] includes them all. The page runs the app in the viewer's language only when it is among locales, which also choose the ICU data that ships. Adding a language therefore costs both its strings and its locale data.

Keys and arguments. LocalizedStringKey, String.LocalizationValue and LocalizedStringResource build their keys the way Xcode writes them in a catalog: the literal text plus one specifier per interpolation.

Interpolated Specifier
String, a FormatStyle's output, a date with a style, any other value %@
Int, Int64 %lld
Int32, Int16, Int8 %d
UInt, UInt64 %llu
UInt32 and smaller %u
Double (and CGFloat) %lf
Float %f
Image, Text %@
any value with specifier: the given specifier

So Text("\(count) posts") looks up "%lld posts", and a literal % in a key with arguments is written %%. As in SwiftUI, a Double shown through a key is formatted as %lf does: Text("\(0.5)") shows 0.500000. Write Text(verbatim:), Text(String(value)) or a specifier to show it otherwise.

Lookup (SwiftUI's Localization/Localization.swift, shared with FoundationBridge's Bundle and String(localized:)):

  • Which language. The bundle's .lproj folders are its localizations. The running one is the viewer's language (SB_LOCALE), matched by whole tag, then by Chinese script (zh-TW matches zh-Hant), then by language (an exact en before en-GB). Without a match it is en when present.
  • Which table. A key is looked up in the running language's table (Localizable unless a table is named), then in the development language's (en when present). A key found in neither is its own text. String(localized:defaultValue:) uses the default value instead.
  • Formatting. With arguments, the format is filled as String.localizedStringWithFormat fills it (what Text and String(localized:) use on Apple platforms): %@, %d/%lld/%u, %f/%lf/%e/%g with flags, width and precision, positional %2$@, and %%. A plain %d/%lld/%u, and a %f/%lf with at most a precision, groups its integer digits with the locale's separator and uses the locale's decimal separator, so Text("\(1024) followers") shows 1,024 followers in English (and a year 2,026, as on iOS; use Text(verbatim:) or String(year) for none); a width, padding (%05d) or another conversion (%x) is formatted as given. A key with no arguments is not formatted, so Text("100%") shows 100%.
  • Plural rules. A %#@name@ token is replaced by the case that its variable's plural rule picks for the token's argument; the rules are CLDR's cardinal rules for the running language (Localization/PluralRules.swift). A zero case, when present, is used for 0 in any language, as Foundation does. A case's own unnumbered specifiers take the token's argument.
  • Views in the text. An Image or Text interpolated into a Text goes where the translation puts its %@.

As in SwiftUI, a string literal given to a title (Button, Label, TextField, Section, Toggle, Picker, Menu, NavigationLink, .navigationTitle, .badge, .searchable(prompt:)…) is a LocalizedStringKey: the StringProtocol versions are @_disfavoredOverload, so they only take strings held in variables, which are shown as they are.

Text(_:tableName:bundle:comment:) and Text(_:bundle:) look keys up in another table or bundle. Bundle.localizedString(forKey:value:table:) returns the key's format string; for a rule, it returns the other case. Bundle.localizations lists the .lproj folders.

Animated GIFs#

Gifu 4.0.1, which Ice Cubes shows animated avatars with, builds from its own sources and runs as it does on iOS: Image I/O reads the GIF's frames and delays, a CADisplayLink ticks, and on each frame change the GIFImageView (a UIImageView) sets the frame as its image, which the page draws. Nothing is special-cased for Gifu; each piece is the framework's:

  • Image I/O. A GIF source counts its frames (CGImageSourceGetCount), read by walking the file's blocks (Sources/ImageIO/GIF.swift), without decoding a pixel. Each frame's properties have {GIF}'s UnclampedDelayTime (the file's delay, in seconds) and DelayTime (under 11 ms is 100 ms, as browsers show it); the source's properties have LoopCount (0: forever; absent when the file plays once), the canvas size and HasGlobalColorMap. CGImageSourceCreateImageAtIndex(source, n, _) of an animated GIF is a CGImage whose recipe names frame n (bitmap.frame); a still GIF's, and UIImage(data:) of any GIF, is the file, its first frame.
  • The page draws a recipe's frame with its own GIF decoder (Web/src/gif.ts): LZW, interlacing, local color tables, then composition as browsers compose: the canvas starts clear, a frame's transparent index leaves what is under it, and its disposal applies before the next frame (leave, clear its rectangle, or restore what was under it). Frames are composed in order and kept, so a loop is decoded once. A file the decoder cannot read is drawn as the browser decodes it.
  • Layers display through their view. A view is its layer's delegate (CALayerDelegate). setNeedsDisplay() on the layer (or the view) calls the view's display(_:) at once, where iOS waits for the frame's commit; a request made during that display is part of it. A layer is also displayed before its view is first drawn, as iOS does, so a GIFImageView that was only told to animate shows its first frame at once. UIView.instancesRespond(to:) answers true for a selector made from a method, so GIFImageView.display(_:) calls super, which draws the view again.
  • Display links run a timer only while added to a run loop and not paused, so a GIF that never starts (Ice Cubes' avatars, unless animated avatars are on) costs nothing.

The frames change through the representable's "changes outside a pass" path: each is an update of the image element's bitmap with its new frame, and the page draws it from the frames it already composed.

packages/cli/test/fixtures/GifuApp links Gifu 4.0.1 from the app and from a local package, Gifs, whose GifView is Ice Cubes' own: a GIFImageView filling a plain view, prepared with prepareForAnimation(withGIFData:) and started or not. A second view plays a three-frame GIF twice with animate(withGIFData:loopCount:) and counts its loops. CI runs it headless for 1.5 s: the frames go 0, 1, 2 and round again, the loop count reaches 2, and the animation finishes.

MapKit#

import MapKit links a stand-in module (Sources/MapKit) with MapKit's SwiftUI API and value types, which Hacking with SwiftUI's Bucket List (14) uses. It adds no element kinds: a map is SwiftUI views.

  • The map is a GeometryReader over a beige surface with a grid of latitude and longitude lines (a custom Shape, sent as path) and a "Map preview" caption, clipped to its size. There is no map data: no tiles, no place names. It shows the region of its camera position (.region, .camera from its distance, the fallback of .userLocation; .automatic shows the whole world) and does not pan, zoom or rotate; a position binding is read, never written.
  • The projection is Web Mercator, as MapKit's: the region's span fits the view's narrower side and its center is the view's middle (_MapProjection). The map passes it to its content in the environment.
  • Map content (MapContentBuilder is ViewBuilder, MapContent refines View) places itself with that projection: Annotation centers its content on its coordinate with its title below, Marker is a red circle with its symbol or monogram (.tint colors it), MapPolyline, MapPolygon and MapCircle are shapes through their points; the iOS 14 MapMarker, MapPin and MapAnnotation in Map(coordinateRegion:annotationItems:annotationContent:) likewise. UserAnnotation draws nothing (the browser's map has no user location).
  • MapReader gives its content a MapProxy whose convert(_:from:) turns a point in the map into a coordinate (and back) with the projection of the map's last render. .onTapGesture { point in … } (the coordinateSpace: overload) asks the page for the tap's location: its tapgesture element carries "location": true and the tap event x and y in the element, in points. That is how Bucket List adds a place where it was tapped.
  • mapStyle, mapControls, mapControlVisibility, onMapCameraChange, the controls (MapCompass, MapScaleView, MapUserLocationButton, MapPitchToggle) and the interaction modes are accepted and do nothing.

Bucket List keeps its places in an @Observable view model and edits one in .sheet(item: $viewModel.selectedPlace). A sheet's or alert's binding is now read under the observation tracking of its node's children, so a binding into an @Observable model presents when the model changes (it only did for @State).

Drag and drop#

.draggable(_:) and .onDrag wrap their view in a draggable element; .dropDestination(for:) and the onDrop family wrap theirs in a dropdestination. Both are transparent for layout, like gesture: one child, the child's size, the list-row context kept. What is dragged stays in Swift; the page only connects a source to a destination.

kind props children
draggable none exactly one
dropdestination accepts: string[]: the MIME patterns of what dragged in from outside the page it takes (text/plain, text/uri-list, image/png, image/*, or a star over a star for anything) exactly one

Events#

{ "type": "dragstart", "id": 12 }                      // a `draggable` was lifted
{ "type": "drop", "id": 40, "phase": "entered" | "exited" | "performed",
  "source": 12,                                        // the lifted `draggable` (a drag that began in the app)
  "x": 24, "y": 10 }                                   // `performed`: the point in the destination's box; else 0, 0
{ "type": "drop", "id": 40, "phase": "performed",      // from outside the page: no `source`, the items instead
  "items": [{ "type": "text/plain", "text": "Hello" },
            { "type": "image/png", "name": "a.png", "data": "iVBORw0…" }],
  "x": 24, "y": 10 }
{ "type": "dragend", "id": 12 }                        // the lifted `draggable` was dropped or let go

A drag in the app#

A draggable lifts on a long press (0.5 s) on a touch screen, or once a mouse has moved it 10 px, so taps and scrolling inside keep working. Lifting sends dragstart: Swift runs the payload closure then (onDrag's provider closure runs when the drag begins, as on iOS) and keeps the result as the current drag (_DragSession). The page copies the element (the copy carries no element id) and the copy follows the pointer above everything, scaled with a shadow, while the original dims. The dropdestination under the pointer gets entered as the copy comes over it and exited as it leaves (the app's isTargeted follows; the page draws nothing of its own). Releasing over one sends performed with the source and the point in the destination's box, and then dragend; releasing elsewhere slides the copy back (0.3 s) and sends dragend alone. The preview: of .draggable / .onDrag is accepted and not drawn: the copy is the preview. While a row or view is lifted its touch moves are kept from scrolling the list.

On the Swift side the destination's handler reads the current drag's payload when source is its id (a stale source carries nothing: the action is not called). .dropDestination(for: T.self) hands the action a payload that is a T at once, within the event; a payload of another Transferable type is exported in the first type T imports (the first representation it exports that conforms wins, so put the preferred one first) and imported, as a task, and the action runs after the drop. isTargeted is told false as the drop performs, as on iOS. onDrop makes NSItemProviders: an onDrag provider as it is, a .draggable payload registered in every type it exports; the providers are filtered by the destination's content types, and a drop that carries none of them is refused without calling the action. A DropDelegate hears dropEntered / dropExited with the providers of the drag passing over, then validateDrop and performDrop.

Drops from outside the page#

The browser's own drag and drop (a file from the desktop, text or a link selected in another window) reaches a dropdestination through the page's dragover / drop events when one of its accepts patterns matches a type the drag offers (entered / exited as it passes, with no source). On drop the page reads the strings (text/plain, text/uri-list) and the accepted files (as base64 data, named, for a Swift app; a React app in the same page asks the renderer for reference drops and gets each file itself, unserialized) and sends performed with the items, after the reads. A dropped folder is walked (webkitGetAsEntry) and each file in it the patterns accept is an item of its own with its path from the folder, the folder's name first (Photos/2025/a.jpg). Natively (SwiftBrowser Native) a dropped file stays on disk and its item names it by url and size, read on demand. Swift turns each item into _TransferContent: text as public.utf8-plain-text, a link as public.url, a file in the type of its MIME type (else of its extension, else public.data) with the file's name as suggestedName. dropDestination imports every item T imports (a JSON file is text, so a String destination takes it); onDrop registers each as a data representation. accepts comes from the imported content types (or onDrop's content types): a type's own MIME type when it declares one, any text for a text type, any image for image, anything for data, item, content and files; an app's own type that no file or text carries matches nothing, so such a destination takes in-app drags only. Dropping anywhere else on the screen never navigates the page away. The page starts no browser drag of its own: a draggable cannot be dragged out to another window.

Headless: drop:"Trash":"Coffee" drags the draggable showing Coffee onto the dropdestination showing Trash (dragstart, the drop, dragend); drop:"Trash":Hello there drops that text from outside the page.

Backyard Birds#

Apple's Backyard Birds sample (its iPhone target, swiftbrowser build … --target "Backyard Birds") builds from its Xcode project unchanged: three local packages of dynamic libraries, PDF artwork composed into scenes, SwiftData with a model actor, StoreKit's subscription views and the iOS 17 API around them.

Packages. The browser build is one module, so a copied package's type: .dynamic library products are built as automatic ones (vendor.ts, manifestPatch). Its targets' asset catalogs join the app's on the page.

Asset symbols. As Xcode does (assetSymbols.ts), each module gets a static member of ImageResource per image or symbol set and of ColorResource per color set (Image(.floor1)): the name in lower camel case without a trailing Image or Color, a nested type per folder that provides a namespace (ImageResource.Fountain.terracotta). An app target also gets Color and ShapeStyle members (.foregroundStyle(.accent)) when it sets ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS, as Xcode's templates do, except those SwiftUI has or the module declares; ASSETCATALOG_COMPILER_GENERATE_ASSET_SYMBOLS = NO turns them all off. Image(_:bundle:) and Color(_:bundle:) name the app's catalog.

PDF images. Browsers cannot show a PDF in an <img>. The build renders each PDF image set's first page with pdf.js and Node's canvas (@napi-rs/canvas, which pdf.js installs where it has a prebuilt binary) to a PNG at 3× with a transparent background, encoded from the pixels (Web/plugins/pdfImages.ts); renders are cached in the OS temporary directory by the PDF's bytes. An image whose PDF does not render leaves the manifest with a warning.

Custom layouts read layout values. .layoutValue(key:value:) marks the elements of the view it modifies; wrappers outside it (styled, decorated, gestures) keep the mark, and a custom layout's subview reads it (subview[Key.self]), the value set closest to the view winning. Backyard Birds places each layer of a backyard this way.

Styles. A ShapeStyle of the app's own (resolve(in:)) is encoded as the style it resolves to in the page's environment (its color scheme…), which a change re-renders every view for; an ancestor's .environment is not seen. .fill, .fill.secondary… are the system fills, .separator the separator color, a Gradient paints top to bottom, Color.Resolved is a style. ShapeStyle.blendMode(_:) paints the style as it is. .background() paints the background style in context (.backgroundStyle(_:)), as .background(in:) already did. .tint takes any style: a gradient tints with its first color.

Shapes. shape.stroke(lineWidth:) is a shape (iOS 17): drawn, or filled with a style (.overlay(.bar, in: .capsule.stroke())), it is the base shape's outline in that style.

Scroll views. .contentMargins(_:_:for:) pads the content of the scroll views below (the margins of nested modifiers combine by edge, the closest winning), once around the whole content: several views are padded as the stack the scroll view lays them out in (a vstack, or an hstack for a horizontal-only scroll view), not each on its own. The nearest scroll view takes the margins: scroll views inside its content do not inherit them. .scrollIndicators margins change nothing. .scrollTransition sends its three phases (the scrollTransition style), which the renderer draws as the view scrolls, and GeometryProxy.bounds(of: .scrollView) is nil.

Animation. PhaseAnimator and .phaseAnimator move through their phases in a task, each change in its phase's animation, waiting out the animation's delay and duration (on the timeline clock: virtual in tests). Without a trigger they cycle; with one, each change of the trigger runs through the phases once. .transition(.scale(0.5)) is iOS 17's spelling.

UIKit traits. A UITraitBridgedEnvironmentKey reads its value from the current traits (an iPhone's) until a view sets it, so Backyard Birds' prefersTabNavigation is true and the app shows its tab bar.

SwiftData. @ModelActor gives an actor its container, an executor with a context of its own and init(modelContainer:); the actor runs on the main actor's executor (Apple's on the model executor), where the context expects to be. import SwiftData re-exports Foundation, as on Apple platforms. Foundation off Apple platforms has only .lexical among the string comparators and builds no other, so .localizedStandard and .localized order as .lexical does.

Alignment guides. .alignmentGuide(g) { d in … } moves the view's guide: the closure is evaluated at 0×0, 100×0 and 0×100 and sent as the styled key alignmentGuide: {axis, name, value: [a, b, c]}, the guide being a + b·width + c·height (exact for the usual d[.trailing] + 4, d.height / 2, constants). Where a stack (on its cross axis), a ZStack, a frame or an overlay or background aligns a child by name, a child that moved that guide (on itself or a styled wrapper inside it) is placed so its guide meets the container's; the other children keep their place, unless a guide reaches past the stack's own, which moves them all along. Backyard Birds puts its member icon before the account name this way (.overlay(alignment: .leading) with the icon's guide d[.trailing] + 4). A decoration in an if (decorated prop conditional: true) is aligned by its edges, its guides unused, as iOS 26 draws Backyard Birds' quantity badge (if food.isPremium { … .alignmentGuide(.bottom) { … } } in an .overlay(alignment: .bottomTrailing)) in its image's corner. Custom alignments still align as the built-in guide their default matches, and guides do not travel out of nested stacks. The list-row separator guides (.listRowSeparatorLeading, .listRowSeparatorTrailing) are guides of their own, which nothing aligns by. When they shared .leading's name, Ice Cubes' .alignmentGuide(.listRowSeparatorLeading) { _ in -100 } on its status rows moved the quoted post inside a post 100 points right in its leading VStack.

Spacers last. A stack sizes its spacers after its other children, even infinitely flexible ones: iOS lays out Ice Cubes' quoted post (HStack { VStack(alignment: .leading) { … }; Spacer() }, whose text is in a .frame(maxWidth: .infinity)) across its whole card, the spacer keeping its 8 points. The page split such a stack evenly, so a quote took half its card and its author's handle wrapped onto three lines (Examples/Fidelity, post).

Modifiers on a group. A modifier applied to a group of views applies to each view, as in SwiftUI. It also does so through a wrapper that only holds a group: Group, AnyView, an optional, a conditional, a tuple. Ice Cubes' post header puts .layoutPriority(1) on Group { name; if locked { lockBadge } } in a first-baseline HStack. The group's one child is the tuple, so the modifier wrapped both views in one styled element, which stacked them vertically: the lock sat under the name. A view of the group that is absent (the badge of an unlocked account) gets no element of its own, so it takes no stack spacing. A wrapper that does something (an environment value, a task) still takes the modifier as one view.

Circular gauges draw their ring (see gauge): Backyard Birds' supply gauges show the food inside a capacity ring.

Accepted, not drawn. .searchSuggestions and .searchCompletion (the page's search field shows no suggestions), .flipsForRightToLeftLayoutDirection (the page lays out left to right), .scenePadding (16 points), .storeButton, .subscriptionStoreControlIcon, SubscriptionStoreView(groupID:visibleRelationships:). EntitlementTaskState has value and map.

Food Truck#

Apple's Food Truck sample (its iOS app, swiftbrowser build … --target "Food Truck") builds from its Xcode project unchanged, with its FoodTruckKit package. Examples/FoodTruck keeps the trimmed copy the snapshot and e2e tests use.

canvas element#

A Canvas is a GeometryReader whose content, at the reported size, is a canvas element: the renderer closure runs in Swift against a GraphicsContext that records what it draws (Sources/SwiftUI/API/Canvas.swift).

prop meaning
width, height the size the closure drew for (the geometry's report)
commands what it drew, in order (later on top)
measure the resolved texts, images and symbols whose size the closure asked for and has not been told (below)

Each command has an op and the context's state when it was drawn: transform ([a, b, c, d, tx, ty], a CGAffineTransform; absent for the identity), opacity (absent at 1), blendMode (CSS mix-blend-mode), clips (SVG path data in the canvas's coordinates; the command draws inside all of them) and filters ({blur}, {shadow: {color, radius, x, y}}, {grayscale}, {saturation}, {brightness}, {contrast}, {hueRotation} in degrees, {invert}).

op fields
fill path (SVG path data), shading, evenOdd
stroke path, shading, lineWidth, lineCap, lineJoin, miterLimit, dash, dashPhase
image image (an image element's props), x, y, anchor (the unit point of the image placed there), width / height for draw(_:in:) (else the image's own size), shading (a resolved image's)
text text, x, y, anchor, shading, font (the environment's), runs (a styled Text's strings with their own font, weight, italic, color, decorations, kerning and baseline offset, as a text element's; absent for an unstyled string)
symbol index (the symbol's among the element's children), x, y, width, height: the rectangle it is drawn in, scaled from its ideal size

A shading is a ShapeStyle or a gradient in the drawing's coordinates: {canvasLinearGradient: {stops, start: {x, y}, end: {x, y}}}, {canvasRadialGradient: {stops, center: {x, y}, startRadius, endRadius}}. A conic gradient is its first color; drawLayer draws into the same list with its own state. A text's runs draw in their own font over font and in their own color; shading fills the runs without one, as ResolvedText.shading fills only uncolored text in SwiftUI.

Sizes. A resolved text's measure(in:) and baselines, a resolved image's size, and a resolved symbol's size come from the page, as a GeometryReader's size does. When the closure reads one it has no answer for, the drawing lists it in measure, each request with its key (the request's own JSON): a text by text, runs, font and maxWidth (measure(in:)'s finite width, which it wraps at), an image by image, a symbol by symbol (its index). The engine lays each text out as the text element it would be, in its font (the body's without one), with the baselines where the page centers glyphs in a line; an image at the size the canvas draws it at a point (an asset's catalog size, a remote image's given size, a symbol 20 points square); a symbol at its ideal size. After the layout pass the page sends {type: "canvasmeasure", id, measures: {key: {width, height, firstBaseline, lastBaseline}}} for the keys whose answer it has not sent yet, and Canvas keeps the answers in its state and draws again. A text or image stops asking once answered; a symbol asks on every drawing, since its content can change, and hears again only when its size does. Until the answer arrives a size is .zero, and a symbol drawn at a point is not drawn.

Symbols. The views passed as symbols are the element's children, one element each (a zstack around the view), resolved by their .tag. They are laid out at their ideal size at the canvas's origin and hidden; after each layout pass each symbol command's <foreignObject> holds a copy of its child as that pass left it (src/ghost.ts's clone, whose ids are ghost ids), scaled to its rectangle.

Layout. Fills its proposal, like a shape; its children (the symbols) at their ideal size at its origin.

Rendering (Web/src/canvasDrawing.ts). An SVG the size of the drawing, clipped to the element's box: each command a <g> (opacity, blend mode, filters, clip) around one <path>, <image>, <text> (a <tspan> per run), symbol <svg> or <foreignObject> (its transform). Paints are CSS, so asset and semantic colors follow the color scheme. An update reuses the elements in place and changes an image's href only when its source changes, so a canvas in a TimelineView (Food Truck's animated header) keeps its decoded images from frame to frame.

Not drawn: bitmaps (Image(uiImage:)), inverse clips, an image inside a canvas text, and the color-multiply, luminance and alpha-threshold filters.

Tables#

Table is drawn as iOS draws one: a list. In a compact width each row shows the first column only; in a regular width every column, side by side, under a row of the column titles. A column's width(_:) fixes its width; the others share the rest. Rows are TableRows, in ForEach and Section as in SwiftUI, and selection is the list's.

A column with a value: key path sorts: its title is a button that puts its KeyPathComparator first in the sortOrder binding, or reverses it when it is first already, with a chevron showing the order. The app sorts its rows by the binding, as with SwiftUI's table. Table(_:) takes an array, or any collection with the closure's parameter type written out ({ (row: Row) in … }): Swift infers the row type of a generic collection too late for the columns' closures.

Frameworks#

  • WeatherKit (Sources/WeatherKit): Apple's weather service answers only apps signed with the WeatherKit capability, so every request throws WeatherError.permissionDenied, as it does on a device for an app without it. The types are all there; Food Truck keeps its placeholder forecast.
  • Passkeys and passwords (Sources/AuthenticationServices/Authorization.swift): in a browser a passkey is WebAuthn, which answers only for the page's own domain, so an app's relying party (Food Truck's example.com) can't be reached. ASAuthorizationController and SwiftUI's @Environment(\.authorizationController) end every request in ASAuthorizationError.notHandled, as a device with no credential to offer does. Food Truck's password sign-up still works.
  • MKMapView (Sources/MapKit/MapView.swift): a UIKit view that keeps its region and settings, and whose layer draws this module's SwiftUI Map showing that region, with its annotations as markers. Setting its camera shows the region the camera sees. The app's own changes move it; gestures do not. (SwiftUI-Introspect's Map support names the class too.)
  • CLLocation: coordinates, accuracy, course, speed and distance(from:) (great-circle).
  • StoreKit: @Environment(\.displayStoreKitMessage) (a no-op: the page shows no App Store messages), Product.SubscriptionPeriod.Unit.formatted.
  • AppIntents: SiriTipView and ShortcutsLink draw nothing (there is no Siri or Shortcuts app).
  • ActivityKit is not provided. Food Truck imports it under #if canImport(ActivityKit), so it takes its own path without live activities, as on macOS.

Smaller additions#

  • @SceneStorage: the page is one scene, restored when it reloads, so a scene-stored value is an @AppStorage value under the key SceneStorage.<key>.
  • A shape style with a drop shadow (.shadow(.drop(…)), and .shadow(…) alone for the foreground) carries a shadow key, which a shape filled with it draws as a CSS drop-shadow. Food Truck's cards cast their shadow from .background(.shadow(.drop(…)), in: shape.scale(0.99)). Inner shadows, and shadows on text, are not drawn.
  • shape.scale(_:anchor:) / scale(x:y:anchor:) (ScaledShape), drawn from its path.
  • An AttributedString's runs take kern, tracking, baselineOffset, foregroundColor and font, which Text(_:) draws.
  • Measurement.formatted() and Measurement.FormatStyle: the value, then the unit's symbol ("5 km", "21°C"). A temperature is converted to the locale's unit (Fahrenheit in the United States) unless its usage is .asProvided.
  • .chartPlotStyle { … } styles the whole chart: the page lays the plot out inside it, so the plot is not a view of its own.
  • UIViewController.additionalSafeAreaInsets and .menuStyle(.borderlessButton) are accepted.
  • Custom symbols. A .symbolset holds an SF Symbols template: one sheet with notes, guides and the glyph in every weight and scale, which drew as a gray smear when used whole as the mask. The build publishes its Regular-M glyph (else another Regular one), cropped to the template's margins for it (Web/plugins/symbolTemplates.ts); Food Truck's donut and flavor symbols.
  • Container shapes. .containerShape(_:) sets the shape below it that a ContainerRelativeShape (filled, or .clipShape(.containerRelative)) takes its corners from, and that .background(_:) and .background() are painted in (the styled key backgroundCornerRadius, which rounds the background without clipping the content). Without one they are rectangles, as in SwiftUI. Food Truck's cards are rounded this way.
  • System colors in catalogs. A color set that names a system color ("reference": "systemIndigoColor", Food Truck's accent) is read as that color in light and dark.
  • The app's accent. A catalog color named AccentColor (what Xcode's global accent setting names in its templates) is the page's accent (--sb-color-accent): buttons, links, toggles and selection, as on iOS.
  • Date axis labels start at their tick (the anchor: "leading" of an x-axis label), as Swift Charts places a date's label; other values stay centered on theirs.
  • Axis marks for values outside the scale's domain are not drawn, as in Swift Charts: Food Truck's forecast asks for hour bins that start before its first entry, whose first label sat on top of the second.

Host elements (the page's own DOM)#

A producer running in the page (such as @swiftbrowser/react, whose Host component renders a React DOM tree) can put its own DOM inside the tree:

kind props children
host content: string, sizing: "fill" | "content" none

content is the key the page registered an element under in Web/src/hostContent.ts; the renderer adopts that element into the host's box, which the layout engine positions like any leaf. A content registered after the element was created (from a React effect, say) is adopted at the next change notice. fill takes the proposal (and the content's own size on an unconstrained axis, such as the height in a vertical scroll view); content takes the content's ideal width capped by the proposal and its height at that width, like text. The engine measures the element in the DOM (measureHost on the measurer); headless layouts, which have no DOM, measure a host as a 10×10 placeholder. A host that is a list row is drawn in the row's box, as every row is, and its content element is positioned back into the row's content frame (Web/src/hostInset.ts), so content that fills its box fills what it was measured for, not the row's padding too. When the content changes size on its own, the renderer lays the tree out again (notifyHostContentChange, and a ResizeObserver on the content). The Swift core never emits host.

The layout environment's contentHeight flag (set by the page for an island, @swiftbrowser/react's SwiftUIView with fit="content") proposes a plain root the screen width and no height and places it at the top, so the root is as tall as its content; the renderer then sets the root element's height.

Registered views#

A view a package (or the app) draws itself, by a name each renderer resolves in its own ViewRegistry:

kind props children
registered name: string, props: object the native view's own (it places them)

On a page Web/src/viewRegistry.ts builds the element registered under name when the element is created, hands it the new props on an update (update) and lets it go with the element (dispose); the element fills the box, which the layout engine sizes as geometry's: the proposal, 10 on an unconstrained axis (so a frame, a stack or a flexible parent gives it its size). The element's children are not drawn on a page. A native app builds the SwiftUI view registered under the same name (SwiftBrowserNative's ViewRegistry), its children placed by the view (context.content). A name nothing registered draws as a visible placeholder. What a view sends arrives as {"type": "registered", "id": n, "name": string, "value": any}. Producers emit it through RegisteredView (@swiftbrowser/react); the Swift core never does itself, but frameworks above it do (RealityKit's RealityView, through _RegisteredElement).

Frames#

A binary channel beside the ops, for registered views that draw every display frame (RealityKit's RealityView; docs/realitykit.md). A framework registers a frame source with SwiftUI's _FrameHost and names its number in the element's props; the page's view calls it once per animation frame. Nothing of the element tree changes, so no reconcile or layout runs.

Export Meaning
sb_frame(source: i32, now: f64, flags: i32) -> i32 Renderer → Swift: steps frame source source for the frame at now (performance.now(), ms) and answers the length of its bytes, or -1 when no source has that number (it went with its view). flags bit 0: the renderer has nothing yet and wants the whole state, not what changed since its last frame.
sb_frame_ptr() -> i32 Where the last frame's bytes are; valid until the next sb_frame (the renderer copies them).
sb_frame_input(length: i32) -> i32 Renderer → Swift: a buffer of length bytes the renderer fills before the next sb_frame, which hands them to its source with the frame (RealityKit's view sends its camera; docs/realitykit.md, "Frame input"). Optional: a frame without it has no input.

The bytes are the source's own format (RealityKit's is in docs/realitykit.md, "Wire format"). After a frame the renderer runs the executor (sb_run_jobs), so what the frame changed in the app's state is rendered as usual. A registered view reaches the channel through its context's frame(source, now, full) (src/viewRegistry.ts), which answers null where the host has no module or no such source; a module without the exports never has frame sources.

Pointer, effects, matched geometry and frames on screen#

Fields page-side producers (@swiftbrowser/react) send for a page that may have a mouse and a keyboard. The Swift shim draws an iPhone and sends none of them; they change nothing for a module that does not.

styled style meaning
hover: true the page sends {"type": "hover", "id": n, "value": true|false} as a mouse or pen enters and leaves the box (never for touch); the whole box is hit, its empty space included
continuousHover: "local"|"global" the page sends {"type": "continuoushover", "id": n, "phase": "active", "location": {x, y}} as a mouse or pen moves over the box, one per animation frame, the location in the box's own coordinates or the root's (scrolling included, as a reportsFrame geometry event reports), then {"type": "continuoushover", "id": n, "phase": "ended"} once as it leaves (.onContinuousHover)
help: string a tooltip (the box's title)
pointerStyle: string the CSS cursor over the box
symbolEffect: {effect, direction?, speed?, repeat?, trigger?} SF Symbols' effects drawn with the CSS scale, rotate, translate and opacity properties (so they compose with the box's own transform): bounce, pulse, variableColor, rotate, wiggle, breathe play repeat times (forever when absent or "forever") and keep running across updates that leave them alone; scale (up, down) and appear / disappear hold a look while set. With trigger the effect plays once each time the number changes (never for the first value), like .symbolEffect(_:value:)
matchedGeometry: string an id (the namespace is part of it). In a pass that may animate, a box inserted with the id of a box the pass removed starts from the removed box's frame (a translate and scale from the frame it is drawn at once its ancestors' tweens begin, to none), and the removed box's exit clone moves and scales onto the new box's final frame, both in the commit's timing; the usual transitions (a fade by default) play too
contentTransition: {kind, countsDown?} how a text under the box changes in a pass that may animate. numericText: a copy of the old text leaves upward (fading and blurring) while the new text comes in from below, both in the commit's timing; downward instead when countsDown is true, or, without countsDown, when the new text reads as a smaller number. opacity and interpolate: the old copy fades out while the new text fades in. A pass that does not animate swaps the text

geometry props take reportsFrame: true: the reader's geometry events then carry x, y (its origin in the root's coordinates, scrolling included, whole px) and safeArea ({top, leading, bottom, trailing}: how far the device's safe area reaches into the reader), are sent when any of them changes, and are checked again once per animation frame after a scroll inside the root, since scrolling moves the reader without a layout pass. Inside a scrollview or list they also carry scrollView ({x, y, width, height, axis}): that scroll view's visible rectangle in the root's coordinates and the axis it scrolls along (horizontal or vertical). @swiftbrowser/react's GeometryReader sets it once its content reads frame('global'), bounds('scrollView') or safeAreaInsets; its visualEffect modifier wraps the view in a zstack with reportsSize (and reportsFrame once the closure reads the frame) and draws its effects in a styled inside it. Its scrollTransition calls the closure once per phase and sends the scrollTransition style.

Rich text editors#

TextEditor(text: $attributed, selection: $selection) (iOS 26), and .scrollDisabled, for an editor whose text has runs of their own: bold words in a paragraph, a struck-through one, a colored one.

On the wire. A texteditor gains runs (the runs of a rich text, whose texts join to text) and selection: { start, end } (UTF-16 offsets; present when the selection is bound). An editor created with runs, an empty array included, is the rich editor for its life. It still sends plain text as the viewer types: the app keeps the runs, and the typed text takes the attributes of what it replaced, else of the character before it (@swiftbrowser/react's AttributedText.replacingCharacters). When the editor's own controls change attributes alone (iOS 26's edit menu offers Bold, Italic and Underline over an attributed editor), it sends { "type": "runs", "id", "value": [run, …] }: the text unchanged, its runs as the editor now shows them, cut where the formatting changes and each keeping the other attributes the app sent for its characters (a color, a link); the app's AttributedText becomes those runs (fromProtocolRuns), so the formatting the viewer applied is the document's and survives the next render.

selection means the same on a plain editor (TextEditor(text: $string, selection:)) and a rich one. A bound editor sends { "type": "selection", "id", "value": { "start", "end" } } as the viewer moves the caret or selects, and not the one the app sent back; a selection the app sends (one the editor did not report) moves the caret there, at once in a focused editor, else when the app focuses it (its bound focused), so an app can put the caret at the end of a paragraph it focuses.

A text that is not the echo of what the editor reported (another person's edit, the app's own change) moves what is under the caret, so the caret is kept in place: the app's selection, when bound, is applied even when its numbers did not change (the same offsets mean a move once the text changed), and without one the caret is moved past the change (the same offset before the change, shifted by its length after it, the change's end inside it: shiftOffset on the web, caretAfterChange natively). The echo of the viewer's own typing still leaves the caret alone.

Marks. marks: [{ start, end, color }] (UTF-16 offsets, a Color JSON object) are ranges drawn with a color behind their characters: a graph's selected node in its source, a find's matches (@swiftbrowser/react's TextEditor marks, the accent at a quarter by default). They are the view's alone, not part of the text or its runs: no caret moves, nothing takes the focus (no keyboard comes up), no event reports them, and a change of marks alone leaves the runs and their spans as they are. The web's rich editor draws them with the CSS Custom Highlight API (a Highlight per color, ::highlight() rules in a style[data-sb-marks], a range for each paragraph a mark covers among the lines drawn; a browser without the API draws none); the in-memory renderer draws them behind the runs' backgrounds; natively the iOS 26 rich editor sets them as backgroundColor on the string it holds when they change. A plain editor (a textarea; the iOS 18 TextEditor of a String) has no way to draw them.

defaultMinListRowHeight is a style (.environment(\.defaultMinListRowHeight, _)), inherited: every list below spaces its rows at least this tall, unless it has its own minRowHeight; a Mac grouped form (formStyle: "grouped") keeps its 36 form rows. The Swift shim sends the environment value on each list as minRowHeight; React sends it once as this style, so it reaches a tree drawn through RemoteTree too. Natively it is SwiftUI's environment value.

scrollDisabled is a style (.scrollDisabled(_:)), inherited, false turning an ancestor's off. Under it a texteditor is as tall as its lines whatever the proposal: the proposed width (200 when nil), its lines (one more after a last newline, at least one) inside UITextView's 8 / 5 insets. A plain editor's lines are a leading apart. A rich editor's are broken by the text system the web view draws them with (Web/src/richEditorText.ts, editorLines), each the editor's leading tall or, holding a run in a larger font, that font's leading, as UITextView spaces them. Natively it is SwiftUI's modifier, so scroll views below stop scrolling too; the web renderer reads it in text editors only.

Web. The rich editor is a div.sb-texteditor (contenteditable, plaintext-only where the browser has it) drawn and edited through the text system (docs/notes/textkit.md, "The rich editor"): the storage holds the plain text, the runs are each paragraph's presentation (a run's font, slant and kerning as a presentation run's font, its colors and lines as rendering attributes), the layout breaks the lines, and the view draws the fragments in view as placed rows of a span per run, feeding the keyboard to the EditorController (Web/src/richEditor.ts, Web/src/textkit/view.ts). Under scrollDisabled it breaks its lines in the width the layout engine measured it in, with the same presenter and measure, and draws those in the window's view; a scrolling editor draws those in its own. Until the app's runs come back, typed text takes the attributes of what it replaced, else of the character before it, as replacingCharacters gives it, so the echo draws nothing. A text equal to the editor's changes nothing (the caret and the undo steps stay); one the editor reported and has typed past since is an echo that is behind, and is let go; any other is from outside (its undo steps go, the caret is kept as above). The text and selection are reported once the edit is done (a microtask), so an app answering inside the event finds it finished. Undo and redo are the editor's (Command-Z, Control-Z elsewhere), each step an edit the app hears as text; Return inserts a newline, Tab moves the focus, copy and cut take the selection's text, pastes and drops insert plain text, and the browser's own formatting is off. A composition runs in the browser's line and comes back as one edit when it ends; props that arrive during it are applied then. The browser has no formatting of its own in it, so the web renderer never sends runs. A plain editor's bound selection is the textarea's selectionStart/selectionEnd (Web/src/plainEditor.ts); both editors keep what they reported and what the app set to apply in Web/src/editorSelection.ts.

Native. On iOS 26 the runs become an AttributedString (a run's weight and slant over the editor's font, underline and strikethrough .single, a color run's foregroundColor) in TextEditor(text:selection:); while the app's runs are the ones the editor's string stands for, the editor keeps its own string, so an edit's echo leaves the caret alone. A write of the string with the same characters and other attributes is the system's own formatting: its runs are read back (Font.resolve(in:) for the weight and slant, the line styles) over the app's runs and sent as runs. Earlier systems show the plain editor of the same text; a plain editor with selection is TextEditor(text:selection:) from iOS 18 (TextSelection to and from UTF-16 offsets, as the rich editor's AttributedTextSelection), the editor without the binding before. texteditor's bound focused now moves the focus natively too.

Shim. TextEditor(text: Binding<String>, selection: Binding<TextSelection?>?) (iOS 18, Sources/SwiftUI/API/TextSelection.swift) and TextEditor(text: Binding<AttributedString>, selection: Binding<AttributedTextSelection>?) (iOS 26, Sources/FoundationBridge/RichTextEditor.swift, which holds the string's SwiftUI attributes) send a bound selection as UTF-16 offsets of the TextSelection's or AttributedTextSelection's indices (several ranges as one, from the first to the last) and set the binding from selection events (a range, or an insertion point when start == end). A selection that selects nothing (a nil TextSelection?, AttributedTextSelection()) sends the selection the editor last reported, the start of the text before any, so the editor keeps reporting and no caret moves; after an edit a selection past the text's new end moves to the end, as the editor keeps its own, so the app's indices stay valid until the editor reports where the caret went. The rich editor's runs are the string's as Text(AttributedString) draws them (a run's font with its size, weight and design, the inline presentation intents, underlineStyle and strikethroughStyle, the colors, the link); its text events edit the characters, compared by Unicode scalar, the typed ones taking the attributes of what they replaced, else of the character before them (AttributedString._replacingCharacters(with:)); and a runs event writes each run's formatting over its characters, leaving their other attributes: bold as the run's font weight when it has a font (.bold, back to .regular), else as the strong-emphasis intent; italic and strikethrough as intents; underline as underlineStyle.

Focus across a submit#

SwiftUI's @FocusState with an enum (.focused($field, equals: .password)) lets .onSubmit keep the keyboard up or move it to the next field, and a field it focuses is scrolled into view. The protocol's per-field focused is unchanged on the wire; what changed is what a renderer owes it.

The app's answer to submit wins. Return runs the app's handler (submit) and then the platform dismisses the keyboard; the two are not independent. A renderer applies the pass that answers submit first, and then reads the field's focused back: left true (set again, or never changed), the field keeps the focus and the dismissal is dropped, no focus event sent; turned false, the dismissal goes through (nothing to report either); another field's turned true, that field takes the focus. The web renderer never blurred on Enter, so there the rule is already true; SwiftBrowser Native's TextFieldElement dispatches submit synchronously, re-reads the prop when it returns, and holds the focus against the resign that SwiftUI's own onSubmit is followed by (taking it back when it comes, within the turn, without a focus event; nothing comes on macOS, so the hold lapses after 300 ms). A focus: false the platform sends for a field the app has moved on from is still answered correctly by a @swiftbrowser/react app: a shared focus binding clears its value only while the value is still that field's.

A field that gains the focus is revealed. When a pass turns a textfield's or texteditor's focused true (a new element included), the renderer scrolls its scroll views and lists as little as shows it, after focusing it, as a scrollTo without an anchor would (Web/src/scrollTo.ts from the layout's frames; a sheet still sliding in is never a reason to scroll the page, and in device mode the frames already stop above the keyboard the focus raised). The keyboard growing afterwards (device mode's measured height) reveals the text input being edited again, as iOS keeps a field above the keyboard. Natively SwiftUI does both itself for a field @FocusState focuses. An explicit scrollTo in the same pass still runs after and wins.

@swiftbrowser/react. TextField, SecureField and TextEditor take focused as before (a boolean binding) or, with focusedValue, a binding of the focused field's value shared among the fields (focused={[field, setField]} focusedValue="password"): each emits its own focused: true|false, a focus: true sets the value, a focus: false clears it only while it is the field's. The Showcase's Numbers keeps one entry field for every cell (it remounted it per cell to survive Return), Reminders shares one binding among its rows (Return names the new row), and Pages no longer calls scrollTo for the block it focuses.

Undo#

useUndoManager() in @swiftbrowser/react is @Environment(\.undoManager) (packages/react/src/undo.ts): a stack of named undo closures with NSUndoManager's rules (a closure registered while undoing lands on the redo stack, a new registration drops the redo stack, registrations in one event form one group, beginGrouping/endGrouping make one of several, a key joins a run of registrations into one step). No op changes: the stack is JavaScript, because its closures are, and canUndo must change in the pass that registered them. What changes is where the system's undo comes from and what it is told, through one more field of the web renderer's host request environment (Web/src/hostRequests.ts):

undoManager?: {
  update(state: { canUndo, canRedo, undoActionName, redoActionName }): void;  // after each change
  listen(commands: { undo(), redo() }): () => void;                           // the last to listen gets them
}

Web (Web/src/undo.ts). The host is the keyboard: ⌘Z and ⇧⌘Z (Ctrl-Z, Ctrl-Shift-Z and Ctrl-Y off Apple platforms) on the document while a manager listens, except from inside an input, textarea, select or editable, whose own undo the browser keeps; update shows nothing, a page having no Edit menu.

Native (packages/native/src/undo.ts, Host/UndoBridge.swift). The bridge gains undoState(json), the state as JSON, and the callback __sbUndoCommand("undo" | "redo"). The window's UndoManager (the root view's @Environment(\.undoManager), handed to NativeApp.setUndoManager) mirrors the state: each update removes the bridge's actions and registers one proxy on the undo stack when the app can undo and one on the redo stack when it can redo, named as the app names them (the redo stack is reached the only way UndoManager allows, by undoing a no-op that registers the proxy while undoing). A proxy the system runs (a shake, the three-finger swipe, ⌘Z, the Edit menu) sends the command to the app, whose new state arrives while the manager is still undoing, so the mirror is rebuilt on the next turn of the run loop. Against the shim (the round trip) the page's keyboard is the host and the bridge is left out.

Swift (Sources/SwiftUI/API/UndoManager.swift). swift-corelibs Foundation has no UndoManager (on WASI or on Linux), so the shim declares it with Foundation's API as SwiftUI apps use it: registerUndo(withTarget: handler:) (and the selector form, over the bridge's Selector; prepare(withInvocationTarget:) is unavailable), undo(), redo(), canUndo, canRedo, undoActionName, redoActionName, setActionName(_:), beginUndoGrouping(), endUndoGrouping(), groupingLevel, groupsByEvent, levelsOfUndo, removeAllActions(), removeAllActions(withTarget:), isUndoing, isRedoing, disableUndoRegistration(), the menu titles. The rules are NSUndoManager's, as above; targets are held weakly. import SwiftUI brings the class along (iOS's re-exported Foundation does), and FoundationBridge re-exports it for a file that imports only Foundation. The runtime keeps one manager per app, in every view's environment (@Environment(\.undoManager)), and is its run loop: at the end of each turn (an event, an executor run, the launch) it closes the group the turn's registrations opened (groupsByEvent), then, when what the stacks can do changed since the page was last told, sends an undo host request whose params are the state, {"canUndo","canRedo","undoActionName", "redoActionName"}. The page answers {} (nothing waits for it: _Runtime._notifyHost) and hands the state to the environment's undoManager host (performUndo, Web/src/undo.ts); the first such request makes the page listen to the keyboard (relayUndo, installed by Web/src/main.ts), whose undo and redo come to the app as events addressed to no element, {"type":"undo"} and {"type":"redo"}, which the runtime routes to the manager. A key past the end of a stack changes nothing and sends nothing. Event scripts replay them as the bare lines undo and redo; headless, the request shows in the op log as the record of what the app could undo. Not here: the NSUndoManager… notifications and runLoopModes.

In the Showcase, Freeform, Keynote, Numbers and Pages edit their documents through useUndoableState (src/shared/undoable.ts): a change registers the undo back to the state before it, which, run, registers the state it left as the redo; Pages' typing joins by the paragraph's key; the editor's registrations go when it does (removeAllActions(target)).

Gesture spaces and composition#

What a canvas whose items carry their own gestures needs, mirroring SwiftUI: DragGesture(coordinateSpace:), .simultaneousGesture and .highPriorityGesture, .onTapGesture(count:) and .contentShape. The Showcase's Keynote is the driver (Native/Examples/Showcase/src/keynote): each slide item is pressed, double-tapped and dragged on its own, and the slide composes a background tap and, while writing, a touch that only ends the writing, where one full-size gesture used to hit-test every item by geometry.

gesture gains coordinateSpace and mode.

{ "kind": "gesture", "props": { "drag": true, "minimumDistance": 0,
  "coordinateSpace": "global",      // "local" (absent) | "global"
  "mode": "simultaneous" } }        // absent (.gesture) | "simultaneous" | "highPriority"

coordinateSpace is the space of a drag event's location and startLocation (translation and velocity are the same in any). local is the element's own box, as before; global is the root's coordinates, scrolling included, the same a reportsFrame geometry event reports its origin in, so a space named with .coordinateSpace(name:) is the global point less that space's reported origin: @swiftbrowser/react resolves { named } that way, from the frame its coordinateSpace wrapper heard (global until it has). A view a local drag moves moves its own space with it; a canvas drags its items in the canvas's space. Natively it is DragGesture(coordinateSpace: .global); the web renderer subtracts the root's box instead of the element's.

A gesture switched off by its mask (.gesture(drag, including: playing ? .all : .subviews)) keeps its gesture element with drag, longPress, magnify and rotate off, so the view under it is the same view, state and all, when the mask changes; the page leaves such an element out of every touch. A tap switched off has no tapgesture element. The mask's other half, switching the subviews' gestures off, is not done.

mode is how the gesture composes with the others between the pointer and the root. Absent, .gesture: the wrappers are asked innermost first and the first whose motion matches claims the pointer. highPriority (.highPriorityGesture): asked before the wrappers inside it, an outer one before an inner one, though still after the system's (a row's grip, the back swipe). simultaneous (.simultaneousGesture): never claims. It begins when its own minimumDistance is met (at the pointer down with 0) and hears every move and the lift beside whatever else owns the pointer, before any claim and after one, and its running does not stop another gesture from claiming later. A simultaneous drag alone over a tap leaves the tap to land (as SwiftUI's tap and simultaneous drag both fire) unless the pointer moved 10 px, which was a drag and no tap; a claim still swallows the click. Natively the drag or long press attaches with .gesture, .highPriorityGesture or .simultaneousGesture as mode says (pinches were simultaneous already). Headless nothing changes. The Swift shim sends mode from the modifier (.gesture none) and coordinateSpace: "global" for a .global or .named drag; .coordinateSpace(name:) is a layout-transparent zstack with reportsSize and reportsFrame, as the React one, and a drag in its name subtracts the origin it last reported, read as the event arrives (DragGesture.Value.location and startLocation; translation is the same in any space), so a space that moved under a scroll costs no pass. The runtime passes a geometry event's x and y on to the element's handler with its size.

tapgesture gains count (.onTapGesture(count:), 1 when absent). With 2, the element sends one tap for two clicks within the double-tap interval (300 ms, src/gestureComposition.ts); a tapgesture of one tap around it (or inside it) waits that interval before sending its own, so a double tap on a view with both lands as a double tap only, and a single tap arrives late by the interval, as iOS delays it. A click elsewhere ends a count, sending the single tap it held. count is read from the data attribute at the click (data-sb-tap-count), so an update changes it at once. Natively it is .onTapGesture(count:); SwiftUI delays the single tap only when the double tap is the inner modifier, so a producer puts the double tap inside (@swiftbrowser/react: onTapGesture={{ count: 2, … }} with the single tap in modifiers). The Swift shim sends a count above 1 from .onTapGesture(count:), its located overload and TapGesture(count:).

styled gains contentShape: "rectangle" (.contentShape(Rectangle())). The page hit-tests like SwiftUI: a stack or modifier box is not hit in its empty space, a stroke-only shape only along its line, so a clear box or a small handle in a larger target took no taps without a painted fill (Keynote hedged with a near-transparent #FFFFFF01 rectangle). The hint makes the box take input across its area (pointer-events: auto, marked data-sb-content-shape); natively it is the modifier. Only the rectangle: another shape would need the box clipped for hit testing, so the Swift shim's .contentShape(_:) sends the hint for any shape (a Circle() hits as its bounding box), and .contentShape(_:_:) when the kinds include .interaction.

TypeScript: GestureProps.coordinateSpace (GestureCoordinateSpace), GestureProps.mode (GestureMode), TapGestureProps.count, Style.contentShape. Swift mirror: GestureProps.coordinateSpace and .mode, TapGestureProps.count, Style.contentShape.

Editors, bars and alerts for a word processor#

What the Showcase's Pages lacked to behave as Pages does: the delete key at the start of a paragraph, highlights and sizes inside an editor's runs, the bar above the keyboard, a rename alert with a field, and text measurement to break pages where the text ends.

The delete key at the start of a field#

A textfield or texteditor with deleteBackward: true (SwiftUI has no modifier for it; @swiftbrowser/react's onDeleteBackward on TextField and TextEditor) sends { "type": "deletebackward", "id" } when Backspace is pressed with nothing selected and the caret at offset 0 (an empty text included), and deletes nothing: there was nothing to delete, so the app hears it and merges the field into what comes before it, say. Elsewhere in the text the key deletes as it does, sending text.

Web: beforeinput with deleteContentBackward on the input, the textarea or the rich editor, the selection read as the editor's (UTF-16 offsets for the rich one), the default prevented (Web/src/renderer.ts onBeforeInput, Web/src/richEditor.ts). Native (iOS): SwiftUI's fields have no hook, .onKeyPress(.delete) hears hardware keyboards only, and the binding is not written when the text does not change. The software keyboard (and a hardware Backspace, which UIKit routes the same way) calls UIKeyInput.deleteBackward() on the UITextView or UITextField behind the SwiftUI editor; so an editor with deleteBackward carries a UIViewRepresentable background that, once in a window, finds the nearest text input beside it in UIKit's hierarchy and marks it with the handler, and deleteBackward() is swizzled once per class to run the handler for a marked input with an empty selection at offset 0 and UIKit's own otherwise (Views/Kinds/DeleteBackward.swift). Its limits: SwiftUI's fields staying UIKit-backed, the nearest text input being the editor's own, a private subclass that overrode deleteBackward() without calling super; macOS (NSTextView) is not covered, the key deletes as it does there.

Richer runs#

A TextRun (a rich text's, a rich texteditor's) gains background, a Color JSON object behind the run's glyphs (AttributedString's backgroundColor; a find highlight), beside the font it had, which the editors now honour in full: a run's size and design as well as its weight. @swiftbrowser/react's AttributedRun gains backgroundColor and font: { size?, weight?, design? } (bold is the weight bold when the font names none; a weight of semibold and up read back from the native editor is bold). The web rich editor paints the background on the run's span and the layout pass gives the span the font the engine measured the run in, size and design included; a rich text draws the background on its run templates too. Natively the editor's AttributedString takes a run's backgroundColor and, for a font with a size, Font.system(size:weight:design:) (a design without a size at the size the editor's font resolves to); the runs read back after the editor's own formatting keep every field the app sent (a background, a size, a design, a link) under the new weight, slant and lines. A rich Text run with a background is drawn from an AttributedString natively, as a link run is.

The keyboard toolbar#

toolbar's placement gains keyboard (ToolbarItemGroup(placement: .keyboard), the shim's .keyboard too, which used to arrive as bottom): the input accessory view, a bar above the keyboard while a text input of the screen is being edited, and nothing otherwise, drawn as Notes draws its format bar on iOS 26: a glass capsule 48 tall, inset 10 from the screen's sides and floating 10 above the keyboard. Natively, on iOS, it is a bottom safe-area inset of the screen's content shown while the keyboard is up (KeyboardBar.swift; SwiftUI's own .keyboard placement is the input accessory view, flush with the keyboard; macOS and the shim keep it). The web engine shows it while env.focusedField (the id of the text input being edited, the renderer's document.activeElement, read again on every focus change and after a pass moved the focus) is in the screen: the capsule (chrome keyboardBar, the screen's .sb-keyboard-bar, the bar's glass) 10 above the keyboard the page measured, or above the bottom safe area when it measured none (frame mode); the content stops above the capsule and a bottom toolbar is covered by it, as by the keyboard. The items of every keyboard toolbar of the screen are one HStack from the capsule's margin (16 in either side), a spacer child or a ToolbarSpacer of the placement flexible; each toolbar's frame is the capsule. Hidden toolbars are in hidden.

Alerts with text fields#

alert takes textfield children among its buttons (.alert { TextField("Name", text: $name); Button("Cancel", role: .cancel) { }; Button("Rename") { } }; @swiftbrowser/react's alert.actions takes a TextField beside the Buttons): the fields are drawn in the card between the message and the buttons, in their order, each a 36 tall row inset 16 from the card's sides as the buttons are, 8 apart, 16 below the message (chrome field<i>), a gray rounded field (--sb-color-tertiary-fill, 10 radius, the text 12 in); the buttons' rows and the button<i> chrome count the buttons alone. A dialog puts them after its caption, inset as it is. Edits send text as any field's; a bound focused focuses the field as the alert appears. Natively the fields pass through to SwiftUI's alert, which lays them out. The shim sends every view of the alert's actions as a child of the alert, so a TextField there is a textfield child with its binding, onSubmit and focus as anywhere; only the buttons dismiss.

Text measurement#

measureText(text, font, width) in @swiftbrowser/react answers synchronously, without an element: { width, height, lines }, the size a Text of the text in the font (a text style name or system(size, weight, design)) takes wrapped to width points (one line when omitted). No op: on the web mount installs the renderer's own typography (wrapText and the line heights its layout engine lays text out with, at the current Dynamic Type size); natively run installs the host's measureText(text, fontJSON, width), a synchronous __sbNative function returning NSAttributedString's bounding rect with the platform font (a text style's preferred font, or a size with a weight and design; lines is the height in the font's line heights; HostBridge.swift, TextMeasureBridge.swift). It throws before an app is mounted or run (canMeasureText() says). An editor under scrollDisabled draws its lines a step apart that differs from a Text's first line by renderer (the web's a leading each, UIKit's a line height each): an app sizing editors measures the step from a one-line and a two-line probe, as Pages does.

Pages merges a paragraph into the one before it on Backspace at its start (mergeIntoPrevious: the runs joined, the caret at the join through the selection binding; a list item steps out first), so the stand-in that dropped empty paragraphs when the writing moved on is gone; find highlights the matches behind the text of the live editors (backgroundColor, the current one orange) instead of swapping each editor for a static text; the format bar is a keyboard toolbar; rename is an alert with a field (in the document and the document manager); and the pages break where measureText says the blocks end (blockMeasurer), in the document's font.

Scroll geometry, pinned views and animation completion#

What a spreadsheet needs of a scroll view: to read where it is, to put it somewhere, to keep headers over it, and to know when an animation is over (Numbers' table in the Showcase, Native/Examples/Showcase/src/numbers/Table.tsx, had been a hand-rolled pan with its own inertia for want of them).

Scroll geometry. .onScrollGeometryChange(for:of:action:) (iOS 18) puts "reportsGeometry": true on the scrollview. The page sends it {"type": "scrollgeometry", "id": n, "offset": {x, y}, "contentSize": {width, height}, "containerSize": {width, height}, "contentInsets": {top, leading, bottom, trailing}} (points, 2 decimals): after every layout pass, from the pass's frames and the element's offsets, and, while anything scrolls, once per animation frame (Web/src/scrollGeometry.ts), only when a field changed since the last report, so a pass that moved nothing says nothing. offset is the visible area's origin in the content; contentInsets is the space the view scrolls into past its content (a bar covering its bottom; zeros otherwise on the web, SwiftUI's own natively). The for: transform runs app-side: @swiftbrowser/react calls action only when of(geometry) answers differently, so an app watching the content size is not rendered per frame of a scroll; an app that watches the offset is, as a drag gesture's handler is, and that is the point (the overlays that follow a scroll). The shim does the same (Sources/SwiftUI/API/ScrollGeometry.swift): the first report runs the action with the old value equal to the new, the scroll view the modifier is on takes the report (one nested inside it does not), and a scrollview that is also refreshable hears both events through one handler. ScrollGeometry.bounds is the offset and the container size; visibleRect leaves the insets out. SwiftBrowser Native hands SwiftUI's onScrollGeometryChange record on (iOS 18), in the action itself, so the pass the app answers with lands in the update the scroll is drawn in, as a @State set there would: what the pass moves by the offset (Numbers' frozen headers) moves in the frame of the scroll, as on the page, which sends the geometry in the animation frame of the scroll, before it paints.

Offsets by point. ScrollPosition.scrollTo(x:y:), a .scrollPosition bound to a point (ScrollPosition(point:)): the scrollview carries "scrollOffset": {"x": 0, "y": 480, "serial": n} (an axis left out keeps its offset; the serial increases with every request, across all scroll views). After laying out the pass that brings a new serial the page scrolls the view there, smoothly when the commit is animated, and carries each serial out once (a pass that re-sends the same command leaves a viewer who scrolled away where they are). A view laid out in no room along an axis the command names keeps it for the first pass that gives it some, as a scrollTo to a target waits. The view reports its position afresh when it next settles, as after a scrollTo to a target. In @swiftbrowser/react a scrollPosition binding takes a point as well as an id, and proxy.scrollTo({ x, y }) reaches the scroll views inside the reader; the binding reads back as ids only (the target at the anchor), never as a point: the offset is onScrollGeometryChange's to read. The shim's ScrollPosition (Sources/SwiftUI/API/ScrollPosition.swift) does the same through .scrollPosition(_:anchor:): an id request goes through the reader as .scrollPosition(id:anchor:)'s does (the request's anchor, else the modifier's), a point or an edge is the scrollOffset of the scroll view the modifier is on (not of one nested inside it; scrollTo(x:) leaves y out; an edge is 0, or an offset far past the content for .bottom and .trailing, which the browser clamps to the end), every scrollTo takes the next serial of the readers' counter, and the page's scrollposition sets the binding to that id with isPositionedByUser. Natively (iOS 18) the view is positioned by a ScrollPosition of its own while it has an offset command, and then does not report ids: SwiftUI takes one position per scroll view.

Pinned views. LazyVStack(pinnedViews: [.sectionHeaders]) (and LazyHStack, LazyVGrid, LazyHGrid, .sectionFooters too) puts "pinned": ["sectionHeaders"] on the stack or grid. Each section child's sectionheader stays at the leading edge of the visible area (below a bar the view scrolls under) while its section passes, and the next section's header pushes it out; a footer stays at the trailing edge while its section is in view the same way. The page moves them by a transform along the axis after every layout and on every scroll event (Web/src/pinnedViews.ts), from the laid-out positions, so the move never feeds back; they are drawn over their section's rows and take the background the app gave them (transparent otherwise, as in SwiftUI). @swiftbrowser/react turns a string Section header into a header view inside a pinned stack, since outside a list the text would not draw; the shim does the same (a Section("Title") in a stack pinning headers emits header: null and a sectionheader holding the Text, and a string footer likewise under .sectionFooters). Natively the stack is a LazyVStack(pinnedViews:) whose sections are Sections already.

Animation completion. withAnimation(_:completionCriteria:_:completion:) (iOS 17) stamps the pass's commit with "completion": n (a serial) and, for .removed, "completionCriteria": "removed". Once the animations the commit started have ended the page sends {"type": "animationcomplete", "serial": n}, an event addressed to no element; at once, after the pass, when nothing animated. The web renderer lists the animations running under the root before and after the Animator's commit and waits for the new ones' finished (one that never ends, repeatForever, counts after one run of its duration, as .logicallyComplete does); the animated scroll of a scrollTo is not waited for. SwiftBrowser Native applies the pass inside withAnimation(_:completionCriteria:_:completion:) and sends the event from the completion, a turn later (OpTree.animateWithCompletion; a tree without the hook answers right after the pass). @swiftbrowser/react's withAnimation(animation, body, completion) runs the completion at once when the body rendered nothing. The shim's withAnimation(_:completionCriteria:_:completion:) keeps the completions under the serial and runs them when the event arrives: one serial per pass (calls whose changes one pass draws share it, and the commit says removed only when all of them asked for it), and a call whose body changed nothing runs its completion after the event or job that made it, with no pass. Headless: animationcomplete:3.

onGeometryChange. .onGeometryChange(for:of:action:) (iOS 18) wraps the view in a zstack with reportsSize (and reportsFrame once the transform reads the frame, the scroll view's bounds or the insets), as visualEffect does; nothing new on the wire. The action runs after the render that heard a change of the transform's answer, so it may set state, which is what the Showcase's SizeReport child and useEffect did by hand. A tapgesture gains its location from @swiftbrowser/react's onTapGesture={{ perform(location) }}.

Numbers. The Showcase's table is a ScrollView(.both) holding the body of the table, so panning, flicking and bouncing are the scroll view's own (iOS's natively; the browser's on the web, which Playwright's touch events fling with inertia), with the letters, numbers, header row and header column laid over it, out of the way of touches, and moved by the offset onScrollGeometryChange reports; a tap on a frozen cell reaches the body under its pane, which finds the cell from where the tap landed. Each sheet's offset is kept and set back through the point-valued scrollPosition when the sheet is shown again. What stayed one drag: the letters bar and the numbers bar (a tap selects, a drag along them extends, a drag from a letter's edge resizes), because a drag there has no scroll to compete with; the selection's handle and the picked reference's handle, drags of their own inside the scroll view (minimumDistance: 0 takes the touch before the scroll view does). What went: the pan, the fling with withAnimation and timeouts, the four clipped panes for the body, and hit-testing the whole view in one gesture.

Recording from the microphone, and cutting a recording#

useAudioRecorder() in @swiftbrowser/react (packages/react/src/audioRecorder.ts) records as AVAudioRecorder does: record, pause, resume, stop (resolving with { url, duration, type }), cancel, discard(url) and trim(url, keep), with status, time, the input's levels and error. No op carries it: the hook is JavaScript on both sides and talks to one more field of the web renderer's host request environment (Web/src/hostRequests.ts), audioRecorder, an AudioRecorderHost (Web/src/audioRecorder.ts) with those same calls plus meter(), which the hook polls while recording.

Web (Web/src/audioRecorder.ts). getUserMedia and MediaRecorder record (AAC in MP4 where the browser encodes it, else Opus), an AnalyserNode meters the input (0 at -50 dB, 1 at 0 dB), and stop writes the sound into the app's Documents/Recordings through the files host ("The app's files from JavaScript": the app's IndexedDB home), named by a UUID and the type's extension (.m4a, .webm, .ogg), and answers its file: URL, which a media element plays (the renderer loads a file: URL through the files host) and discard deletes (one gone already is nothing to delete; a data: URL is nothing to delete). Where the page keeps no files, or the write is refused, the sound is a data: URL instead, which goes with its string. trim(url, keep) cuts with the Web Audio API, since MediaRecorder cannot encode what is not playing: the file is read (or a data: URL fetched) and decoded (decodeAudioData on an OfflineAudioContext, or an AudioContext closed once it has decoded), the frames of each kept range are copied in order (keptRanges, sliceSamples: clamped to the recording, sorted, overlaps merged), and the result is written as 16-bit PCM WAV (encodeWAV, the source's channel count) to a new .wav file in Recordings (a data:audio/wav;base64,… URL where the page keeps no files), with type: "audio/wav" and the new duration. Without Web Audio it rejects unsupported: this page cannot cut audio; nothing kept rejects empty: …; a URL that does not decode rejects decode: ….

Native (packages/native/src/hostRequests.ts, Host/AudioRecorderBridge.swift). The hook's calls become audioRecord host requests from the app to the bridge, one recording at a time, kept as AAC in Documents/Recordings:

action params answer
start none {}; asks for the microphone the first time (NSMicrophoneUsageDescription), else fails permission: …; busy: … while one records
pause, resume, cancel none {} (cancel deletes the file)
meter none { level, time }: averagePower(forChannel:) on the page's scale, and the seconds recorded (held while paused)
stop none { url, duration, type: "audio/mp4" }: the file's URL in Recordings
discard url {}: deletes that file; unsupported: … for a file outside Recordings
trim url, keep: [{ start, end }] (seconds) { url, duration, type: "audio/mp4" }: a new file in Recordings (a new UUID name) of the kept parts in order, through an AVMutableComposition (insertTimeRange(_:of:at:) per part, each clamped to the asset) exported with AVAssetExportSession and AVAssetExportPresetAppleM4A; the original stays, for the app to discard. unsupported: … for a file outside Recordings or one that is not there; empty: … when nothing falls in keep; export: … when the export fails
{ "kind": "audioRecord", "params": { "action": "trim",
  "url": "file:///…/Documents/Recordings/3F2A….m4a",
  "keep": [{ "start": 0, "end": 4.5 }, { "start": 9, "end": 12.25 }] } }
→ { "url": "file:///…/Documents/Recordings/8B1C….m4a", "duration": 7.75, "type": "audio/mp4" }

keep is read the same way on both sides (AudioTrim.ranges natively, keptRanges on the page): a range starting before 0 starts at 0, one past the end ends at the end, an empty or reversed one is dropped, they go in time order and overlapping ones merge, so [{ start, end }] trims to that stretch and two parts around a stretch delete it. iOS moves an app's container when it is installed again, so a file URL under an old Documents is read at the same path under today's (AppFiles.current). Against the shim (the round trip) the audioRecord request answers unsupported, and a page without a microphone API has no audioRecorder field, so the hook's available is false and its calls fail unsupported: ….

A video recorder#

useVideoRecorder() and CameraPreview in @swiftbrowser/react (packages/react/src/videoRecorder.tsx) talk to the host request environment's videoRecorder, a VideoRecorderHost (Web/src/videoRecorder.ts): open({ facing }) answers { stream, facing }, the id a video element's stream prop shows live; start, pause, resume, cancel, close; stop answers { url, duration, type, width, height }; time() the seconds recorded; discard(url) lets a recording go.

Web. getUserMedia keeps the stream by its id and MediaRecorder records it (MP4 where the browser can, else WebM) into a blob: URL.

Native (VideoRecorderBridge.swift, iOS). The calls become videoRecord host requests (action: open with facing, close, start, pause, resume, stop, cancel, time answering { time }, discard with url): an AVCaptureSession with the camera asked for and the microphone, recording with an AVCaptureMovieFileOutput into a QuickTime file in Documents/Recordings, written upright as the phone is held when recording starts (an AVCaptureDevice.RotationCoordinator's horizon-level capture angle: held sideways, a landscape movie). Opening again turns to the other camera under the same stream id, which the video element draws with an AVCaptureVideoPreviewLayer kept upright by the coordinator's preview angle. The app's Info.plist must name NSCameraUsageDescription and NSMicrophoneUsageDescription (without them open answers permission: … rather than iOS ending the app); pause and resume need iOS 18 (unsupported: … before).

Video assets#

AVURLAsset, AVAssetImageGenerator, AVMutableComposition and AVAssetExportSession in @swiftbrowser/react (packages/react/src/avAsset.ts), with CMTime and CMTimeRange, read and write video as AVFoundation's do. No op carries them: they talk to the host request environment's avAsset, an AVAssetHost (Web/src/avAsset.ts). A composition is kept in the app as its parts ({ url, start, end } in seconds, in order); only an export sends them.

call answer
load(url) { duration, tracks: [{ trackID, mediaType (video, audio), naturalSize (upright), nominalFrameRate, timeRange: { start, duration }, codec }], naturalSize }
image(url, time, { maxWidth, maxHeight }) { url, actualTime, width, height }: a JPEG still of the frame at time (or the last before it), fitted in the box, never up
export(id, { segments, preset, fileType (mp4, mov, webm), outputURL? }) { url, duration, type }: the parts in order as one file, written to outputURL (a file of the app's) or a new URL; empty: …, unsupported: …, cancelled: …
progress(id) 0 … 1 while that export runs
cancel(id) stops it; its export rejects cancelled: …
release(url) lets go of a still or an export the host made

AVAssetExportPresetPassthrough copies the media (each part's cut lands on a key frame); every other preset re-encodes, cutting exactly, the video fitted to the preset's frame (a portrait video to a portrait one): HighestQuality keeps its size, MediumQuality fits 1280 × 720, LowQuality 640 × 360, 640x480 … 3840x2160 theirs.

Web (Web/src/avAsset.ts). mediabunny over WebCodecs, imported the first time an asset is used: a part per Conversion (trimmed; copied or transcoded), several joined by copying their packets in turn, so parts copied from sources in different codecs cannot be joined (unsupported: …; a re-encoding preset makes them alike). file: URLs are read and written through the page's files host; anything else is fetched. A page without WebCodecs has no avAsset.

Native (AVAssetBridge.swift, iOS). The calls become avAsset host requests (action: load, image, export, progress, cancel, release, with the call's arguments as params) answered by AVURLAsset, AVAssetImageGenerator (upright, exact times), and an AVMutableComposition exported by AVAssetExportSession with the preset into MP4 or MOV (WebM answers unsupported). Stills and exports without an outputURL are files in Caches/AVAssets, which release deletes. The native bundle aliases mediabunny to a stub, so none of it is bundled.

An audio engine#

AVAudioEngine in @swiftbrowser/react (packages/react/src/audioEngine.ts) is AVFoundation's engine for a JavaScript app: AVAudioEngine with mainMixerNode, outputNode and inputNode; AVAudioPlayerNode, AVAudioUnitSampler and AVAudioMixerNode; AVAudioUnitReverb, AVAudioUnitDelay, AVAudioUnitDistortion, AVAudioUnitEQ (with its bands) and AVAudioUnitTimePitch; AVAudioFile, AVAudioPCMBuffer and AVAudioTime; and useAudioEngine(build), an engine for a view's life. No op carries it: like the recorder it talks to one more field of the host request environment, audioEngine, an AudioEngineHost (Web/src/audioEngine.ts) with one call, perform(command). The app names every engine, node, file and buffer by a number from one counter, and each call is one command, in the order made; a call that answers nothing (a property, a note) reports a failure to the engine's onError.

action params answer
create engine, mixer, output, input {}: an engine and its own three nodes
destroy engine {}: stopped and let go (dispose(), or the engine's object collected)
attach engine, node, kind (player, sampler, mixer, reverb, delay, distortion, eq, timePitch), values (its properties so far, preset among them), bands (an EQ's) {}; exists: … for a number attached already
detach engine, node {}
connect engine, from, to (numbers: a fan-out) {}: from's output goes there instead of where it went; a destination that is not a mixer takes one input, so what fed it is let go. unsupported: … into a player, a sampler or the input, out of the output, or into itself
disconnectOutput, disconnectInput engine, node {}
prepare, start, pause, stop, reset engine {}; start with the input connected asks for the microphone (permission: …); pause holds the players where they are and start plays them on; stop and reset stop them, dropping what they had scheduled
set node, values {}: volume and pan (players, samplers, mixers, the input), outputVolume, overallGain (dB), globalTuning (cents), stereoPan (-100 … 100), wetDryMix, delayTime, feedback, lowPassCutoff, preGain, globalGain, bands.<i>.filterType, .frequency, .bandwidth, .gain, .bypass, pitch, rate, overlap, bypass
preset node, preset {}: an AVAudioUnitReverbPreset or AVAudioUnitDistortionPreset by name
openFile file, url (file:, https:, data:) { length, sampleRate, channelCount }; notFound: …, decode: …
readFile file, buffer, start, frames { frameLength, sampleRate, channelCount }
writeBuffer buffer, sampleRate, channels (the samples, a Float32Array per channel; across the native bridge a typed array beside the command, or base64 of float32 little-endian to a host without hostRequestBytes) {}
release id {}: a file or buffer let go
scheduleFile node, file, start, frames (a segment), at {} once it has played (or the player stopped)
scheduleBuffer node, buffer, at, loops, interrupts, interruptsAtLoop {} once it has played (a loop: once it stopped or was replaced)
play node, at {}; notConnected: … for a player connected to nothing, stopped: … while its engine is not running
pausePlayer, stopPlayer node {}
playerTime node { sampleTime, sampleRate } on the player's timeline, or null before it plays
loadZones node, zones ([{ file, root, low, high }]), attack, release {}
loadInstrument node, url, program, bankMSB, bankLSB {} natively; unsupported: … on a page
startNote, stopNote node, note, velocity, channel {}
controller node, controller, value, channel {}
pitchBend node, value (0 … 16383), channel {}
meter node { level }: the output's RMS, 0 at -50 dB, 1 at 0 dB
{ "kind": "audioEngine", "params": { "action": "scheduleBuffer", "node": 7,
  "buffer": 12, "at": { "sampleTime": 96000, "sampleRate": 48000 }, "loops": true } }
→ {}   (once the player stops or another buffer takes over)

at is { sampleTime, sampleRate }, a place on the player's own timeline (frames from when it first played), or { delay }, seconds from when the command arrives. A player's items play one after another, each from where the last ends unless it has a time; interrupts drops what is scheduled and plays at once, or, with a time to come, lets what sounds play on until that time and takes over there (to the sample); interruptsAtLoop lets a looping buffer finish the pass it is in and plays from there, so a sequencer swaps its bar on the bar line; another interruptsAtLoop before that bar line takes the waiting one's place there, its answer given as a replaced loop's is, as AVAudioPlayerNode drops what is scheduled and keeps what sounds (two posted in the same instant it can queue instead, the waiting one playing a pass first: a sequencer posts one swap at a time).

A sampler's zones are the app's: loadAudioFiles(urls, { rootNotes, attack, release }) opens each file and places it at its root note (from rootNotes, else the note its name names: Piano C4.wav, F#2, Bb3, 60, C4 being middle C, MIDI 60; else 60), each zone covering the keys from halfway after the root below to halfway to the root above (samplerZones), a note playing its zone's sample pitched by the semitones from the root.

Swift apps (Sources/AVFoundation/AudioEngine.swift). The shim's AVFoundation has the same engine for a Swift app compiled to WebAssembly: AVAudioEngine (mainMixerNode, outputNode, attach, detach, connect(_:to:format:) and its bus and fan-out forms, disconnectNodeInput / Output, prepare, start, pause, stop, reset, isRunning), AVAudioPlayerNode (scheduleFile, scheduleSegment, scheduleBuffer with AVAudioPlayerNodeBufferOptions and an AVAudioTime, each with its completion handler, its callback-type form and async form; play, play(at:), pause, stop, isPlaying, volume, pan, playerTime(forNodeTime:) worked out on Swift's clock), AVAudioMixerNode (volume, pan, outputVolume), AVAudioUnitReverb, AVAudioUnitDelay, AVAudioUnitDistortion (factory presets by name), AVAudioUnitEQ with its bands, AVAudioUnitTimePitch, AVAudioFile (init(forReading:); a file that is not there throws), AVAudioPCMBuffer (floatChannelData, frameLength), AVAudioFormat and AVAudioTime (host time is nanoseconds on the engine's clock: AVAudioTime._now stands for mach_absolute_time()). Each call is an audioEngine host request (Phase 13's channel) carrying one command of the table above, sent in the order made; the page performs it as it arrives (hostRequests.ts), and a writeBuffer's channels cross as the float32 bytes of each channel (beside the JSON, or base64). A file is opened at the URL the page loads it from (a bundle resource where the page serves it, another file as a blob); a WAV file's header is read in Swift, so length and processingFormat are known at once, and read(into:) decodes it in Swift; another format's length comes with openFile's answer (0 until then) and read(into:) reads on the page (readFile), its samples staying there. A buffer's samples are sent (writeBuffer) each time it is scheduled. Completion handlers run on the main actor once the page answers. Not covered from Swift: taps (installTap is kept and never called), the input node's microphone, the sampler, manual rendering, writing files, and the exceptions iOS raises (a call the page fails, a player played before its engine started, fails quietly). The page starts its context only in a tap: an engine started before the viewer's first tap plays from that tap on (what it had scheduled then plays at once), and from timers after it.

Web (Web/src/audioEngine.ts). One AudioContext for the page, made with the first engine and resumed by start (a page may only start sound in a tap). A node is a few Web Audio nodes: a player's and a sampler's sources into a gain and a stereo panner (volume, pan; a mono source centered is -3 dB a side, equal power); a mixer a summing gain; an effect a dry path and a wet one through the effect, crossfaded by wetDryMix. The player keeps its timeline itself (each item an AudioBufferSourceNode started where the timeline puts it, part-way through after a pause). The sampler's voices are buffer sources at 2^((note - root)/12) with a linear attack and release, velocity squared as gain, the sustain pedal (64), volume (7), expression (11), pan (10), all notes off (120, 123) and a ±2 semitone bend. The reverb is a ConvolverNode on a decaying noise tail for each factory preset (seeded, so it is the same each time), the delay a DelayNode fed back through a lowpass, the distortion a WaveShaperNode curve per preset after preGain, the EQ a chain of BiquadFilterNodes (the bands each bypassed until the app turns them on, as Apple's are). Web Audio cannot shift pitch apart from speed, so AVAudioUnitTimePitch passes its input through, and a page has no sound banks (loadInstrument answers unsupported). Files are read through the files host (file:) or fetched, and decoded with decodeAudioData.

Native (packages/native/src/hostRequests.ts, Host/AudioEngineBridge.swift). Each command is an audioEngine host request the bridge performs as it arrives, not on a later turn of the main actor, so commands keep their order and a note sounds at once; what finishes later (start asking for the microphone, a download, a scheduled buffer playing) answers later. AVAudioEngine raises Objective-C exceptions that end the app where a page shrugs, so the bridge checks first: a player plays and schedules only connected (notConnected) and plays only while its engine runs (stopped); players connect in stereo at the output's rate and a buffer in another format is converted to it (a mono buffer into both channels); a file in the player's format streams (scheduleSegment), another is read and converted; the input connects only with a format it has. On iOS start sets the session to .playback (sound with the ringer switch off), or .playAndRecord with the microphone; a configuration change (headphones in or out) starts the engine again. A sampler's loadZones loads the files with loadAudioFiles(at:), so the instrument is the sampler's own default (velocity, the pedal, the bend), then rewrites each zone's root key, min key and max key and the envelope's attack and release stages in the unit's fullState, the dictionary an .aupreset holds. meter taps the node the first time it is asked. Against the shim (the round trip) the page answers.

Kinds a package adds. attach takes a kind neither host has when an optional package registered it: on a page with registerAudioNodeKind(kind, make) (Web/src/audioEngine.ts; make(context) answers a CustomAudioNode, its Web Audio input and output, set(key, value) and note(command)), natively with AudioEngineNodes.register(kind) { context in … } (Host/AudioEngineNodes.swift; an AudioEngineCustomNode, its AVAudioNode, set and note, made with the format to render in). The host makes the node, gives it the attach values and every set (volume and pan go to the host's own mixing first), routes startNote, stopNote, controller and pitchBend to it, and halts it on stop, reset and detach; a node whose attach values fail is not left attached. A kind nobody registered fails unsupported: no node kind ….

Programs. @swiftbrowser/dsp registers program (natively SwiftBrowserDSP's SwiftBrowserDSP.install()): a compiled DSP program (packages/dsp/README.md) as a polyphonic source, DSPNode in JavaScript. Its values are program (the program's JSON, checked by the host before it runs: every register, operand and instance in range) and param.<name> (a parameter, clamped to its range and glided to over about 20 ms; one the program does not have is kept for a later program that does), beside volume and pan; it takes notes as a sampler does (velocity 0 a note off, controller 64 the pedal, 120 all sound off, 123 all notes off, a ±2 semitone bend). Events apply at the machine's next 128-frame block.

{ "kind": "audioEngine", "params": { "action": "attach", "engine": 1, "node": 7,
  "kind": "program", "values": { "program": "{\"format\":\"swiftbrowser-dsp\",…}", "param.cutoff": 2400 } } }
→ {}

On a page the program runs in an AudioWorklet (packages/dsp/src/worklet.ts): the engine as a WebAssembly module (the machine a native app plays), its worklet script made from the wrapper's own source text, the program, parameters and notes posted to it (what is sent while the script loads goes in the processor's options, so it applies before the first quantum). Natively an AVAudioSourceNode runs the Swift machine (Native/Packages/SwiftBrowserDSP), handed the program and the events through a lock the audio thread only ever tries; a program replaced is released on the main thread, not the audio thread. The two machines are one algorithm and render the same samples to within a few millionths (the package's parity fixtures).

The on-device language model#

LanguageModelSession in @swiftbrowser/react (packages/react/src/languageModel.ts) is Foundation Models for a JavaScript app: Apple Intelligence's on-device model, shaped as the framework is. SystemLanguageModel.default.availability() (or useSystemLanguageModel(), which asks again every few seconds while the model is not ready) says whether it can answer; a session made with instructions keeps its conversation, so each prompt follows the ones before; respond(to:) resolves with the whole response and streamResponse(to:) is an async iterable of snapshots, { content }, the response so far, which cancel() (or leaving the loop) stops. One request at a time per session. Failures are GenerationErrors whose kind names LanguageModelSession.GenerationError's case. Guided generation and tools are not here.

Every call is a host request of kind languageModel, answered natively by FoundationModels (Host/LanguageModelBridge.swift, iOS 26 and macOS 26) where Apple Intelligence can answer, else by the model the app installed as LanguageModels.fallback (Host/LanguageModelProvider.swift; see below), else as unavailable for the system's reason (deviceNotEligible before iOS 26); and on a page by Chrome's Prompt API (LanguageModel, Web/src/languageModel.ts) where the browser has it, else as a device without Apple Intelligence:

action params native page value
availability SystemLanguageModel.default.availability, else the fallback's, with its download where it fetches its model LanguageModel.availability(): available and downloadable (the first prompt downloads it, within its tap) are available, downloading is modelNotReady, unavailable and no API deviceNotEligible { "status": "available" } or { "status": "unavailable", "reason": "deviceNotEligible" | "appleIntelligenceNotEnabled" | "modelNotReady" }, either with "download": { "size"?, "downloaded", "progress"?, "failure"? } for a model the app fetches
download the fallback's startDownload() nothing (the browser fetches its own) {}
deleteDownload the fallback's deleteDownload(): a download under way stops, the model leaves the device nothing {}
select id the choice of models that answers from the next session on, remembered across launches nothing {}
toolCall session the model's next call of one of the session's tools, once it makes one { "closed": true } (no tools on a page) { "call": n, "name", "arguments" }, or { "closed": true } once the session is closed
toolResult session, call, output or error the model reads it and goes on nothing {}
open session, instructions?, tools? LanguageModelSession(tools:instructions:), each tool a Tool whose arguments' GenerationSchema is built from its JSON schema with DynamicGenerationSchema its instructions kept for LanguageModel.create({ initialPrompts }) on first use {}
prewarm session prewarm() create ahead of the first prompt {}
respond session, prompt, options? respond(to:options:) prompt(text) { "content": string }
stream session, stream, prompt, options? streamResponse(to:options:), iterated in a task promptStreaming(text), its chunks added up {}
next stream answered once the response has grown or ended the same { "content": string, "done": bool }, the latest snapshot
cancel stream cancels the task aborts the prompt {}
close session lets the session go destroy() {}

Natively, availability also lists models when there is a choice to make: Apple Intelligence where it answers (id system), then the fallback's choices, each { id, name, summary?, selected, download? }. The default is Apple Intelligence where it answers, else the fallback's first model.

A session's tools are { name, description, parameters }, the arguments a JSON schema (an object of properties: strings, string enums, numbers, integers, booleans, arrays). The app's LanguageModelSession runs them: it asks toolCall again and again while the session is open, runs each call's call(arguments) and answers with toolResult, which the model reads before it goes on. A tool that throws answers error, which fails the response on Apple Intelligence and is handed to a local model as the tool's output.

session and stream are numbers the app chooses. A stream is read by asking next again as each answer arrives: the host keeps the response so far and answers with it once it has changed, so no event channel is needed and a reader slower than the model skips snapshots rather than queueing them; the answer that says done is the last, and the stream is gone after it. options are GenerationOptions: temperature, maximumResponseTokens, sampling: "greedy"; Chrome takes its sampling per session and leaves them at its defaults. A failure rejects with a tagged message: unavailable: … (assetsUnavailable), context: … (exceededContextWindowSize), guardrail: …, language: … (unsupportedLanguageOrLocale), concurrent: … (a session asked while it responds), rateLimited: …, refusal: …; Chrome's QuotaExceededError is context, NotSupportedError language and NotAllowedError unavailable.

An app's own model. A native app can bring a model for where Apple Intelligence cannot answer: an iPhone before the 15 Pro, Apple Intelligence turned off, a system before iOS 26. LanguageModels.fallback takes a LanguageModelProvider (its availability, and sessions whose streamResponse yields the response so far and whose failures are LanguageModelErrors of a kind); the bridge asks it whenever the system model is unavailable for a reason other than still downloading its own model, and a session opens on whichever model answered available. SwiftBrowserLocalModel (Native/Packages/SwiftBrowserLocalModel) is such a provider: open GGUF models run with llama.cpp (several to choose from, the choice remembered), each fetched when the app asks (SystemLanguageModel.default.download(), after showing the viewer its size; until then modelNotReady with download.downloaded false, then the download's progress), kept in Application Support out of backups, removed with deleteDownload(), loaded once, its sessions keeping their conversations in one context that decodes only what a prompt adds. Tools are offered in its instructions: the model calls one by answering with just {"tool": name, "arguments": {...}}, which the session runs, hands back (as Llama 3's ipython turn, or a tool turn) and lets the model go on, a few rounds at most; a reply that starts as such an object is held back until it is clear whether it is a call. It is a package of its own, so an app that does not add it neither fetches, builds nor links llama.cpp. @swiftbrowser/native ships it beside the core (swift/Packages/SwiftBrowserLocalModel), and swiftbrowser native add local-model (or native init --with local-model) links it into an app's Xcode project:

import SwiftBrowserLocalModel
LocalLanguageModel.install([.llama3_2_1B, .qwen2_5_1_5B, .llama3_2_3B])   // at launch

The app's files from JavaScript#

fileManager in @swiftbrowser/react (packages/react/src/fileManager.ts) is FileManager.default with URL.documentsDirectory and its siblings: documentsDirectory, applicationSupportDirectory, cachesDirectory, temporaryDirectory, url(directory, path), contents, text, write, contentsOfDirectory, createDirectory, fileExists, attributesOfItem, moveItem, copyItem, removeItem and loadURL, every path a file: URL and every call asynchronous. No op carries it: like the recorder it talks to one more field of the host request environment, files, a FilesHost (Web/src/files.ts) with directories, read, write, remove, createDirectory, list, attributes, move, copy and loadURL. Failures are kind: detail: unsupported (a URL outside the app's directories, no host), notFound (nothing there, or no directory for a write or a destination), exists (a destination, or a file where a directory is made), isDirectory, notDirectory.

Web (Web/src/files.ts). The host is the home of "Phase 19": /data with Documents, Library/Application Support and Library/Caches in the app's IndexedDB database (sb-files:<App>, the entries store, a row per file or directory, now with a modified time the module's rows lack), and /tmp in memory for the session. A React app names its database with mount's app option (app by default), so a React app and a Swift app of one name share a home. loadURL answers an object URL of the file's bytes, typed by the file's extension, one per file and revoked when the file is written again or removed (a data: URL where the page has no object URLs). The renderer calls it for a file: URL in a video or image element (loadableURL, Web/src/hostRequests.ts): the element's source is set once the object URL is made, and a video asked to play then plays; a file that cannot be loaded leaves the file: URL in the element, which fails and says so.

Native (packages/native/src/hostRequests.ts, Host/FilesBridge.swift). The bridge's appDirectories() answers the standard directories as file: URLs (made where they are not yet), and the calls become files host requests, bytes crossing as base64, on Foundation's FileManager in the app's sandbox; a URL outside Documents, Library or tmp fails unsupported: …, and one under an old container is read under today's (AppFiles.current). loadURL is the URL itself: AVPlayer and UIImage read the file.

action params answer
read url { data } (base64)
write url, data (base64) {}; the file's directory must exist
remove url {}; a directory goes with all it holds; the standard directories themselves cannot
createDirectory url {}; with the directories above it
list url { urls }, by name
attributes url { size, modified, directory } (modified in milliseconds, or null), or null when nothing is there
move, copy from, to {}; to must be free, in a directory that exists, and not inside from
{ "kind": "files", "params": { "action": "write",
  "url": "file:///…/Documents/Recordings/3F2A….m4a", "data": "AAAA…" } }
→ {}

Against the shim (the round trip) the files request answers unsupported, the bridge has no appDirectories, and a page without IndexedDB and without a document has no files field, so fileManager's available is false and its calls fail unsupported: ….

Bar visibility#

.toolbar(.hidden, for: .navigationBar) (.toolbarVisibility on iOS 18, .navigationBarHidden(true) before iOS 16), .toolbar(.hidden, for: .bottomBar) and .statusBarHidden() are three booleans on the screen they apply to (a navscreen's props; absent means shown, .visible sets one false again and .automatic says nothing): navigationBarHidden, bottomBarHidden, statusBarHidden. The Swift runtime writes them as it writes the title, from wherever in the screen's content the modifier sits; React's toolbarVisibility={{ navigationBar: 'hidden' }} and statusBarHidden are preferences of the screen the same way. The tab bar has no prop yet.

  • navigationBarHidden: the screen has no bar: no bar, barRow, title, back, more or glass chrome, no large title (whatever displayMode says), and the toolbars of the bar's placements (leading, trailing, principal, secondary, largeTitle) are hidden, their items too. The content starts under the status bar, which stays a safe area (content.y is the status bar height); a root list or scroll view runs under the status bar alone (its topInset is that tall), and content that ignores the safe area reaches the top of the screen. A pushed screen keeps its swipe-back edge. The page keeps the bar element where it was and fades it with a 0.25s stylesheet transition (data-sb-bar-hidden on the screen), its title still in it, so a tap that hides the bars in withAnimation plays as iOS does; the capsules play their exit and the items leave with the layout. Natively the stack's navigation bar is hidden for the screen (.toolbar(.hidden, for: .navigationBar), animated in an animated commit).
  • bottomBarHidden: the bottom toolbars are hidden and there is no bottomBar / bottomGlass… chrome; the content runs to the bottom as it does without a bottom bar. A keyboard toolbar is the content's and stays. Natively .toolbar(.hidden, for: .bottomBar).
  • statusBarHidden: natively .statusBarHidden(true) for the screen. The page cannot hide the browser's status bar: in frame mode the drawn status bar fades (data-sb-status-hidden on html while a screen that shows asks for it), in device mode nothing changes; the safe area is unchanged either way, as it is under a notch.

The Showcase's Files clone shows a photo this way: a pushed screen with the file's name, the back button and a "⋯" menu in the bar, Get Info and Share in a bottom bar, the picture on black under them; a tap hides the bars and the status bar and the next tap shows them again, as the real Files app's Quick Look does.

A tree drawn by another root#

A producer need not be the renderer's own: @swiftbrowser/react's RemoteTree draws, inside a host tree, the ops another SwiftUI root emits (in a sandbox, a worker, another runtime). The child root is made with createSwiftUIRoot(sink, { remote: true }): its ops are the usual ones, with two differences for a tree no renderer sees directly. A preference whose screen the child has not got (navigationTitle under no navstack) is merged into the root's props instead of being dropped, and the root's props are sent whole as update of element 0 whenever they change (a renderer takes only colorScheme there; the host lifts title, displayMode, toolbarRole and the bar visibilities to the screen the tree sits in, and colorScheme to its own root). What the child hoists to its root for lack of a screen (toolbar, searchfield) joins the host's screen; its sheet and alert elements are presented over the host's root.

The host mirrors the child's elements as elements of its own (new ids), and forwards every event the renderer addresses to one of them to the child under the child's id; animationcomplete is answered for the child's completion serial when the host's pass, stamped with the child's animation, has finished animating (at once when the host drew nothing for it).

The child's first navstack (outside its sheets) is not mirrored as one when the host tree has a stack around RemoteTree: its depth-0 navscreen's children are drawn in place and its props lifted to the host's screen, and each deeper navscreen becomes a screen of the host's stack (a pushed value on its path) holding that screen's children and props. When the renderer pops one of those host screens (a tap on it), the host sends the child a tap on the matching child navscreen, the event a renderer sends for a back, so the child pops its own path; the host's path then follows the child's. In a remote root, a pushed navscreen whose value is plain data carries it as route (a renderer's root never sends it); a host restoring the child's screens sends its navstack a setpath event ({ type: 'setpath', id, path }), which sets the stack's path whole. No renderer sends it.

The platform#

An app is drawn as one of two platforms (docs/notes/macos.md): ios, the default, or macos. The renderer tells Swift which in the environment event, beside the size class:

{ "type": "environment", "colorScheme": "light", "dynamicTypeSize": "large",
  "horizontalSizeClass": "regular", "scenePhase": "active", "platform": "macos" }

A page sends it in every environment event, from the device the preview shows (a Mac window is macos, the iPhone and iPad and no device ios) or, for a React app mounted without a device, from the browser (a fine pointer that can hover at the regular width is macos); a native app sends the OS it runs on. It does not change within a session except when the preview's device picker changes it. Swift keeps it as EnvironmentValues._swiftBrowserPlatform ("ios" until the first event), for the shim's own choices; an app's code tells the platforms apart at compile time with #if os(macOS), which the CLI makes hold for an app built with --platform macos (as it makes os(iOS) hold otherwise), defining SWIFTBROWSER_MACOS beside SWIFTBROWSER. The renderer marks the document html[data-sb-platform="macos"] and lays out with the platform in its environment; what the Mac idiom draws differently is the next stage.