@swiftbrowser/react 0.28.4 → 0.28.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -1
- package/dist/components/containers.d.ts.map +1 -1
- package/dist/components/controls.d.ts +14 -0
- package/dist/components/controls.d.ts.map +1 -1
- package/dist/components/remoteTree.d.ts +31 -0
- package/dist/components/remoteTree.d.ts.map +1 -1
- package/dist/components/shapes.d.ts +3 -1
- package/dist/components/shapes.d.ts.map +1 -1
- package/dist/components/split.d.ts.map +1 -1
- package/dist/components/stacks.d.ts +16 -0
- package/dist/components/stacks.d.ts.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +156 -40
- package/dist/index.js.map +1 -1
- package/dist/lazy.d.ts +16 -4
- package/dist/lazy.d.ts.map +1 -1
- package/dist/mount.d.ts +1 -1
- package/dist/mount.d.ts.map +1 -1
- package/package.json +2 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/environment.ts","../src/bitmaps.ts","../src/host/instance.ts","../src/host/tree.ts","../src/host/reconciler.ts","../src/host/root.ts","../src/host/remote.ts","../src/host/sb.ts","../src/inheritedStyle.ts","../src/navigation-context.ts","../src/components/remoteTree.tsx","../src/binding.ts","../src/dragDrop.tsx","../src/fileImporter.tsx","../src/fileExporter.tsx","../src/components/row.tsx","../src/values.ts","../src/scrollReader.tsx","../src/scrollEnvironment.tsx","../src/lazy.tsx","../src/components/stacks.tsx","../src/components/text.tsx","../src/components/navigation.tsx","../src/components/split.tsx","../src/presentation.tsx","../src/inspector.tsx","../src/lifecycle.tsx","../src/coordinateSpace.tsx","../src/components/geometry.tsx","../src/visualEffect.tsx","../src/pointer.tsx","../src/modifiers.tsx","../src/components/hostElement.tsx","../src/measureText.ts","../src/mount.ts","../src/undo.ts","../src/bridge.ts","../src/island.tsx","../src/path.ts","../src/attributedText.ts","../src/audioRecorder.ts","../src/avAsset.ts","../src/videoRecorder.tsx","../src/audioEngine.ts","../src/languageModel.ts","../src/wakeLock.ts","../src/components/controls.tsx","../src/components/shapes.tsx","../src/appleSignIn.tsx","../src/geolocation.ts","../src/speech.ts","../src/appStorage.ts","../src/fileManager.ts","../src/fileStorage.ts","../src/components/lists.tsx","../src/components/tabs.tsx","../src/components/host.tsx","../src/components/registered.tsx","../src/components/menus.tsx","../src/components/images.tsx","../src/components/charts.tsx","../src/components/containers.tsx","../src/components/table.tsx","../src/components/system.tsx","../src/components/canvas.tsx","../src/components/media.tsx","../src/components/animators.tsx"],"sourcesContent":["/**\n * Environment values: what a modifier on a container passes to the views\n * below it (`.buttonStyle`, `.controlSize`…), and the device environment the\n * page sets (color scheme, Dynamic Type size, size class, scene phase).\n */\n\nimport type { ButtonStyle, ColorScheme, DynamicTypeSize, PickerStyle, Platform, ScenePhase, ToggleStyle } from '@swiftbrowser/web/src/protocol';\nimport { createContext, createElement, useContext, type ReactNode } from 'react';\n\nexport type ControlSize = 'mini' | 'small' | 'regular' | 'large' | 'extraLarge';\n\n/** `.symbolRenderingMode(_:)`: `palette` draws a symbol's layers in the foreground styles' levels. */\nexport type SymbolRenderingMode = 'monochrome' | 'multicolor' | 'hierarchical' | 'palette';\n\n/** The text input hints a text field carries (the `textfield` element's props of the same names). */\nexport interface TextInputHints {\n keyboard?: KeyboardType | undefined;\n contentType?: TextContentType | undefined;\n autocapitalization?: 'never' | 'words' | 'sentences' | 'characters' | undefined;\n autocorrectionDisabled?: boolean | undefined;\n}\n\n/** `UIKeyboardType`'s cases. */\nexport type KeyboardType =\n | 'default' | 'asciiCapable' | 'numbersAndPunctuation' | 'URL' | 'numberPad' | 'phonePad' | 'namePhonePad'\n | 'emailAddress' | 'decimalPad' | 'twitter' | 'webSearch' | 'asciiCapableNumberPad';\n\n/** `UITextContentType`'s names. */\nexport type TextContentType =\n | 'name' | 'givenName' | 'familyName' | 'emailAddress' | 'telephoneNumber' | 'username' | 'password' | 'newPassword'\n | 'oneTimeCode' | 'URL' | 'fullStreetAddress' | 'postalCode' | 'creditCardNumber';\n\nexport interface ViewEnvironment {\n buttonStyle?: ButtonStyle;\n controlSize?: ControlSize;\n pickerStyle?: PickerStyle;\n toggleStyle?: ToggleStyle;\n labelsHidden?: boolean;\n /** `.refreshable`: the nearest `List` or `ScrollView` below runs it on a pull. */\n refresh?: () => unknown;\n /** `.submitLabel`: the return key's label of the text fields below. */\n submitLabel?: string;\n /** `.keyboardType`, `.textContentType`, `.textInputAutocapitalization`, `.autocorrectionDisabled` for the text fields below. */\n textInputHints?: TextInputHints;\n /** `.labelStyle`: how the `Label`s below draw. */\n labelStyle?: 'automatic' | 'titleAndIcon' | 'titleOnly' | 'iconOnly' | undefined;\n /** `.redacted(reason: .placeholder)`: text and images below draw as placeholder shapes. */\n redacted?: boolean;\n /** `.textCase(_:)` for the texts below. */\n textCase?: 'uppercase' | 'lowercase' | null;\n /** `.symbolRenderingMode(_:)` for the images below. */\n symbolRenderingMode?: SymbolRenderingMode;\n /** Inside an alert's actions: tapping a button also dismisses the alert. */\n dismissAlert?: () => void;\n}\n\nexport const ViewEnvironmentContext = createContext<ViewEnvironment>({});\n\nexport function useViewEnvironment(): ViewEnvironment {\n return useContext(ViewEnvironmentContext);\n}\n\n/** Wrap `children` in an environment with `values` added. */\nexport function withEnvironment(values: ViewEnvironment, children: ReactNode): ReactNode {\n return createElement(EnvironmentExtender, { values }, children);\n}\n\nfunction EnvironmentExtender({ values, children }: { values: ViewEnvironment; children?: ReactNode }): ReactNode {\n const parent = useContext(ViewEnvironmentContext);\n return createElement(ViewEnvironmentContext.Provider, { value: { ...parent, ...values } }, children);\n}\n\nexport type HorizontalSizeClass = 'compact' | 'regular';\n\nexport type { Platform };\n\nexport interface Environment {\n colorScheme: ColorScheme;\n dynamicTypeSize: DynamicTypeSize;\n /** `compact` below 700 points of width (an iPhone), `regular` from it (an iPad, a desktop window). */\n horizontalSizeClass: HorizontalSizeClass;\n /**\n * `active` while the app is in front and takes input, `inactive` while it\n * shows but does not (the app switcher, a system sheet over it, a page\n * whose window lost focus), `background` while it is not shown (a hidden\n * tab, an app the viewer left). `active` where nothing says otherwise.\n */\n scenePhase: ScenePhase;\n /**\n * The platform the app is drawn as (docs/notes/macos.md): `ios` (the\n * default) or `macos`. The renderer draws that platform's idiom; a page\n * decides it from the browser (`mount`'s `platform`), a native app from\n * the OS it runs on. Fixed for the app's life.\n */\n platform: Platform;\n}\n\nexport type { ScenePhase };\n\nexport const EnvironmentContext = createContext<Environment>({\n colorScheme: 'light',\n dynamicTypeSize: 'large',\n horizontalSizeClass: 'compact',\n scenePhase: 'active',\n platform: 'ios',\n});\n\nexport function EnvironmentProvider({ value, children }: { value: Environment; children?: ReactNode }): ReactNode {\n return createElement(EnvironmentContext.Provider, { value }, children);\n}\n\n/** `@Environment(\\.colorScheme)` */\nexport function useColorScheme(): ColorScheme {\n return useContext(EnvironmentContext).colorScheme;\n}\n\n/** `@Environment(\\.dynamicTypeSize)` */\nexport function useDynamicTypeSize(): DynamicTypeSize {\n return useContext(EnvironmentContext).dynamicTypeSize;\n}\n\n/** `@Environment(\\.dismiss)`: set by sheets and pushed screens. */\nexport const DismissContext = createContext<(() => void) | null>(null);\n\nexport function useDismiss(): () => void {\n const dismiss = useContext(DismissContext);\n return dismiss ?? (() => {});\n}\n\n/** `@Environment(\\.horizontalSizeClass)` */\nexport function useHorizontalSizeClass(): HorizontalSizeClass {\n return useContext(EnvironmentContext).horizontalSizeClass;\n}\n\n/**\n * `@Environment(\\.scenePhase)`: `active`, `inactive` or `background`. A\n * page follows the document's visibility and the window's focus; the native\n * app follows its scene. Refresh what time moved on when it turns `active`.\n */\nexport function useScenePhase(): ScenePhase {\n return useContext(EnvironmentContext).scenePhase;\n}\n\n/**\n * The platform the app is drawn as, `ios` or `macos` (docs/notes/macos.md):\n * for a layout that differs between a phone and a Mac beyond what the size\n * class says (a toolbar's placement, a window's columns). The views adapt\n * on their own, as SwiftUI's do.\n */\nexport function usePlatform(): Platform {\n return useContext(EnvironmentContext).platform;\n}\n\n/** `@Environment(\\.redactionReasons)`: whether the views below are placeholders. */\nexport function useRedacted(): boolean {\n return useContext(ViewEnvironmentContext).redacted === true;\n}\n","/**\n * Bitmaps: a picture's bytes as a Core Image source, and the recipes the\n * renderer draws over one (docs/ops-protocol.md, \"Bitmaps and Core Image\").\n * `bitmapSource` registers a file (a PNG, JPEG, GIF or WebP, as bytes or a\n * data URL) and reads its size from the header; `<Image bitmap={...} />`\n * draws it with Core Image steps applied: crops, turns, adjustments, photo\n * effects, blurs. The pixels never pass through JavaScript: the page runs\n * the steps on a canvas (Web/src/imageOps.ts), a native app with Core Image.\n * The host tree sends each source once, as an `imagedata` op before the\n * first element that draws it (host/tree.ts).\n */\n\nimport { base64Decode, base64Encode } from '@swiftbrowser/web/src/base64';\nimport { addLiveBitmap, forgetLiveBitmap } from '@swiftbrowser/web/src/bitmaps';\nimport type { BitmapStep, ImageDataOp } from '@swiftbrowser/web/src/protocol';\n\nexport type { BitmapPoint, BitmapStep, BitmapVector, PhotoEffect } from '@swiftbrowser/web/src/protocol';\n\n/** A registered picture: the key the renderer knows it by, and its size in pixels as drawn (a JPEG's EXIF rotation applied). */\nexport interface BitmapSource {\n readonly key: string;\n readonly width: number;\n readonly height: number;\n readonly mime: string;\n}\n\n/** What `<Image bitmap>` draws: `source` (null: an empty image) with `steps` applied in order, in Core Image's space (source pixels, origin at the bottom left, y up). */\nexport interface Bitmap {\n source: BitmapSource | null;\n steps?: readonly BitmapStep[];\n /** For a live source (`liveBitmapSource`): a count raised each time the pixels changed in place, which draws them again. */\n version?: number;\n}\n\n/** A rectangle in Core Image's space; infinite sides for a clamped image. */\nexport interface BitmapRect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/** The sources registered in this realm, by key, as their ops. */\nconst registry = new Map<string, ImageDataOp>();\n/** Data URLs already registered, so a render does not decode one again. */\nconst byURL = new Map<string, BitmapSource | null>();\n\n/**\n * Registers a picture file and returns it as a source, or null when the bytes\n * are not a PNG, JPEG, GIF or WebP file whose size the header gives (pass\n * `width` and `height` to register one anyway). The same bytes give the same\n * key, however often they are registered.\n */\nexport function bitmapSource(file: Uint8Array | string, options: { mime?: string; width?: number; height?: number } = {}): BitmapSource | null {\n if (typeof file === 'string') {\n const known = byURL.get(file);\n if (known !== undefined) return known;\n const match = /^data:([^;,]*)(?:;[^,]*)?;base64,(.*)$/s.exec(file);\n const source = match ? register(base64Decode(match[2]!), match[2]!, { mime: match[1] || undefined, ...options }) : null;\n byURL.set(file, source);\n return source;\n }\n return register(file, null, options);\n}\n\nfunction register(bytes: Uint8Array, base64: string | null, options: { mime?: string | undefined; width?: number | undefined; height?: number | undefined }): BitmapSource | null {\n const header = imageHeader(bytes);\n const width = options.width ?? header?.width;\n const height = options.height ?? header?.height;\n const mime = header?.mime ?? options.mime ?? '';\n if (width === undefined || height === undefined) return null;\n const key = `f${fnv1a64(bytes)}`;\n if (!registry.has(key)) registry.set(key, { op: 'imagedata', key, width, height, mime, data: base64 ?? base64Encode(bytes) });\n return { key, width, height, mime };\n}\n\n/**\n * Pixels the page holds as a source: RGBA (straight alpha, rows from the\n * top), `width` × `height`, in memory the app changes in place, a frame at a\n * time, and draws with `<Image bitmap={{ source, version }} />`, raising\n * `version` after each change. Over a `SharedArrayBuffer` (a worker's\n * output, a WebAssembly module's memory) the drawing reads the bytes as\n * they are; over plain memory each version is copied once to the drawing\n * worker. Null in a native app, whose renderer draws no pixels the app\n * holds yet. `releaseBitmapSource` lets the pixels go once nothing shows\n * them.\n */\nexport function liveBitmapSource(pixels: Uint8Array, width: number, height: number): BitmapSource | null {\n if ((globalThis as { __sbNative?: unknown }).__sbNative !== undefined) return null;\n return { key: addLiveBitmap(pixels, width, height), width, height, mime: '' };\n}\n\nexport function releaseBitmapSource(source: BitmapSource): void {\n if (source.key.startsWith('l')) forgetLiveBitmap(source.key);\n}\n\n/** A source's `imagedata` op, when it was registered here. */\nexport function bitmapSourceOp(key: string): ImageDataOp | undefined {\n return registry.get(key);\n}\n\n/** Keeps an `imagedata` op another tree sent (a remote tree's, host/remote.ts), so this realm's tree can send it on. */\nexport function registerBitmapSourceOp(op: ImageDataOp): void {\n if (!registry.has(op.key)) registry.set(op.key, op);\n}\n\n/** FNV-1a, 64 bits, as 16 hex digits: the protocol's content hash. */\nfunction fnv1a64(bytes: Uint8Array): string {\n // Two 32-bit halves: the prime is 2^40 + 0x1b3.\n let hi = 0xcbf29ce4;\n let lo = 0x84222325;\n for (let i = 0; i < bytes.length; i++) {\n lo = (lo ^ bytes[i]!) >>> 0;\n // (hi, lo) × 0x100000001b3 = (hi, lo) × 0x1b3 + (lo << 40)\n const loMul = lo * 0x1b3;\n const carry = Math.floor(loMul / 0x100000000);\n const newLo = loMul >>> 0;\n const newHi = (Math.imul(hi, 0x1b3) + carry + ((lo << 8) >>> 0)) >>> 0;\n hi = newHi;\n lo = newLo;\n }\n return hi.toString(16).padStart(8, '0') + lo.toString(16).padStart(8, '0');\n}\n\n// ---------------------------------------------------------------------------\n// Headers\n// ---------------------------------------------------------------------------\n\n/** A file's type and size in pixels as drawn, from its header: PNG, JPEG (EXIF orientation 5–8 swaps the sides), GIF and WebP. */\nexport function imageHeader(b: Uint8Array): { mime: string; width: number; height: number } | null {\n const u16 = (i: number, little = false): number => (little ? b[i]! | (b[i + 1]! << 8) : (b[i]! << 8) | b[i + 1]!);\n const u32 = (i: number): number => ((b[i]! << 24) | (b[i + 1]! << 16) | (b[i + 2]! << 8) | b[i + 3]!) >>> 0;\n if (b.length >= 24 && b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47) {\n return { mime: 'image/png', width: u32(16), height: u32(20) };\n }\n if (b.length >= 10 && b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46) {\n return { mime: 'image/gif', width: u16(6, true), height: u16(8, true) };\n }\n if (b.length >= 30 && b[0] === 0x52 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x46 && b[8] === 0x57 && b[9] === 0x45 && b[10] === 0x42 && b[11] === 0x50) {\n const chunk = String.fromCharCode(b[12]!, b[13]!, b[14]!, b[15]!);\n if (chunk === 'VP8 ') return { mime: 'image/webp', width: u16(26, true) & 0x3fff, height: u16(28, true) & 0x3fff };\n if (chunk === 'VP8L') {\n const bits = (b[21]! | (b[22]! << 8) | (b[23]! << 16) | (b[24]! << 24)) >>> 0;\n return { mime: 'image/webp', width: (bits & 0x3fff) + 1, height: ((bits >>> 14) & 0x3fff) + 1 };\n }\n if (chunk === 'VP8X') return { mime: 'image/webp', width: 1 + (b[24]! | (b[25]! << 8) | (b[26]! << 16)), height: 1 + (b[27]! | (b[28]! << 8) | (b[29]! << 16)) };\n return null;\n }\n if (b.length >= 4 && b[0] === 0xff && b[1] === 0xd8) {\n let orientation = 1;\n let i = 2;\n while (i + 4 <= b.length) {\n if (b[i] !== 0xff) return null;\n const marker = b[i + 1]!;\n if (marker === 0xd8 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {\n i += 2;\n continue;\n }\n const length = u16(i + 2);\n if (marker === 0xe1 && length >= 16) orientation = exifOrientation(b, i + 4, length - 2) ?? orientation;\n // Start of frame (baseline, progressive, …), not DHT (c4), JPG (c8) or DAC (cc).\n if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {\n if (i + 9 > b.length) return null;\n const height = u16(i + 5);\n const width = u16(i + 7);\n return orientation >= 5 && orientation <= 8 ? { mime: 'image/jpeg', width: height, height: width } : { mime: 'image/jpeg', width, height };\n }\n i += 2 + length;\n }\n }\n return null;\n}\n\n/** The orientation tag (0x0112) of an APP1 segment's EXIF data, if any. */\nfunction exifOrientation(b: Uint8Array, start: number, length: number): number | null {\n // \"Exif\\0\\0\", then a TIFF header.\n if (b[start] !== 0x45 || b[start + 1] !== 0x78 || b[start + 2] !== 0x69 || b[start + 3] !== 0x66) return null;\n const tiff = start + 6;\n const end = Math.min(b.length, start + length);\n const little = b[tiff] === 0x49;\n const u16 = (i: number): number => (little ? b[i]! | (b[i + 1]! << 8) : (b[i]! << 8) | b[i + 1]!);\n const u32 = (i: number): number => (little ? (b[i]! | (b[i + 1]! << 8) | (b[i + 2]! << 16) | (b[i + 3]! << 24)) >>> 0 : ((b[i]! << 24) | (b[i + 1]! << 16) | (b[i + 2]! << 8) | b[i + 3]!) >>> 0);\n if (tiff + 8 > end) return null;\n const ifd = tiff + u32(tiff + 4);\n if (ifd + 2 > end) return null;\n const count = u16(ifd);\n for (let n = 0; n < count; n++) {\n const entry = ifd + 2 + n * 12;\n if (entry + 12 > end) return null;\n if (u16(entry) === 0x0112) return u16(entry + 8);\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Extents\n// ---------------------------------------------------------------------------\n\n/**\n * Where a recipe's output lies, in Core Image's space: the source's\n * rectangle carried through the steps as Core Image's `extent` is (a crop\n * keeps the overlap, a blur grows by three radii, a transform takes the\n * moved rectangle's bounds, `clamp` makes it infinite). What `<Image\n * bitmap>` sizes itself by.\n */\nexport function bitmapExtent(source: { width: number; height: number } | null, steps: readonly BitmapStep[] = []): BitmapRect {\n let r: BitmapRect = source ? { x: 0, y: 0, width: source.width, height: source.height } : { x: 0, y: 0, width: 0, height: 0 };\n const infinite = (): boolean => !Number.isFinite(r.width) || !Number.isFinite(r.height);\n for (const step of steps) {\n switch (step.op) {\n case 'crop': {\n if (infinite()) {\n r = { x: step.x, y: step.y, width: step.width, height: step.height };\n break;\n }\n const x0 = Math.max(r.x, step.x);\n const y0 = Math.max(r.y, step.y);\n const x1 = Math.min(r.x + r.width, step.x + step.width);\n const y1 = Math.min(r.y + r.height, step.y + step.height);\n r = { x: x0, y: y0, width: Math.max(0, x1 - x0), height: Math.max(0, y1 - y0) };\n break;\n }\n case 'render':\n r = { x: 0, y: 0, width: step.width, height: step.height };\n break;\n case 'clamp':\n r = { x: -Infinity, y: -Infinity, width: Infinity, height: Infinity };\n break;\n case 'gaussianBlur': {\n if (infinite()) break;\n const grow = Math.ceil(3 * step.radius);\n r = { x: r.x - grow, y: r.y - grow, width: r.width + 2 * grow, height: r.height + 2 * grow };\n break;\n }\n case 'place':\n if (!(step.sx > 0) || !(step.sy > 0)) r = { x: step.tx, y: step.ty, width: 0, height: 0 };\n else if (!infinite()) r = { x: r.x * step.sx + step.tx, y: r.y * step.sy + step.ty, width: r.width * step.sx, height: r.height * step.sy };\n break;\n case 'transform': {\n if (infinite()) break;\n const { a, b, c, d, tx, ty } = step;\n if (!(Math.abs(a * d - b * c) > 1e-12)) {\n r = { x: tx, y: ty, width: 0, height: 0 };\n break;\n }\n const xs: number[] = [];\n const ys: number[] = [];\n for (const [x, y] of [\n [r.x, r.y],\n [r.x + r.width, r.y],\n [r.x, r.y + r.height],\n [r.x + r.width, r.y + r.height],\n ] as const) {\n xs.push(a * x + c * y + tx);\n ys.push(b * x + d * y + ty);\n }\n const x0 = Math.min(...xs);\n const y0 = Math.min(...ys);\n r = { x: x0, y: y0, width: Math.max(...xs) - x0, height: Math.max(...ys) - y0 };\n break;\n }\n default:\n break;\n }\n }\n return r;\n}\n","/**\n * The host tree the reconciler mutates: one `Instance` per host element. A\n * host element is always the intrinsic type `sb` with a `kind` (an element\n * kind of the ops protocol, or one of the two virtual kinds below) and the\n * element's `props`; the React components in ../components render nothing\n * else.\n */\n\nimport type { RendererEvent } from '@swiftbrowser/web/src/protocol';\nimport type { ReactNode } from 'react';\nimport type { Effective } from './tree';\n\nexport type EventType = RendererEvent['type'];\nexport type EventOf<K extends EventType> = Extract<RendererEvent, { type: K }>;\n/**\n * The renderer's events an element answers, by type. `'*'` takes every\n * event addressed to the element that no typed handler took: a mirrored\n * element (`RemoteTree`) forwards them all to the root that drew it.\n */\nexport type EventHandlers = { [K in EventType]?: (event: EventOf<K>) => void } & { '*'?: (event: AddressedEvent) => void };\n\n/** An event the renderer addresses to one element. */\nexport type AddressedEvent = Extract<RendererEvent, { id: number }>;\n\n/**\n * Where a virtual element acts: the nearest enclosing `navscreen` or `sheet`\n * element, or the root container.\n */\nexport type HoistTarget = 'navscreen' | 'sheet' | 'root';\n\n/**\n * A preference: not an element itself; its `props` are merged into the\n * target's props (`.navigationTitle` sets the enclosing screen's `title`,\n * `.presentationDetents` the enclosing sheet's `detents`).\n */\nexport const PREF_KIND = '$pref';\n/**\n * A hoist: not an element itself; its children become children of the target\n * after the target's own (`.toolbar` items join the screen, `.sheet` content\n * becomes a root-level `sheet` element).\n */\nexport const HOIST_KIND = '$hoist';\n\nexport interface HostProps {\n kind: string;\n props?: Record<string, unknown>;\n on?: EventHandlers;\n target?: HoistTarget;\n children?: ReactNode;\n}\n\nexport interface Instance {\n /** The element id in the ops protocol; stable for the instance's life. */\n id: number;\n kind: string;\n props: Record<string, unknown>;\n on: EventHandlers | undefined;\n target: HoistTarget | undefined;\n /** The children as React currently has them (virtual kinds included). */\n children: Instance[];\n /** Hidden by Suspense: left out of the emitted tree. */\n hidden: boolean;\n /** Whether a `create` op was emitted for the current id. */\n created: boolean;\n committedProps: Record<string, unknown> | null;\n committedParent: TreeNode | null;\n committedChildren: Instance[];\n /** The element React has it under (virtual kinds included); null while detached. */\n parent: TreeNode | null;\n /** Changed since the last flush (itself, a child, its visibility), or under something that has: resolved again at the next. */\n stale: boolean;\n /** How it was last emitted (tree.ts `Effective`); null before its first flush. */\n entry: Effective | null;\n /** Whether it is in the emitted tree as of the last flush. */\n shown: boolean;\n /** The element it is a child of as emitted: its React parent, or the target it was hoisted to. */\n effectiveParent: TreeNode | null;\n /** The flush that last resolved it (tree.ts `generation`); a reused subtree keeps an older one. */\n resolvedIn: number;\n}\n\n/** The root container, element id 0. */\nexport interface RootNode {\n id: 0;\n kind: 'root';\n children: Instance[];\n committedChildren: Instance[];\n parent: null;\n stale: boolean;\n entry: Effective | null;\n}\n\nexport type TreeNode = Instance | RootNode;\n","/**\n * Turns the host tree into ops. The reconciler mutates `Instance.children`\n * freely during a React commit; `flush` then resolves the virtual kinds\n * (preferences and hoists), diffs the result against what was emitted last\n * time and produces one render pass: creates and updates, inserts (parents\n * before children, as the Swift core orders them), removes, `commit`.\n *\n * The flush is incremental: every mutation the reconciler makes marks the\n * instance and its ancestors stale (`markStale`), and a flush resolves and\n * diffs only the stale subtrees, reusing each clean subtree's effective\n * entry from the last flush, what it hoisted and the preferences it sent\n * up replayed into the ancestors resolved again. A knob dragged in a tree\n * of three thousand elements then costs the knob's path, not the tree.\n */\n\nimport type { Animation, CommitOp, Op, RendererEvent } from '@swiftbrowser/web/src/protocol';\nimport { bitmapSourceOp } from '../bitmaps';\nimport { HOIST_KIND, PREF_KIND, type HoistTarget, type HostProps, type Instance, type RootNode, type TreeNode } from './instance';\n\nexport type OpsSink = (ops: Op[]) => void;\n\nexport interface HostTreeOptions {\n /**\n * The tree is drawn by another root (`RemoteTree`), not a renderer: a\n * preference with no screen to take it goes to the root instead of being\n * dropped, and the root's props are sent whole as `update` of element 0\n * (a renderer takes only `colorScheme` there), so the host can lift them\n * to the screen it draws the tree in.\n */\n remote?: boolean;\n}\n\n/**\n * What a subtree sends past its top to the ancestors that take it: a\n * preference's props for the nearest element of its target kind, or an\n * element hoisted after that target's own children. Kept with the subtree's\n * entry and replayed when the subtree is reused, resolved against the\n * ancestors it then has.\n */\ntype Contribution = { kind: 'pref'; target: HoistTarget | undefined; props: Record<string, unknown> } | { kind: 'hoist'; target: HoistTarget | undefined; node: Instance };\n\n/** An element as emitted: its props with the preferences merged in, its children (own, then hoisted), what left it. */\nexport interface Effective {\n /** The props as sent: the element's own object until a preference or an inherited title mode writes, then a copy. */\n props: Record<string, unknown>;\n /** The props before the title mode inherited from the screen below (a stack's screens), to derive it from again. */\n base: Record<string, unknown>;\n children: Instance[];\n /** Children hoisted here from inside the subtree, appended after `children` once the whole tree is visited. */\n hoisted: Instance[];\n /** What this subtree sent to the ancestors above it, in visit order. */\n escaping: Contribution[];\n}\n\ninterface Context {\n navscreen?: Instance;\n sheet?: Instance;\n}\n\n/**\n * A pushed screen whose title display mode is `automatic` takes the mode of\n * the screen below it, as on iOS (a navigation item's `.automatic` inherits\n * the previous item's): a stack whose root has a large title shows large\n * titles on the screens it pushes, until one says `.inline`. The root's own\n * `automatic` is left for the page (large). As the Swift core does\n * (`_inheritingTitleModes`), once `.navigationBarTitleDisplayMode` is merged in.\n */\nfunction inheritTitleModes(screens: readonly Instance[]): void {\n let below = 'large';\n for (const screen of screens) {\n const entry = screen.kind === 'navscreen' ? screen.entry : null;\n if (!entry) continue;\n const base = entry.base;\n const depth = typeof base['depth'] === 'number' ? base['depth'] : 0;\n let mode = typeof base['displayMode'] === 'string' ? base['displayMode'] : 'automatic';\n if (mode === 'automatic') {\n if (depth > 0) {\n // Written into a copy, never the element's own props; the same value as last time leaves the entry as it is.\n if (entry.props['displayMode'] !== below) entry.props = { ...base, displayMode: below };\n } else if (entry.props !== base) entry.props = base;\n mode = depth > 0 ? below : 'large';\n } else if (entry.props !== base) entry.props = base;\n below = mode === 'inline' ? 'inline' : 'large';\n }\n}\n\n/** `node` changed (its props, its children, its visibility): it and every ancestor are resolved and diffed again at the next flush. */\nexport function markStale(node: TreeNode): void {\n for (let current: TreeNode | null = node; current && !current.stale; current = current.kind === 'root' ? null : current.parent) current.stale = true;\n}\n\n/** Puts `child` under `parent` at `index` (the end when absent), as the reconciler asks. */\nexport function attach(parent: TreeNode, child: Instance, index?: number): void {\n detach(parent, child);\n if (index === undefined || index < 0 || index > parent.children.length) parent.children.push(child);\n else parent.children.splice(index, 0, child);\n child.parent = parent;\n markStale(parent);\n}\n\n/** Takes `child` out of `parent`, if it is there. */\nexport function detach(parent: TreeNode, child: Instance): void {\n const at = parent.children.indexOf(child);\n if (at >= 0) parent.children.splice(at, 1);\n if (child.parent === parent) child.parent = null;\n markStale(parent);\n}\n\nexport class HostTree {\n readonly root: RootNode = { id: 0, kind: 'root', children: [], committedChildren: [], parent: null, stale: true, entry: null };\n private nextId = 1;\n /** Emitted elements by id, for event dispatch. */\n private readonly live = new Map<number, Instance>();\n /** Ids whose element changed kind: removed at the end of the next flush. */\n private retired: number[] = [];\n /** Which flush is under way; an instance resolved in it carries the number. */\n private generation = 0;\n /** `withAnimation`: stamped on the next `commit`. */\n pendingAnimation: Animation | undefined;\n /** `withAnimation(_:completionCriteria:_:completion:)`: stamped on the next `commit` with its serial; the callback waits in `completions`. */\n pendingCompletion: { serial: number; criteria: 'logicallyComplete' | 'removed'; callback: () => void; whenNothingDrawn?: boolean } | undefined;\n private readonly completions = new Map<number, () => void>();\n /** The root's `colorScheme` last sent (`.preferredColorScheme`); undefined while none was. */\n private committedColorScheme: 'light' | 'dark' | null | undefined;\n /** Remote: the root's props last sent. */\n private committedRootProps: Record<string, unknown> = {};\n /** The bitmap sources (`imagedata` keys) this tree has sent: each goes once, before the first image that draws it. */\n private readonly sentSources = new Set<string>();\n\n constructor(\n private readonly sink: OpsSink,\n private readonly options: HostTreeOptions = {},\n ) {}\n\n /** Whether another tree draws this one (`createSwiftUIRoot(sink, { remote: true })`, for a `RemoteTree`). */\n get remote(): boolean {\n return this.options.remote === true;\n }\n\n createInstance(props: HostProps): Instance {\n return {\n id: this.nextId++,\n kind: props.kind,\n props: props.props ?? {},\n on: props.on,\n target: props.target,\n children: [],\n hidden: false,\n created: false,\n committedProps: null,\n committedParent: null,\n committedChildren: [],\n parent: null,\n stale: true,\n entry: null,\n shown: false,\n effectiveParent: null,\n resolvedIn: 0,\n };\n }\n\n updateInstance(instance: Instance, next: HostProps): void {\n if (next.kind !== instance.kind) {\n // An element cannot change kind: the old one goes, a new id takes its\n // place and the children move over.\n if (instance.created) {\n this.retired.push(instance.id);\n this.live.delete(instance.id);\n }\n instance.id = this.nextId++;\n instance.kind = next.kind;\n instance.created = false;\n instance.committedProps = null;\n instance.committedParent = null;\n instance.committedChildren = [];\n }\n instance.props = next.props ?? {};\n instance.on = next.on;\n instance.target = next.target;\n markStale(instance);\n }\n\n /** `node` is hidden or shown again (Suspense): it leaves or rejoins the emitted tree. */\n setHidden(instance: Instance, hidden: boolean): void {\n instance.hidden = hidden;\n markStale(instance);\n }\n\n /** Emit the ops for everything that changed since the last commit. */\n commit(): void {\n const ops = this.flush();\n if (ops.length > 0) this.sink(ops);\n }\n\n flush(): Op[] {\n const animation = this.pendingAnimation;\n this.pendingAnimation = undefined;\n const completion = this.pendingCompletion;\n this.pendingCompletion = undefined;\n const generation = ++this.generation;\n const root = this.root;\n\n // Phase 1: the effective tree, resolved again only where something changed.\n const rootEntry: Effective = { props: {}, base: {}, children: [], hoisted: [], escaping: [] };\n const previousRoot = root.entry;\n root.entry = rootEntry;\n /** The elements resolved this flush, with their last entry (to find what left them). */\n const resolved: [Instance, Effective | null][] = [];\n /** The elements resolved this flush whose own children are under way, nearest last (a contribution is kept by those below its target). */\n const path: Instance[] = [];\n const targetOf = (target: HoistTarget | undefined, ctx: Context, hoist: boolean): TreeNode | undefined => {\n if (target === 'root' || target === undefined) return root;\n return ctx[target] ?? (hoist || this.options.remote ? root : undefined);\n };\n /** Keeps `contribution` with every element on the path below `target`, so a reuse of any of them replays it. */\n const keep = (contribution: Contribution, target: TreeNode | undefined): void => {\n for (let i = path.length - 1; i >= 0; i--) {\n const node = path[i]!;\n if (node === target) return;\n node.entry!.escaping.push(contribution);\n }\n };\n const assign = (target: TreeNode, props: Record<string, unknown>): void => {\n const entry = target.entry!;\n // The element's own props object is never written: the first preference takes a copy.\n if (target.kind !== 'root' && entry.props === (target as Instance).props) {\n entry.props = { ...entry.props };\n entry.base = entry.props;\n }\n Object.assign(entry.props, props);\n if (entry.base !== entry.props) Object.assign(entry.base, props);\n };\n const contribute = (contribution: Contribution, ctx: Context): void => {\n if (contribution.kind === 'pref') {\n const target = targetOf(contribution.target, ctx, false);\n if (target) assign(target, contribution.props);\n keep(contribution, target);\n } else {\n const target = targetOf(contribution.target, ctx, true)!;\n target.entry!.hoisted.push(contribution.node);\n contribution.node.effectiveParent = target;\n keep(contribution, target);\n }\n };\n const visit = (child: Instance, sink: Instance[], owner: TreeNode, ctx: Context, hoistedTo: HoistTarget | null | undefined): void => {\n if (child.hidden) return;\n // A preference or a hoist is resolved into its target, never kept as an entry: it is clean once visited, so a\n // change below it marks its ancestors stale again (`markStale` stops at the first stale element it meets).\n if (child.kind === PREF_KIND || child.kind === HOIST_KIND) child.stale = false;\n if (child.kind === PREF_KIND) {\n contribute({ kind: 'pref', target: child.target, props: child.props }, ctx);\n return;\n }\n if (child.kind === HOIST_KIND) {\n const target = targetOf(child.target, ctx, true)!;\n for (const grandchild of child.children) visit(grandchild, target.entry!.hoisted, target, ctx, child.target ?? 'root');\n return;\n }\n if (hoistedTo !== undefined) {\n // A hoisted element: kept by the path below its target, with the target as its effective parent.\n child.effectiveParent = owner;\n keep({ kind: 'hoist', target: hoistedTo ?? undefined, node: child }, owner);\n }\n sink.push(child);\n if (!child.stale && child.entry) {\n // Nothing under it changed: last flush's entry stands, and what it sent up goes up again.\n child.effectiveParent = owner;\n child.shown = true;\n for (const contribution of child.entry.escaping) contribute(contribution, ctx);\n return;\n }\n const entry: Effective = { props: child.props, base: child.props, children: [], hoisted: [], escaping: [] };\n resolved.push([child, child.entry]);\n child.entry = entry;\n child.stale = false;\n child.shown = true;\n child.effectiveParent = owner;\n child.resolvedIn = generation;\n const next: Context = child.kind === 'navscreen' ? { ...ctx, navscreen: child } : child.kind === 'sheet' ? { ...ctx, sheet: child } : ctx;\n path.push(child);\n for (const grandchild of child.children) visit(grandchild, entry.children, child, next, undefined);\n path.pop();\n };\n for (const child of root.children) visit(child, rootEntry.children, root, {}, undefined);\n root.stale = false;\n if (rootEntry.hoisted.length > 0) rootEntry.children.push(...rootEntry.hoisted);\n for (const [node] of resolved) {\n const entry = node.entry!;\n if (entry.hoisted.length > 0) entry.children.push(...entry.hoisted);\n }\n for (const [node] of resolved) {\n if (node.kind === 'navstack') inheritTitleModes(node.entry!.children);\n }\n\n // Phase 2: what left the tree. An element shown last flush and not now sits in the old children of an element\n // resolved now (its parent, or the target it was hoisted to), unless it moved to another.\n const ops: Op[] = [];\n const left: Instance[] = [];\n const arrived = new Set<Instance>();\n const compare = (before: Instance[] | undefined, after: Instance[]): void => {\n if (!before) {\n for (const child of after) arrived.add(child);\n return;\n }\n let same = before.length === after.length;\n for (let i = 0; same && i < after.length; i++) if (before[i] !== after[i]) same = false;\n if (same) return;\n const now = new Set(after);\n for (const child of before) if (!now.has(child)) left.push(child);\n const then = new Set(before);\n for (const child of after) if (!then.has(child)) arrived.add(child);\n };\n compare(previousRoot?.children, rootEntry.children);\n for (const [node, previous] of resolved) compare(previous?.children, node.entry!.children);\n const gone = (instance: Instance): void => {\n this.live.delete(instance.id);\n instance.shown = false;\n instance.created = false;\n instance.committedProps = null;\n instance.committedParent = null;\n instance.committedChildren = [];\n // Resolved afresh if it ever comes back.\n instance.stale = true;\n const entry = instance.entry;\n if (entry) for (const child of entry.children) if (child.effectiveParent === instance) gone(child);\n };\n for (const instance of left) {\n if (!instance.shown || arrived.has(instance)) continue;\n // The top of a removed subtree only: removing it removes the rest.\n ops.push({ op: 'remove', id: instance.id });\n gone(instance);\n }\n\n // Phase 3: the diff, into the elements resolved this flush; a reused subtree is as it was committed.\n const emit = (parent: TreeNode, entry: Effective): void => {\n const current = parent.committedChildren.filter((child) => child.shown && child.effectiveParent === parent);\n entry.children.forEach((child, index) => {\n const childEntry = child.entry!;\n if (child.kind === 'image') this.sendBitmapSource(childEntry.props, ops);\n if (!child.created) {\n ops.push({ op: 'create', id: child.id, kind: child.kind, props: childEntry.props } as Op);\n child.created = true;\n this.live.set(child.id, child);\n } else if (childEntry.props !== child.committedProps && !deepEqual(childEntry.props, child.committedProps)) {\n ops.push({ op: 'update', id: child.id, props: childEntry.props } as Op);\n }\n child.committedProps = childEntry.props;\n // A child that changed kind is the same instance under a new id: it\n // must be inserted again even where it already sits.\n if (current[index] !== child || child.committedParent !== parent) {\n ops.push({ op: 'insert', parent: parent.id, id: child.id, index });\n const at = current.indexOf(child);\n if (at >= 0) current.splice(at, 1);\n current.splice(index, 0, child);\n }\n child.committedParent = parent;\n if (child.resolvedIn === generation) emit(child, childEntry);\n });\n parent.committedChildren = entry.children;\n };\n emit(root, rootEntry);\n\n for (const id of this.retired) ops.push({ op: 'remove', id });\n this.retired = [];\n\n if (this.options.remote) {\n // Everything the preferences left on the root (a title with no screen of its own, a color scheme) goes whole to the host.\n if (!deepEqual(rootEntry.props, this.committedRootProps)) {\n ops.push({ op: 'update', id: 0, props: rootEntry.props } as Op);\n this.committedRootProps = rootEntry.props;\n }\n } else {\n // `.preferredColorScheme`: the only prop the root takes; `null` hands the\n // appearance back to the page once a preference is gone.\n const scheme = rootEntry.props['colorScheme'] as 'light' | 'dark' | null | undefined;\n const next = scheme === undefined ? (this.committedColorScheme === undefined ? undefined : null) : scheme;\n if (next !== undefined && next !== this.committedColorScheme) {\n ops.push({ op: 'update', id: 0, props: { colorScheme: next } } as Op);\n this.committedColorScheme = next === null ? undefined : next;\n }\n }\n\n if (ops.length === 0) {\n // A stamp with no body of its own (`stampNextCommit`): nothing will animate, so its completion runs now.\n if (completion?.whenNothingDrawn) completion.callback();\n return ops;\n }\n const commit: CommitOp = { op: 'commit' };\n if (animation) commit.animation = animation;\n if (completion) {\n // The renderer answers `animationcomplete` with the serial once the pass has finished animating.\n commit.completion = completion.serial;\n if (completion.criteria === 'removed') commit.completionCriteria = 'removed';\n this.completions.set(completion.serial, completion.callback);\n }\n ops.push(commit);\n return ops;\n }\n\n /** An `imagedata` op ahead of an image whose recipe's source this tree has not sent yet (bitmaps.ts). */\n private sendBitmapSource(props: Record<string, unknown>, ops: Op[]): void {\n const key = (props['bitmap'] as { source?: unknown } | undefined)?.source;\n if (typeof key !== 'string' || this.sentSources.has(key)) return;\n const op = bitmapSourceOp(key);\n if (!op) return;\n this.sentSources.add(key);\n ops.push(op);\n }\n\n /** Whether a pass is still animating with this completion serial. */\n awaitsCompletion(serial: number): boolean {\n return this.completions.has(serial);\n }\n\n /** Hand a renderer event to the element's handler for its type. */\n dispatch(event: RendererEvent): void {\n if (event.type === 'batch') {\n for (const each of event.events) this.dispatch(each);\n return;\n }\n if (event.type === 'animationcomplete') {\n const callback = this.completions.get(event.serial);\n this.completions.delete(event.serial);\n callback?.();\n return;\n }\n if (!('id' in event)) return;\n const instance = this.live.get(event.id);\n const handler = (instance?.on?.[event.type] ?? instance?.on?.['*']) as ((event: RendererEvent) => void) | undefined;\n handler?.(event);\n }\n}\n\n/** Structural equality of JSON-like values. */\nexport function deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n if (Array.isArray(a)) {\n const other = b as unknown[];\n return a.length === other.length && a.every((value, index) => deepEqual(value, other[index]));\n }\n const left = a as Record<string, unknown>;\n const right = b as Record<string, unknown>;\n const keys = Object.keys(left);\n if (keys.length !== Object.keys(right).length) return false;\n return keys.every((key) => key in right && deepEqual(left[key], right[key]));\n}\n\n","/**\n * The react-reconciler host config: React mutates `Instance` trees, and\n * `resetAfterCommit` asks the `HostTree` for the ops of the pass.\n */\n\nimport { createContext } from 'react';\nimport Reconciler from 'react-reconciler';\nimport { DefaultEventPriority } from 'react-reconciler/constants';\nimport type { HostProps, Instance } from './instance';\nimport { attach, detach, markStale, type HostTree } from './tree';\n\ntype HostContext = Record<string, never>;\n\nlet currentUpdatePriority = 0;\n\ntype Config = Reconciler.HostConfig<\n string, // Type\n HostProps, // Props\n HostTree, // Container\n Instance, // Instance\n never, // TextInstance\n never, // ActivityInstance\n never, // SuspenseInstance\n never, // HydratableInstance\n never, // FormInstance\n Instance, // PublicInstance\n HostContext, // HostContext\n never, // ChildSet\n ReturnType<typeof setTimeout>, // TimeoutHandle\n -1, // NoTimeout\n null, // TransitionStatus\n null, // SuspendedState\n null, // RendererInspectionConfig\n never, // FormStateMarkerInstance\n never, // HoistableRoot\n never // Resource\n>;\n\nconst hostConfig: Config = {\n supportsMutation: true,\n supportsPersistence: false,\n supportsHydration: false,\n isPrimaryRenderer: true,\n noTimeout: -1,\n scheduleTimeout: setTimeout,\n cancelTimeout: clearTimeout,\n supportsMicrotasks: true,\n scheduleMicrotask: queueMicrotask,\n\n getRootHostContext: () => ({}),\n getChildHostContext: (parent) => parent,\n getPublicInstance: (instance) => instance,\n prepareForCommit: () => null,\n resetAfterCommit: (tree) => tree.commit(),\n preparePortalMount: () => {},\n shouldSetTextContent: () => false,\n\n createInstance: (type, props, tree) => {\n if (type !== 'sb') throw new Error(`Unknown host element <${type}>: only SwiftUI components render here.`);\n return tree.createInstance(props);\n },\n createTextInstance: (text) => {\n throw new Error(`Text strings must be rendered within a <Text> component (got ${JSON.stringify(text)}).`);\n },\n appendInitialChild: (parent, child) => attach(parent, child),\n finalizeInitialChildren: () => false,\n commitMount: () => {},\n commitUpdate: (instance, _type, _prev, next, handle) => {\n const tree = treeOf(handle);\n if (tree) tree.updateInstance(instance, next);\n else {\n instance.props = next.props ?? {};\n instance.on = next.on;\n instance.target = next.target;\n markStale(instance);\n }\n },\n\n appendChild: (parent, child) => attach(parent, child),\n appendChildToContainer: (tree, child) => attach(tree.root, child),\n insertBefore: (parent, child, before) => {\n detach(parent, child);\n const at = parent.children.indexOf(before);\n attach(parent, child, at < 0 ? parent.children.length : at);\n },\n insertInContainerBefore: (tree, child, before) => {\n detach(tree.root, child);\n const at = tree.root.children.indexOf(before);\n attach(tree.root, child, at < 0 ? tree.root.children.length : at);\n },\n removeChild: (parent, child) => detach(parent, child),\n removeChildFromContainer: (tree, child) => detach(tree.root, child),\n clearContainer: (tree) => {\n for (const child of tree.root.children) child.parent = null;\n tree.root.children = [];\n markStale(tree.root);\n },\n resetTextContent: () => {},\n commitTextUpdate: () => {},\n hideInstance: (instance) => {\n instance.hidden = true;\n markStale(instance);\n },\n unhideInstance: (instance) => {\n instance.hidden = false;\n markStale(instance);\n },\n hideTextInstance: () => {},\n unhideTextInstance: () => {},\n detachDeletedInstance: () => {},\n\n getInstanceFromNode: () => null,\n beforeActiveInstanceBlur: () => {},\n afterActiveInstanceBlur: () => {},\n prepareScopeUpdate: () => {},\n getInstanceFromScope: () => null,\n setCurrentUpdatePriority: (priority) => {\n currentUpdatePriority = priority;\n },\n getCurrentUpdatePriority: () => currentUpdatePriority,\n resolveUpdatePriority: () => (currentUpdatePriority !== 0 ? currentUpdatePriority : DefaultEventPriority),\n resetFormInstance: () => {},\n requestPostPaintCallback: () => {},\n shouldAttemptEagerTransition: () => false,\n trackSchedulerEvent: () => {},\n resolveEventType: () => null,\n resolveEventTimeStamp: () => -1.1,\n maySuspendCommit: () => false,\n maySuspendCommitOnUpdate: () => false,\n maySuspendCommitInSyncRender: () => false,\n suspendOnActiveViewTransition: () => {},\n getSuspendedCommitReason: () => null,\n bindToConsole: (methodName, args) => () => (console as unknown as Record<string, (...a: unknown[]) => unknown>)[methodName]?.(...args),\n preloadInstance: () => true,\n startSuspendingCommit: () => null,\n suspendInstance: () => {},\n waitForCommitToBeReady: () => null,\n NotPendingTransition: null,\n HostTransitionContext: createContext<null>(null) as unknown as Config['HostTransitionContext'],\n rendererVersion: '0.3.1',\n rendererPackageName: '@swiftbrowser/react',\n extraDevToolsConfig: null,\n};\n\n/**\n * The fiber's root container: `commitUpdate` needs the tree to retire an\n * element whose kind changed. React hands the fiber as the opaque handle.\n */\nfunction treeOf(handle: unknown): HostTree | null {\n let fiber = handle as { return: unknown; stateNode: unknown; tag: number } | null;\n while (fiber) {\n // HostRoot fibers (tag 3) hold the FiberRoot, whose containerInfo is our tree.\n if (fiber.tag === 3) return (fiber.stateNode as { containerInfo: HostTree }).containerInfo;\n fiber = fiber.return as typeof fiber;\n }\n return null;\n}\n\nexport const reconciler = Reconciler(hostConfig);\n","/**\n * A SwiftUI root: renders a React element tree into a stream of render ops.\n * The page gives the ops to a `Renderer` (@swiftbrowser/web) and feeds the\n * renderer's events back through `dispatch`; headless code (tests) records\n * the ops instead.\n */\n\nimport type { Animation, ColorScheme, DynamicTypeSize, Op, RendererEvent } from '@swiftbrowser/web/src/protocol';\nimport { createContext, createElement, type ReactNode } from 'react';\nimport { ConcurrentRoot } from 'react-reconciler/constants';\nimport { EnvironmentProvider, type Environment } from '../environment';\nimport { reconciler } from './reconciler';\nimport { HostTree, type HostTreeOptions, type OpsSink } from './tree';\n\nexport interface SwiftUIRoot {\n /** Render (or re-render) the tree; the ops of the pass reach the sink before this returns. */\n render(element: ReactNode): void;\n unmount(): void;\n /** A renderer event (a tap, a toggle…) for the element it names. */\n dispatch(event: RendererEvent): void;\n /** The device environment the tree reads through `useColorScheme` and friends. */\n setEnvironment(environment: Partial<Environment>): void;\n}\n\nconst DEFAULT_ENVIRONMENT: Environment = { colorScheme: 'light', dynamicTypeSize: 'large', horizontalSizeClass: 'compact', scenePhase: 'active', platform: 'ios' };\n\nconst roots = new Set<HostTree>();\n\n/** The tree a component renders into (`RemoteTree` stamps a child's animation on it). */\nexport const HostTreeContext = createContext<HostTree | null>(null);\n\nexport type SwiftUIRootOptions = HostTreeOptions;\n\n/**\n * A root whose ops reach `sink`. `remote: true` for a tree another root\n * draws through `RemoteTree` (`createRemoteRoot`), rather than a renderer.\n */\nexport function createSwiftUIRoot(sink: OpsSink, options: SwiftUIRootOptions = {}): SwiftUIRoot {\n const tree = new HostTree(sink, options);\n roots.add(tree);\n // The tenth argument is `onDefaultTransitionIndicator` from react-reconciler\n // 0.33 (React 19.2) and `transitionCallbacks` before it (an object the\n // stable build never reads): a no-op function serves both, and the\n // eleventh is ignored by every version the package supports.\n const container = reconciler.createContainer(\n tree,\n ConcurrentRoot,\n null,\n false,\n null,\n '',\n (error) => {\n throw error;\n },\n (error) => console.error(error),\n (error) => console.warn(error),\n () => {},\n null,\n );\n let environment = DEFAULT_ENVIRONMENT;\n let current: ReactNode = null;\n const update = (): void => {\n reconciler.updateContainerSync(createElement(HostTreeContext.Provider, { value: tree }, createElement(EnvironmentProvider, { value: environment }, current)), container, null, null);\n reconciler.flushSyncWork();\n };\n return {\n render(element) {\n current = element;\n update();\n },\n unmount() {\n reconciler.updateContainerSync(null, container, null, null);\n reconciler.flushSyncWork();\n roots.delete(tree);\n },\n dispatch(event) {\n // Updates the handler makes flush before this returns, like the Swift\n // core answers an event with the ops of its render pass.\n reconciler.flushSyncFromReconciler(() => tree.dispatch(event));\n },\n setEnvironment(next) {\n environment = { ...environment, ...next };\n update();\n },\n };\n}\n\nexport type { ColorScheme, DynamicTypeSize, Op };\n\n/**\n * Registers the reconciler with the React DevTools hook (`__REACT_DEVTOOLS_GLOBAL_HOOK__`)\n * when the page has one: DevTools then sees the SwiftUI tree, and React Fast\n * Refresh (whose runtime installs that hook) can refresh its components in\n * place. Call it before the first root; `react-dom` does the same for itself.\n */\nexport function injectIntoDevTools(): boolean {\n return reconciler.injectIntoDevTools() === true;\n}\n\n/** `AnimationCompletionCriteria`: when a `withAnimation` completion runs. */\nexport type AnimationCompletionCriteria = 'logicallyComplete' | 'removed';\n\nexport interface WithAnimationOptions {\n /**\n * `logicallyComplete` (the default) calls the completion when the\n * animation's duration has passed; `removed` once every effect of it is\n * gone (a spring's last settling included).\n */\n completionCriteria?: AnimationCompletionCriteria;\n}\n\nlet nextCompletionSerial = 1;\n\n/**\n * Stamps one tree's next `commit` with an animation (and a completion, whose\n * serial is answered), without a body: for a pass another root animated,\n * drawn here by `RemoteTree`. The stamp waits for the tree's next flush,\n * however late React runs it; `withAnimation` clears its stamps as its body\n * returns.\n */\nexport function stampNextCommit(tree: HostTree, animation: Animation, completion?: { criteria: AnimationCompletionCriteria; callback: () => void }): number {\n tree.pendingAnimation = animation;\n if (!completion) return 0;\n const serial = nextCompletionSerial++;\n tree.pendingCompletion = { serial, criteria: completion.criteria, callback: completion.callback, whenNothingDrawn: true };\n return serial;\n}\n\n/**\n * `withAnimation { }`: the state changes `body` makes render in one pass whose\n * `commit` carries the animation, so the renderer animates every frame and\n * style change of the pass. With a `completion`\n * (`withAnimation(_:completionCriteria:_:completion:)`) the renderer answers\n * once the pass has finished animating and the completion runs then; a body\n * that changes nothing to render runs it at once.\n */\nexport function withAnimation<T>(animation: Animation | undefined, body: () => T, completion?: () => void): T;\nexport function withAnimation<T>(animation: Animation | undefined, options: WithAnimationOptions, body: () => T, completion?: () => void): T;\nexport function withAnimation<T>(body: () => T): T;\nexport function withAnimation<T>(\n first: Animation | undefined | (() => T),\n second?: (() => T) | WithAnimationOptions,\n third?: (() => T) | (() => void),\n fourth?: () => void,\n): T {\n const animation: Animation = typeof first === 'function' ? { type: 'default' } : (first ?? { type: 'default' });\n let body: () => T;\n let completion: (() => void) | undefined;\n let criteria: AnimationCompletionCriteria = 'logicallyComplete';\n if (typeof first === 'function') {\n body = first;\n } else if (typeof second === 'function') {\n body = second;\n completion = third as (() => void) | undefined;\n } else {\n criteria = second?.completionCriteria ?? 'logicallyComplete';\n body = third as () => T;\n completion = fourth;\n }\n const serial = completion ? nextCompletionSerial++ : 0;\n for (const tree of roots) {\n tree.pendingAnimation = animation;\n if (completion) tree.pendingCompletion = { serial, criteria, callback: completion };\n }\n try {\n return reconciler.flushSyncFromReconciler(body);\n } finally {\n let committed = false;\n for (const tree of roots) {\n tree.pendingAnimation = undefined;\n tree.pendingCompletion = undefined;\n if (completion && tree.awaitsCompletion(serial)) committed = true;\n }\n // Nothing rendered, so nothing will animate: the completion runs now, as SwiftUI's does.\n if (completion && !committed) completion();\n }\n}\n","/**\n * A tree drawn by another root. `createRemoteRoot` keeps a mirror of the\n * elements a second SwiftUI root emits (one in a sandbox, a worker, another\n * runtime: anything that produces the ops protocol), and `RemoteTree` draws\n * the mirror as host elements inside a host tree, forwarding the events the\n * renderer sends those elements back to the root that owns them. Everything\n * stays synchronous: a tap mirrored to the child runs its handler, the\n * child's pass re-enters `applyOps`, and the host's own pass draws the result\n * before the tap returns.\n */\n\nimport type { Animation, Op, RendererEvent } from '@swiftbrowser/web/src/protocol';\nimport type { Environment } from '../environment';\nimport type { AddressedEvent, EventHandlers } from './instance';\nimport { stampNextCommit } from './root';\nimport type { HostTree } from './tree';\nimport { registerBitmapSourceOp } from '../bitmaps';\n\n/** An element of the child's tree as the mirror holds it. */\nexport interface MirrorNode {\n id: number;\n kind: string;\n props: Record<string, unknown>;\n children: MirrorNode[];\n parent: MirrorNode | null;\n}\n\nexport interface RemoteRoot {\n /** The child root's ops, one pass at a time (each ending in `commit`). */\n applyOps(ops: readonly Op[]): void;\n /** Where the events for the child's elements go: its root's `dispatch`. */\n onEvent(handler: (event: RendererEvent) => void): void;\n /** Where the host's environment goes: its root's `setEnvironment`. */\n onEnvironment(handler: (environment: Environment) => void): void;\n /** An event for the child (by the child's element id, or unaddressed). */\n dispatch(event: RendererEvent): void;\n setEnvironment(environment: Environment): void;\n /** For `useSyncExternalStore`: the version moves on every `commit`. */\n subscribe(listener: () => void): () => void;\n getVersion(): number;\n /** The mirror: element 0, whose children are the child's top-level elements (hoisted sheets and alerts last). */\n readonly root: MirrorNode;\n /** The mirrored element with that id (the child's own id), if it is there. */\n node(id: number): MirrorNode | undefined;\n /** What the child's root carries (a title with no screen of its own, a color scheme); `update` of element 0. */\n readonly rootProps: Record<string, unknown>;\n /** The handlers a mirrored element gets: every event forwarded to the child under the child's id. */\n handlersFor(id: number): EventHandlers;\n /** `RemoteTree` names the tree it draws into, so a child's animated pass animates that tree's. */\n attach(tree: HostTree | null): void;\n /** Forget the mirror and the handlers; the child root is the caller's to unmount. */\n dispose(): void;\n}\n\nexport function createRemoteRoot(): RemoteRoot {\n const root: MirrorNode = { id: 0, kind: 'root', props: {}, children: [], parent: null };\n const nodes = new Map<number, MirrorNode>([[0, root]]);\n const handlers = new Map<number, EventHandlers>();\n const listeners = new Set<() => void>();\n let version = 0;\n let rootProps: Record<string, unknown> = {};\n let eventHandler: ((event: RendererEvent) => void) | undefined;\n let environmentHandler: ((environment: Environment) => void) | undefined;\n let lastEnvironment: Environment | undefined;\n let hostTree: HostTree | null = null;\n\n const detach = (node: MirrorNode): void => {\n if (!node.parent) return;\n const siblings = node.parent.children;\n const at = siblings.indexOf(node);\n if (at >= 0) siblings.splice(at, 1);\n node.parent = null;\n };\n const forget = (node: MirrorNode): void => {\n nodes.delete(node.id);\n handlers.delete(node.id);\n for (const child of node.children) forget(child);\n };\n const notify = (): void => {\n version += 1;\n for (const listener of listeners) listener();\n };\n\n const remote: RemoteRoot = {\n applyOps(ops) {\n let commit: { animation?: Animation; completion?: number; completionCriteria?: 'logicallyComplete' | 'removed' } | null = null;\n for (const op of ops) {\n switch (op.op) {\n case 'create': {\n if (nodes.has(op.id)) throw new Error(`remote tree: element ${op.id} created twice`);\n nodes.set(op.id, { id: op.id, kind: op.kind, props: op.props as Record<string, unknown>, children: [], parent: null });\n break;\n }\n case 'update': {\n if (op.id === 0) {\n rootProps = op.props as Record<string, unknown>;\n break;\n }\n const node = nodes.get(op.id);\n if (!node) throw new Error(`remote tree: update of unknown element ${op.id}`);\n node.props = op.props as Record<string, unknown>;\n break;\n }\n case 'insert': {\n const node = nodes.get(op.id);\n const parent = nodes.get(op.parent);\n if (!node || !parent) throw new Error(`remote tree: insert of ${op.id} into ${op.parent}: unknown element`);\n detach(node);\n parent.children.splice(op.index, 0, node);\n node.parent = parent;\n break;\n }\n case 'remove': {\n const node = nodes.get(op.id);\n if (!node) break;\n detach(node);\n forget(node);\n break;\n }\n case 'commit':\n commit = op;\n break;\n case 'imagedata':\n // A bitmap source: kept here, so the host's tree sends it before the first image that draws it.\n registerBitmapSourceOp(op);\n break;\n default:\n // `defaults`, `request`, `swiftdata`: the child has no loader here.\n break;\n }\n }\n if (!commit) return;\n const { animation, completion, completionCriteria } = commit;\n const answer = completion === undefined ? undefined : (): void => remote.dispatch({ type: 'animationcomplete', serial: completion });\n if (animation && hostTree) {\n // The host's pass carries the child's animation; the renderer's `animationcomplete` for it answers the child's serial.\n stampNextCommit(hostTree, animation, answer && { criteria: completionCriteria ?? 'logicallyComplete', callback: answer });\n notify();\n return;\n }\n notify();\n answer?.();\n },\n node(id) {\n return nodes.get(id);\n },\n onEvent(handler) {\n eventHandler = handler;\n },\n onEnvironment(handler) {\n environmentHandler = handler;\n if (lastEnvironment) handler(lastEnvironment);\n },\n dispatch(event) {\n eventHandler?.(event);\n },\n setEnvironment(environment) {\n if (\n lastEnvironment &&\n lastEnvironment.colorScheme === environment.colorScheme &&\n lastEnvironment.dynamicTypeSize === environment.dynamicTypeSize &&\n lastEnvironment.horizontalSizeClass === environment.horizontalSizeClass &&\n lastEnvironment.scenePhase === environment.scenePhase &&\n lastEnvironment.platform === environment.platform\n )\n return;\n lastEnvironment = environment;\n environmentHandler?.(environment);\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n getVersion: () => version,\n get root() {\n return root;\n },\n get rootProps() {\n return rootProps;\n },\n attach(tree) {\n hostTree = tree;\n },\n handlersFor(id) {\n let on = handlers.get(id);\n if (!on) {\n on = { '*': (event: AddressedEvent) => remote.dispatch({ ...event, id } as RendererEvent) };\n handlers.set(id, on);\n }\n return on;\n },\n dispose() {\n root.children = [];\n nodes.clear();\n nodes.set(0, root);\n handlers.clear();\n listeners.clear();\n eventHandler = undefined;\n environmentHandler = undefined;\n hostTree = null;\n },\n };\n return remote;\n}\n","import { createElement, type ReactElement, type ReactNode } from 'react';\nimport type { EventHandlers, HoistTarget, HostProps } from './instance';\n\n/** A host element: the intrinsic `sb` with a protocol kind and props. */\nexport function sb(\n kind: string,\n props?: Record<string, unknown>,\n on?: EventHandlers,\n children?: ReactNode,\n target?: HoistTarget,\n): ReactElement {\n const hostProps: HostProps = { kind };\n if (props) hostProps.props = props;\n if (on) hostProps.on = on;\n if (target) hostProps.target = target;\n return children === undefined ? createElement('sb', hostProps) : createElement('sb', hostProps, children);\n}\n","/**\n * The environment a presentation carries. SwiftUI's sheets, full-screen\n * covers and popovers inherit the environment of the view that presents\n * them: a `.defaultMinListRowHeight`, `.font` or `.tint` set around it\n * reaches the lists and text inside the sheet. Here a presentation is drawn\n * at the root, away from the `styled` wrappers around its presenter, so the\n * modifiers that set such values also record them in a React context\n * (outermost first), and a presentation replays them around its content.\n */\n\nimport type { Style } from '@swiftbrowser/web/src/protocol';\nimport { createContext, createElement, isValidElement, useContext, useMemo, type ReactElement, type ReactNode } from 'react';\nimport { sb } from './host/sb';\n\n/** The `styled` modifiers whose values are environment values a presentation inherits. */\nexport const INHERITED_STYLE_KEYS: ReadonlySet<string> = new Set([\n 'font',\n 'fontWeight',\n 'bold',\n 'monospacedDigit',\n 'tint',\n 'lineLimit',\n 'multilineTextAlignment',\n 'imageScale',\n 'defaultMinListRowHeight',\n]);\n\n/** The modifiers that present their content at the root (and so take the inherited styles with them). */\nexport const PRESENTATION_KEYS: ReadonlySet<string> = new Set(['sheet', 'fullScreenCover', 'popover']);\n\n/** The inherited styles set around this point, outermost first. */\nexport const InheritedStylesContext = createContext<readonly Style[]>([]);\n\nexport function useInheritedStyles(): readonly Style[] {\n return useContext(InheritedStylesContext);\n}\n\n/** The style of a `styled` element (`{}` for anything else). */\nexport function styleOf(node: ReactNode): Style {\n if (!isValidElement<{ kind?: unknown; props?: { style?: Style } }>(node) || node.props.kind !== 'styled') return {};\n return node.props.props?.style ?? {};\n}\n\n/** `children`, with `style` added to the inherited styles below it (an empty style adds nothing). */\nexport function InheritStyle({ style, children }: { style: Style; children?: ReactNode }): ReactNode {\n const parent = useContext(InheritedStylesContext);\n // A new style object each render with the same values keeps the list, so the views below that read it don't render again.\n const key = JSON.stringify(style);\n const value = useMemo(() => (key === '{}' ? parent : [...parent, style]), [parent, key]);\n return createElement(InheritedStylesContext.Provider, { value }, children);\n}\n\n/**\n * `content` inside `styles` (outermost first), as `styled` wrappers, and\n * with them as its inherited styles; `content` itself when there are none.\n */\nexport function replayStyles(styles: readonly Style[], content: ReactNode): ReactNode {\n if (styles.length === 0) return content;\n const provided = createElement(InheritedStylesContext.Provider, { value: styles }, content);\n return styles.reduceRight<ReactNode>((child, style): ReactElement => sb('styled', { style }, undefined, child), provided);\n}\n","import { createContext, useContext, type ReactNode } from 'react';\n\n/** What a `NavigationStack` offers the views inside it. */\nexport interface NavigationContextValue {\n push(value: unknown): void;\n pop(): void;\n /** The pushed values, and replacing them whole: how a `RemoteTree` keeps another root's stack in step with this one. */\n path: readonly unknown[];\n setPath(path: readonly unknown[]): void;\n /** `.navigationDestination(for:)`: how a pushed value becomes a screen. */\n registerDestination(destination: (value: unknown) => ReactNode): void;\n}\n\nexport const NavigationContext = createContext<NavigationContextValue | null>(null);\n\n/** The depth of the stack screen a view is in: 0 for the root screen, 1 for the first pushed one. */\nexport const ScreenDepthContext = createContext(0);\n\nexport function useScreenDepth(): number {\n return useContext(ScreenDepthContext);\n}\n\nexport function useNavigation(): NavigationContextValue | null {\n return useContext(NavigationContext);\n}\n\n/** Rendered by the `navigationDestination` modifier: registers the builder with the enclosing stack. */\nexport function RegisterDestination({ destination }: { destination: (value: never) => ReactNode }): null {\n const navigation = useContext(NavigationContext);\n navigation?.registerDestination(destination as (value: unknown) => ReactNode);\n return null;\n}\n","/**\n * `RemoteTree`: another root's tree drawn here. The child root (made with\n * `createSwiftUIRoot(sink, { remote: true })` wherever it runs) sends its\n * ops to a `RemoteRoot`'s `applyOps`; this component draws the mirror as\n * host elements, so the child's views take part in this tree's layout, its\n * screen and its renderer, web or native alike. What a child hoists to its\n * root for lack of a screen of its own joins this tree's enclosing screen\n * (a title, a toolbar, a search field) or root (a sheet, an alert).\n *\n * A child's `NavigationStack` becomes this tree's: inside a host stack, the\n * child's root screen is drawn in place (its title and toolbar on the host's\n * screen) and each screen the child pushes is pushed onto the host's stack,\n * so the child's screens slide in, get the host's back button and swipe,\n * and show in its bar like the host's own. The child's path stays the\n * truth: a push or pop in the child pushes or pops the host's screens, and\n * a pop in the host (back, swipe, a tap on an earlier screen) is sent to the\n * child as the renderer would send it (a `tap` on the popped screen), which\n * pops the child's path.\n */\n\nimport type { Style } from '@swiftbrowser/web/src/protocol';\nimport { createElement, Fragment, useContext, useLayoutEffect, useRef, useSyncExternalStore, type ReactNode } from 'react';\nimport { EnvironmentContext } from '../environment';\nimport { HOIST_KIND, PREF_KIND } from '../host/instance';\nimport type { MirrorNode, RemoteRoot } from '../host/remote';\nimport { HostTreeContext } from '../host/root';\nimport { sb } from '../host/sb';\nimport { replayStyles, useInheritedStyles } from '../inheritedStyle';\nimport { useNavigation, useScreenDepth } from '../navigation-context';\n\n/** The host's view for an element kind of the child's own: its props as the child set them, and its children drawn as usual. */\nexport type HostElementRenderer = (props: Readonly<Record<string, unknown>>, children: ReactNode) => ReactNode;\n\nexport interface RemoteTreeProps {\n root: RemoteRoot;\n /**\n * The host's own views for element kinds the child makes up (a\n * `HostElement`'s `kind`, `'app:preview'` say), by kind: the host draws\n * each as it likes where the child put it, with the props the child gave\n * it. A kind no host draws is left to the renderer, which draws nothing\n * for it.\n */\n elements?: Readonly<Record<string, HostElementRenderer>>;\n /**\n * The child's stack's path to open with, as its screens' `route`s name it\n * (a link to one of the child's screens): set once, when the child's stack\n * first shows, so the child's destinations build the screens.\n */\n initialPath?: readonly unknown[];\n}\n\n/** The props a child's `navigationTitle` and friends leave on its root or its screens, lifted to this tree's screen. */\nconst SCREEN_PROPS = ['title', 'subtitle', 'displayMode', 'toolbarRole', 'navigationBarHidden', 'bottomBarHidden', 'statusBarHidden'];\n\n/** What the child left on a root or a screen for the host's screen: a screen's defaults (no title, `automatic`) are not choices. */\nfunction screenPrefs(props: Record<string, unknown>, key: string): ReactNode {\n const picked: Record<string, unknown> = {};\n for (const name of SCREEN_PROPS) if (name in props) picked[name] = props[name];\n if (picked['title'] === '') delete picked['title'];\n if (picked['displayMode'] === 'automatic') delete picked['displayMode'];\n return Object.keys(picked).length ? createElement(Fragment, { key }, sb(PREF_KIND, picked, undefined, undefined, 'navscreen')) : null;\n}\n\n/** The child's stack that becomes the host's: its first, outside sheets and alerts (which present their own). */\nfunction findStack(node: MirrorNode): MirrorNode | null {\n for (const child of node.children) {\n if (child.kind === 'sheet' || child.kind === 'alert') continue;\n if (child.kind === 'navstack') return child;\n const found = findStack(child);\n if (found) return found;\n }\n return null;\n}\n\nconst screensOf = (stack: MirrorNode | null): MirrorNode[] => (stack ? stack.children.filter((child) => child.kind === 'navscreen') : []);\n\ntype Elements = Readonly<Record<string, HostElementRenderer>> | undefined;\n\nfunction renderNode(root: RemoteRoot, node: MirrorNode, stack: MirrorNode | null, elements: Elements): ReactNode {\n // A `host` element's DOM lives in the child's page, which has none here.\n if (node.kind === 'host') return null;\n if (node === stack) {\n const first = screensOf(stack)[0];\n return createElement(Fragment, { key: node.id }, first ? renderScreen(root, first, stack, elements) : null);\n }\n const children = node.children.length ? node.children.map((child) => renderNode(root, child, stack, elements)) : undefined;\n // A kind of the child's own, drawn by the host.\n const own = elements && Object.prototype.hasOwnProperty.call(elements, node.kind) ? elements[node.kind] : undefined;\n if (own) return createElement(Fragment, { key: node.id }, own(node.props, children));\n return createElement(Fragment, { key: node.id }, sb(node.kind, node.props, root.handlersFor(node.id), children));\n}\n\n/** A child's sheet, its content inside the host's inherited styles (`inheritedStyle.ts`). */\nfunction renderSheet(root: RemoteRoot, node: MirrorNode, stack: MirrorNode | null, inherited: readonly Style[], elements: Elements): ReactNode {\n const children = node.children.map((child) => renderNode(root, child, stack, elements));\n return createElement(Fragment, { key: node.id }, sb(node.kind, node.props, root.handlersFor(node.id), replayStyles(inherited, children)));\n}\n\n/** A child's screen drawn in the host's: its views in place, its title on the host's screen, its toolbar and search field in the host's bar. */\nfunction renderScreen(root: RemoteRoot, screen: MirrorNode, stack: MirrorNode | null, elements: Elements): ReactNode {\n const out: ReactNode[] = [screenPrefs(screen.props, '$screen')];\n for (const child of screen.children) {\n const drawn = renderNode(root, child, stack, elements);\n if (child.kind === 'toolbar' || child.kind === 'searchfield') out.push(createElement(Fragment, { key: child.id }, sb(HOIST_KIND, undefined, undefined, drawn, 'navscreen')));\n else out.push(drawn);\n }\n return createElement(Fragment, null, ...out);\n}\n\n/** A screen the child pushed, as the host's stack shows it. */\nfunction RemoteScreen({ root, id, elements }: { root: RemoteRoot; id: number; elements: Elements }): ReactNode {\n useSyncExternalStore(root.subscribe, root.getVersion, root.getVersion);\n const screen = root.node(id);\n // Popped in the child: the host pops it next.\n if (!screen?.parent) return null;\n return renderScreen(root, screen, findStack(root.root), elements);\n}\n\n/**\n * A value on the host's path standing for one of the child's screens (a\n * pushed view, as `NavigationLink(destination:)` pushes), with the child's\n * value for it as plain data when it has one (`route`): what the host's\n * URL can name it by, and `initialPath` takes back.\n */\nexport interface PushedScreen {\n view: ReactNode;\n route?: unknown;\n}\n\nexport function RemoteTree({ root, initialPath, elements }: RemoteTreeProps): ReactNode {\n useSyncExternalStore(root.subscribe, root.getVersion, root.getVersion);\n const environment = useContext(EnvironmentContext);\n // The host's environment around this tree, which the child's sheets inherit as the child's own views do.\n const inherited = useInheritedStyles();\n const tree = useContext(HostTreeContext);\n const navigation = useNavigation();\n const depth = useScreenDepth();\n useLayoutEffect(() => {\n root.attach(tree);\n return () => root.attach(null);\n }, [root, tree]);\n useLayoutEffect(() => {\n root.setEnvironment(environment);\n }, [root, environment]);\n\n // Only inside a host stack does the child's become the host's; elsewhere it is drawn as it is.\n const stack = navigation ? findStack(root.root) : null;\n const pushed = screensOf(stack).slice(1);\n // A screen is the same value while it is the same element with the same route; a new route (a screen\n // replaced in place) is a new value, so the host's path (its URL) follows.\n const values = useRef(new Map<string, PushedScreen>());\n const ours = useRef(new WeakSet<object>());\n const lastPushed = useRef<string[]>([]);\n const keyOf = (screen: MirrorNode): string => `${screen.id}:${JSON.stringify(screen.props['route'] ?? null)}`;\n const valueFor = (screen: MirrorNode): PushedScreen => {\n const key = keyOf(screen);\n let value = values.current.get(key);\n if (!value) {\n value = 'route' in screen.props ? { view: <RemoteScreen root={root} id={screen.id} elements={elements} />, route: screen.props['route'] } : { view: <RemoteScreen root={root} id={screen.id} elements={elements} /> };\n values.current.set(key, value);\n ours.current.add(value);\n }\n return value;\n };\n\n // A link's path, given to the child's stack once it shows (and before it has pushed anything of its own).\n const restored = useRef(false);\n useLayoutEffect(() => {\n if (restored.current) return;\n const childStack = findStack(root.root);\n if (!childStack) return;\n restored.current = true;\n if (initialPath?.length && screensOf(childStack).length === 1) root.dispatch({ type: 'setpath', id: childStack.id, path: [...initialPath] });\n });\n\n useLayoutEffect(() => {\n if (!navigation) return;\n const keys = pushed.map(keyOf);\n const wanted = pushed.map(valueFor);\n for (const key of values.current.keys()) if (!keys.includes(key)) values.current.delete(key);\n // The host's path from this screen on: the child's screens first, then whatever the host pushed over them.\n const tail = navigation.path.slice(depth);\n let shown = 0;\n while (shown < tail.length && typeof tail[shown] === 'object' && tail[shown] !== null && ours.current.has(tail[shown] as object)) shown += 1;\n const childMoved = keys.length !== lastPushed.current.length || keys.some((key, i) => key !== lastPushed.current[i]);\n lastPushed.current = keys;\n if (!childMoved && shown < wanted.length && tail.slice(0, shown).every((value, i) => value === wanted[i])) {\n // The host popped some of the child's screens (back, swipe): the child pops to the same place.\n root.dispatch({ type: 'tap', id: pushed[shown]!.id });\n return;\n }\n if (shown === wanted.length && wanted.every((value, i) => tail[i] === value)) return;\n // The child pushed or popped: the host's path follows. Screens the host pushed over the child's stay while the child's are unchanged.\n navigation.setPath([...navigation.path.slice(0, depth), ...wanted]);\n });\n\n const out: ReactNode[] = [screenPrefs(root.rootProps, '$root')];\n if ('colorScheme' in root.rootProps)\n out.push(createElement(Fragment, { key: '$scheme' }, sb(PREF_KIND, { colorScheme: root.rootProps['colorScheme'] }, undefined, undefined, 'root')));\n for (const child of root.root.children) {\n const drawn = child.kind === 'sheet' && inherited.length > 0 ? renderSheet(root, child, stack, inherited, elements) : renderNode(root, child, stack, elements);\n if (child.kind === 'sheet' || child.kind === 'alert') out.push(createElement(Fragment, { key: child.id }, sb(HOIST_KIND, undefined, undefined, drawn, 'root')));\n else if (child.kind === 'toolbar' || child.kind === 'searchfield') out.push(createElement(Fragment, { key: child.id }, sb(HOIST_KIND, undefined, undefined, drawn, 'navscreen')));\n else out.push(drawn);\n }\n return createElement(Fragment, null, ...out);\n}\n","/**\n * A `Binding<T>`: a `useState` pair, so `isOn={[downloads, setDownloads]}`\n * reads like `isOn: $downloads`. A plain value with an `onChange` handler is\n * accepted everywhere a binding is.\n */\nexport type Binding<T> = readonly [T, (value: T) => void];\n\nexport type BindingValue<T> = Binding<T> | T;\n\nexport function readBinding<T>(value: BindingValue<T>, onChange?: (value: T) => void): [T, (next: T) => void] {\n if (Array.isArray(value) && value.length === 2 && typeof value[1] === 'function') {\n const [current, set] = value as Binding<T>;\n return [current, set];\n }\n return [value as T, onChange ?? (() => {})];\n}\n","/**\n * `.draggable` and `.dropDestination`. What is dragged stays in React: a\n * lift (`dragstart`) remembers the payload, a drop naming its source hands\n * it to the destination, and `dragend` forgets it. Drops from outside the\n * page arrive as text and files.\n */\n\nimport { browserEnvironment } from '@swiftbrowser/web/src/hostRequests';\nimport type { DropItem } from '@swiftbrowser/web/src/protocol';\nimport type { ReactNode } from 'react';\nimport { sb } from './host/sb';\nimport type { DropDestinationModifier } from './modifiers';\n\nlet active: { id: number; payload: unknown } | null = null;\n\nexport function Draggable({ payload, children }: { payload: unknown; children?: ReactNode }): ReactNode {\n return sb(\n 'draggable',\n {},\n {\n dragstart: (event) => {\n active = { id: event.id, payload };\n },\n dragend: (event) => {\n if (active?.id === event.id) active = null;\n },\n },\n children,\n );\n}\n\n/**\n * Text as a string, a link as a `URL`, a file as a `File`: the browser's own\n * (a page's drops carry it by reference), one the native host left on disk\n * (read on demand), or one built from the bytes the event carried. A file\n * from a dropped folder is named by its path in it, the folder's name first\n * (`Photos/2025/a.jpg`), as `fileImporter` names a picked folder's files.\n */\nfunction itemValue(item: DropItem): unknown {\n if (item.text !== undefined) {\n if (item.type === 'text/uri-list') {\n try {\n return new URL(item.text.split(/\\r?\\n/)[0]!.trim());\n } catch {\n return item.text;\n }\n }\n return item.text;\n }\n const name = item.path ?? item.name ?? 'file';\n if (item.file) {\n const file = item.file;\n return item.path !== undefined && item.path !== file.name ? new File([file], item.path, { type: file.type, lastModified: file.lastModified }) : file;\n }\n if (item.url !== undefined && item.data === undefined) {\n const fromReference = browserEnvironment.fileFromReference;\n if (fromReference) {\n return fromReference({ type: item.type, name, url: item.url, ...(item.path !== undefined ? { path: item.path } : {}), ...(item.size !== undefined ? { size: item.size } : {}) });\n }\n }\n const binary = atob(item.data ?? '');\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return typeof File !== 'undefined' ? new File([bytes], name, { type: item.type }) : bytes;\n}\n\nexport function DropDestination({ action, isTargeted, accepts, children }: DropDestinationModifier & { children?: ReactNode }): ReactNode {\n return sb(\n 'dropdestination',\n { accepts: accepts ?? [] },\n {\n drop: (event) => {\n if (event.phase === 'entered') {\n isTargeted?.(true);\n return;\n }\n isTargeted?.(false);\n if (event.phase !== 'performed') return;\n let items: unknown[];\n if (event.source !== undefined) items = active && active.id === event.source ? [active.payload] : [];\n else items = (event.items ?? []).map(itemValue);\n if (items.length > 0) action(items, { x: event.x, y: event.y });\n },\n },\n children,\n );\n}\n","/**\n * `.fileImporter(isPresented:allowedContentTypes:…)`: the browser's file\n * chooser in place of the Files app. A browser opens a chooser only within a\n * tap; a tap's state changes render before its event returns (host/root.ts),\n * so the layout effect that sees `isPresented` turn true opens it in time.\n * Set `isPresented` from a button's action. `onCompletion` gets the chosen\n * `File`s; a dismissed chooser calls `onCancellation` instead, as on iOS.\n */\n\nimport { browserEnvironment } from '@swiftbrowser/web/src/hostRequests';\nimport { useLayoutEffect, useRef, type ReactNode } from 'react';\nimport { readBinding, type BindingValue } from './binding';\n\nexport interface FileImporterModifier {\n isPresented: BindingValue<boolean>;\n /**\n * What the chooser offers (its `accept`): MIME types, patterns (`image/*`) or extensions (`.svg`); any file when\n * empty. `'public.folder'` (SwiftUI's `.folder`) makes it a folder chooser: `onCompletion` then gets the folder's\n * files, at any depth, that the other types allow, each named by its path from the folder, the folder's name first\n * (`Bank/Leads/Saw.fxp`).\n */\n allowedContentTypes: string[];\n allowsMultipleSelection?: boolean;\n onCompletion: (files: File[]) => void;\n onCancellation?: () => void;\n}\n\nexport function FileImporterPresenter(spec: FileImporterModifier): ReactNode {\n const [presented, setPresented] = readBinding(spec.isPresented);\n const latest = useRef(spec);\n latest.current = spec;\n const choosing = useRef(false);\n useLayoutEffect(() => {\n if (!presented || choosing.current) return;\n const { allowedContentTypes, allowsMultipleSelection } = latest.current;\n const pick = browserEnvironment.pickFiles;\n if (!pick) {\n setPresented(false);\n latest.current.onCancellation?.();\n return;\n }\n choosing.current = true;\n void pick({ accept: allowedContentTypes.join(','), multiple: allowsMultipleSelection === true }).then((files) => {\n choosing.current = false;\n setPresented(false);\n if (files.length > 0) latest.current.onCompletion(files);\n else latest.current.onCancellation?.();\n });\n }, [presented, setPresented]);\n return null;\n}\n","/**\n * `.fileExporter(isPresented:document:contentType:defaultFilename:…)`: the\n * document goes where the viewer chooses. A page shows a save dialog where\n * the browser has one (the File System Access API) and downloads the file\n * elsewhere; the native app shows the document picker (the Files app). Set\n * `isPresented` from a button's action, as a dialog opens only within a tap.\n * `onCompletion` gets where it went (`saved` or `downloaded`, with the\n * host's URLs where it knows them); a dismissed dialog calls `onCancellation`.\n */\n\nimport { exportFiles, type ExportFilesResult } from '@swiftbrowser/web/src/hostRequests';\nimport { useLayoutEffect, useRef, type ReactNode } from 'react';\nimport { readBinding, type BindingValue } from './binding';\n\nexport type { ExportFilesResult };\n\n/** What a `fileExporter` writes: text, bytes or a Blob; a `File` brings its own name and type. */\nexport type ExportDocument = string | Uint8Array | ArrayBuffer | Blob;\n\nexport interface FileExporterModifier {\n isPresented: BindingValue<boolean>;\n /** The document, or several; `null` presents nothing (the exporter closes at once). */\n document: ExportDocument | ExportDocument[] | null;\n /** The MIME type (`text/plain`), for a document that is not a typed Blob. */\n contentType?: string;\n /** The name offered (`Notes.txt`); the type's extension is added when the name has none. `Untitled` by default. */\n defaultFilename?: string;\n onCompletion?: (result: ExportFilesResult) => void;\n onCancellation?: () => void;\n onError?: (error: unknown) => void;\n}\n\nconst EXTENSIONS: Record<string, string> = {\n 'text/plain': 'txt',\n 'text/csv': 'csv',\n 'text/markdown': 'md',\n 'text/html': 'html',\n 'application/json': 'json',\n 'application/pdf': 'pdf',\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/svg+xml': 'svg',\n 'audio/mp4': 'm4a',\n 'video/mp4': 'mp4',\n};\n\n/** The file a document is exported as: named, typed, with the type's extension when the name has none. */\nexport function exportFile(document: ExportDocument, contentType: string | undefined, defaultFilename: string | undefined, index = 0): File {\n const type = (document instanceof Blob && document.type) || contentType || 'application/octet-stream';\n let name = defaultFilename ?? (document instanceof File ? document.name : index === 0 ? 'Untitled' : `Untitled ${index + 1}`);\n name = name.replace(/[\\\\/:*?\"<>|]+/g, '-').trim() || 'Untitled';\n const extension = EXTENSIONS[type.split(';')[0]!.trim()];\n if (extension && !/\\.[A-Za-z0-9]{1,8}$/.test(name)) name = `${name}.${extension}`;\n if (document instanceof File && document.name === name && document.type === type) return document;\n const bytes = typeof document === 'string' ? new TextEncoder().encode(document) : document;\n return new File([bytes as BlobPart], name, { type });\n}\n\nexport function FileExporterPresenter(spec: FileExporterModifier): ReactNode {\n const [presented, setPresented] = readBinding(spec.isPresented);\n const latest = useRef(spec);\n latest.current = spec;\n const exporting = useRef(false);\n useLayoutEffect(() => {\n if (!presented || exporting.current) return;\n const { document, contentType, defaultFilename } = latest.current;\n const documents = document === null ? [] : Array.isArray(document) ? document : [document];\n if (documents.length === 0) {\n setPresented(false);\n latest.current.onCancellation?.();\n return;\n }\n exporting.current = true;\n const files = documents.map((item, index) => exportFile(item, contentType, defaultFilename, index));\n exportFiles(files).then(\n (result) => {\n exporting.current = false;\n setPresented(false);\n if (result.outcome === 'cancelled') latest.current.onCancellation?.();\n else latest.current.onCompletion?.(result);\n },\n (error: unknown) => {\n exporting.current = false;\n setPresented(false);\n latest.current.onError?.(error);\n },\n );\n }, [presented, setPresented]);\n return null;\n}\n","/**\n * List rows that can be selected or deleted are wrapped in a `listrow`\n * (docs/ops-protocol.md, \"Edit mode and list selection\"). `ForEach`'s\n * `onDelete` and a `List`'s `selection` both end in this component; a row\n * that is neither selectable nor deletable renders bare.\n */\n\nimport { createContext, useContext, type ReactNode } from 'react';\nimport { sb } from '../host/sb';\n\nexport interface ListSelection {\n isSelected(tag: unknown): boolean;\n select(tag: unknown): void;\n editing: boolean;\n}\n\nexport const ListSelectionContext = createContext<ListSelection | null>(null);\n\nexport interface RowProps {\n /** The row's tag (`.tag`, a `NavigationLink` value or a `ForEach` id). */\n tag?: unknown;\n /** `ForEach` with `onDelete`: what a swipe or the edit-mode minus does. */\n onDelete?: () => void;\n deletable?: boolean;\n /**\n * `ForEach` with `onMove`: called with the destination offset in the\n * `ForEach`'s data (as `move(fromOffsets:toOffset:)` takes it) when the\n * row was dragged to a new place.\n */\n onMove?: (to: number) => void;\n movable?: boolean;\n /** The row's offset in its `ForEach`. */\n index?: number;\n /** The row's index among its container's children (set by `List` / `Section`), for mapping `move`. */\n containerIndex?: number;\n children?: ReactNode;\n}\n\nexport function Row({ tag, onDelete, deletable, onMove, movable, index, containerIndex, children }: RowProps): ReactNode {\n const selection = useContext(ListSelectionContext);\n const selectable = selection !== null && tag !== undefined;\n const canDelete = onDelete !== undefined && deletable !== false;\n const canMove = onMove !== undefined && movable !== false;\n if (!selectable && !canDelete && !canMove) return children;\n const props: Record<string, unknown> = {};\n if (selectable) {\n props['selectable'] = true;\n props['selected'] = selection.isSelected(tag);\n }\n if (canDelete) props['deletable'] = true;\n if (canMove) props['movable'] = true;\n return sb(\n 'listrow',\n props,\n {\n tap: () => selectable && selection.select(tag),\n delete: () => onDelete?.(),\n move: (event) => {\n // `to` counts the container's children; the ForEach's first row is\n // `containerIndex - index` children in.\n const start = (containerIndex ?? index ?? 0) - (index ?? 0);\n onMove?.(Math.max(0, event.to - start));\n },\n },\n children,\n );\n}\n","/**\n * Value types of the SwiftUI API as plain data: colors and shape styles,\n * fonts, frames, insets and gradients, encoded as the ops protocol wants them.\n */\n\nimport type {\n Color as ProtocolColor,\n EdgeInsets,\n Font as ProtocolFont,\n FontDesign,\n FontWeight,\n Frame,\n FrameAlignment,\n GradientStop,\n NamedColor,\n RGBAColor,\n SemanticColorName,\n ShapeStyle,\n TextStyle,\n UnitPoint,\n} from '@swiftbrowser/web/src/protocol';\n\nexport type { EdgeInsets, FontDesign, FontWeight, Frame, FrameAlignment, ShapeStyle, TextStyle, UnitPoint };\n/** The protocol's color value (the `Color` export is the view, with the color helpers as members). */\nexport type ColorType = ProtocolColor;\n/** The protocol's font value (the `Font` export is the helper object). */\nexport type FontType = ProtocolFont;\n\n// ---------------------------------------------------------------------------\n// Colors and shape styles\n// ---------------------------------------------------------------------------\n\n/** `.primary` … `.quaternary` as foreground styles (the label colors) or fills. */\nexport type HierarchyName = 'primary' | 'secondary' | 'tertiary' | 'quaternary';\n\n/**\n * A style as a prop: a protocol value, or a name. A hierarchy name\n * (`\"secondary\"`) is the hierarchical style, as `.foregroundStyle(.secondary)`\n * is; a palette or UIKit name (`\"red\"`, `\"secondarySystemBackground\"`) is that\n * semantic color; `\"white\"`, `\"black\"` and `\"#rrggbb[aa]\"` are explicit colors.\n */\nexport type StyleValue = ShapeStyle | HierarchyName | SemanticColorName | 'white' | 'black' | `#${string}`;\n\nconst HIERARCHY: Record<HierarchyName, 1 | 2 | 3 | 4> = { primary: 1, secondary: 2, tertiary: 3, quaternary: 4 };\n\nexport function rgb(r: number, g: number, b: number, a = 1): RGBAColor {\n return { r, g, b, a };\n}\n\nexport function hex(value: string): RGBAColor {\n const digits = value.replace('#', '');\n const wide = digits.length === 3 || digits.length === 4 ? [...digits].map((d) => d + d).join('') : digits;\n const n = (at: number): number => parseInt(wide.slice(at, at + 2), 16) / 255;\n return { r: n(0), g: n(2), b: n(4), a: wide.length >= 8 ? n(6) : 1 };\n}\n\nexport function shapeStyle(value: StyleValue): ShapeStyle {\n if (typeof value !== 'string') return value;\n if (value in HIERARCHY) return { hierarchical: HIERARCHY[value as HierarchyName] };\n if (value === 'white') return rgb(1, 1, 1);\n if (value === 'black') return rgb(0, 0, 0);\n if (value.startsWith('#')) return hex(value);\n return { name: value as SemanticColorName };\n}\n\n/** A color as a prop: a protocol color or a name (hierarchy names are not colors). */\nexport type ColorValue = ProtocolColor | SemanticColorName | 'white' | 'black' | `#${string}`;\n\nexport function color(value: ColorValue): ProtocolColor {\n return shapeStyle(value as StyleValue) as ProtocolColor;\n}\n\n/** `color.opacity(a)` */\nexport function opacity(value: ColorValue, a: number): ProtocolColor;\nexport function opacity(value: StyleValue, a: number): ShapeStyle;\nexport function opacity(value: StyleValue, a: number): ShapeStyle {\n const style = shapeStyle(value);\n if ('r' in style) return { ...style, a: style.a * a };\n if ('name' in style) return { ...style, a: ((style as NamedColor).a ?? 1) * a };\n if ('named' in style) return { ...style, opacity: style.opacity * a };\n return { ...style, opacity: ((style as { opacity?: number }).opacity ?? 1) * a };\n}\n\n/** `color.gradient`: the subtle vertical gradient iOS derives from a color. */\nexport function gradient(value: ColorValue): ShapeStyle {\n return { colorGradient: color(value) };\n}\n\n/** `Color.red`, `Color.white`, `Color(.secondarySystemBackground)`… (`Color` itself, a view, carries these as members). */\nexport const ColorValues = {\n red: { name: 'red' } as ProtocolColor,\n orange: { name: 'orange' } as ProtocolColor,\n yellow: { name: 'yellow' } as ProtocolColor,\n green: { name: 'green' } as ProtocolColor,\n mint: { name: 'mint' } as ProtocolColor,\n teal: { name: 'teal' } as ProtocolColor,\n cyan: { name: 'cyan' } as ProtocolColor,\n blue: { name: 'blue' } as ProtocolColor,\n indigo: { name: 'indigo' } as ProtocolColor,\n purple: { name: 'purple' } as ProtocolColor,\n pink: { name: 'pink' } as ProtocolColor,\n brown: { name: 'brown' } as ProtocolColor,\n gray: { name: 'gray' } as ProtocolColor,\n white: rgb(1, 1, 1) as ProtocolColor,\n black: rgb(0, 0, 0) as ProtocolColor,\n clear: { name: 'clear' } as ProtocolColor,\n primary: { name: 'primary' } as ProtocolColor,\n secondary: { name: 'secondary' } as ProtocolColor,\n accent: { name: 'accent' } as ProtocolColor,\n /** `Color(uiColor:)` / `Color(.name)`: a UIKit semantic color by its iOS name. */\n system: (name: SemanticColorName): ProtocolColor => ({ name }),\n rgb,\n hex,\n opacity,\n gradient,\n};\n\n// ---------------------------------------------------------------------------\n// Unit points and gradients\n// ---------------------------------------------------------------------------\n\nexport type UnitPointName =\n | 'center'\n | 'top'\n | 'bottom'\n | 'leading'\n | 'trailing'\n | 'topLeading'\n | 'topTrailing'\n | 'bottomLeading'\n | 'bottomTrailing';\nexport type UnitPointValue = UnitPoint | UnitPointName;\n\nconst UNIT_POINTS: Record<UnitPointName, UnitPoint> = {\n center: { x: 0.5, y: 0.5 },\n top: { x: 0.5, y: 0 },\n bottom: { x: 0.5, y: 1 },\n leading: { x: 0, y: 0.5 },\n trailing: { x: 1, y: 0.5 },\n topLeading: { x: 0, y: 0 },\n topTrailing: { x: 1, y: 0 },\n bottomLeading: { x: 0, y: 1 },\n bottomTrailing: { x: 1, y: 1 },\n};\n\nexport function unitPoint(value: UnitPointValue): UnitPoint {\n return typeof value === 'string' ? UNIT_POINTS[value] : value;\n}\n\nexport interface GradientColors {\n /** Evenly spaced colors, or explicit stops. */\n colors?: ColorValue[];\n stops?: { color: ColorValue; location: number }[];\n}\n\nfunction stops(spec: GradientColors): GradientStop[] {\n if (spec.stops) return spec.stops.map((stop) => ({ color: color(stop.color), location: stop.location }));\n const colors = spec.colors ?? [];\n const last = Math.max(colors.length - 1, 1);\n return colors.map((value, index) => ({ color: color(value), location: index / last }));\n}\n\nexport function LinearGradient(spec: GradientColors & { startPoint: UnitPointValue; endPoint: UnitPointValue }): ShapeStyle {\n return { linearGradient: { stops: stops(spec), start: unitPoint(spec.startPoint), end: unitPoint(spec.endPoint) } };\n}\n\nexport function RadialGradient(\n spec: GradientColors & { center: UnitPointValue; startRadius: number; endRadius: number },\n): ShapeStyle {\n return {\n radialGradient: { stops: stops(spec), center: unitPoint(spec.center), startRadius: spec.startRadius, endRadius: spec.endRadius },\n };\n}\n\nexport function AngularGradient(\n spec: GradientColors & { center: UnitPointValue; startAngle?: number; endAngle?: number },\n): ShapeStyle {\n return {\n angularGradient: {\n stops: stops(spec),\n center: unitPoint(spec.center),\n startAngle: spec.startAngle ?? 0,\n endAngle: spec.endAngle ?? 360,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Fonts\n// ---------------------------------------------------------------------------\n\n/** A font as a prop: a text style name (`\"headline\"`) or a `Font` object. */\nexport type FontValue = TextStyle | ProtocolFont;\n\nexport function font(value: FontValue): ProtocolFont {\n return typeof value === 'string' ? { textStyle: value } : value;\n}\n\n/** `Font.system(size:weight:design:)` */\nexport function system(size: number, weight?: FontWeight, design?: FontDesign): ProtocolFont;\n/** `Font.system(.body, design:weight:)` */\nexport function system(textStyle: TextStyle, design?: FontDesign, weight?: FontWeight): ProtocolFont;\nexport function system(first: number | TextStyle, second?: FontWeight | FontDesign, third?: FontDesign | FontWeight): ProtocolFont {\n const result: ProtocolFont = typeof first === 'number' ? { size: first } : { textStyle: first };\n const weight = typeof first === 'number' ? (second as FontWeight | undefined) : (third as FontWeight | undefined);\n const design = typeof first === 'number' ? (third as FontDesign | undefined) : (second as FontDesign | undefined);\n if (weight) result.weight = weight;\n if (design) result.design = design;\n return result;\n}\n\n/** `.font(.title2.bold())`, `.font(.subheadline.weight(.semibold))` */\nexport function weighted(value: FontValue, weight: FontWeight): ProtocolFont {\n return { ...font(value), weight };\n}\n\nexport const Font = { system, weighted, bold: (value: FontValue): ProtocolFont => weighted(value, 'bold') };\n\n// ---------------------------------------------------------------------------\n// Frames and insets\n// ---------------------------------------------------------------------------\n\n/** `Infinity` stands for `.infinity`. */\nexport interface FrameValue {\n width?: number;\n height?: number;\n minWidth?: number;\n maxWidth?: number;\n minHeight?: number;\n maxHeight?: number;\n alignment?: FrameAlignment;\n}\n\nexport function frame(value: FrameValue): Frame {\n const dimension = (n: number | undefined): number | 'infinity' | undefined =>\n n === undefined ? undefined : n === Infinity ? 'infinity' : n;\n const result: Frame = { alignment: value.alignment ?? 'center' };\n if (value.width !== undefined) result.width = value.width;\n if (value.height !== undefined) result.height = value.height;\n const minWidth = dimension(value.minWidth);\n const maxWidth = dimension(value.maxWidth);\n const minHeight = dimension(value.minHeight);\n const maxHeight = dimension(value.maxHeight);\n if (minWidth !== undefined) result.minWidth = minWidth;\n if (maxWidth !== undefined) result.maxWidth = maxWidth;\n if (minHeight !== undefined) result.minHeight = minHeight;\n if (maxHeight !== undefined) result.maxHeight = maxHeight;\n return result;\n}\n\nexport type EdgeName = 'top' | 'bottom' | 'leading' | 'trailing' | 'horizontal' | 'vertical' | 'all';\n/**\n * `.padding()` (`true`), `.padding(12)`, `.padding(.vertical, 6)` (`[\"vertical\", 6]`),\n * `.padding([.top, .leading], 8)`, or explicit insets.\n */\nexport type PaddingValue = true | number | EdgeInsets | [EdgeName | EdgeName[], number?];\n\nexport const DEFAULT_PADDING = 16;\n\nexport function padding(value: PaddingValue): EdgeInsets {\n if (value === true) return insets(['all'], DEFAULT_PADDING);\n if (typeof value === 'number') return insets(['all'], value);\n if (Array.isArray(value)) {\n const [edges, amount] = value;\n return insets(Array.isArray(edges) ? edges : [edges], amount ?? DEFAULT_PADDING);\n }\n return value;\n}\n\nexport function insets(edges: EdgeName[], amount: number): EdgeInsets {\n const result: EdgeInsets = {};\n for (const edge of edges) {\n if (edge === 'all' || edge === 'vertical' || edge === 'top') result.top = amount;\n if (edge === 'all' || edge === 'vertical' || edge === 'bottom') result.bottom = amount;\n if (edge === 'all' || edge === 'horizontal' || edge === 'leading') result.leading = amount;\n if (edge === 'all' || edge === 'horizontal' || edge === 'trailing') result.trailing = amount;\n }\n return result;\n}\n","/**\n * `ScrollViewReader` and `.id` (the `scrollID` modifier): `proxy.scrollTo(id)`\n * marks the view with that id with a `scrollTo` command whose serial is new,\n * and the page scrolls every scrolling ancestor to it after the pass.\n * `proxy.scrollTo({ x, y })` (SwiftUI's `ScrollPosition.scrollTo(x:y:)`)\n * puts a `scrollOffset` command on the scroll views inside the reader\n * instead, as does a `scrollPosition` binding set to a point.\n */\n\nimport type { ScrollAxes, ScrollOffsetCommand, UnitPoint } from '@swiftbrowser/web/src/protocol';\nimport { createContext, useContext, useRef, useState, type ReactNode } from 'react';\nimport { readBinding, type BindingValue } from './binding';\nimport type { EventHandlers } from './host/instance';\nimport { sb } from './host/sb';\nimport { styled } from './modifiers';\nimport { unitPoint, type UnitPointValue } from './values';\n\n/** A target to scroll to, or (`point`) an offset for the scroll views inside the reader. */\ntype ScrollRequest = TargetRequest | PointRequest;\n\ninterface TargetRequest {\n id: string | number;\n anchor: UnitPoint | null;\n serial: number;\n /** The axes to scroll on; both when absent. */\n axes?: ScrollAxes;\n}\n\ninterface PointRequest {\n point: ScrollPoint;\n serial: number;\n}\n\n/** A content offset; an axis left out keeps its offset. */\nexport interface ScrollPoint {\n x?: number;\n y?: number;\n}\n\nconst isPoint = (value: unknown): value is ScrollPoint => typeof value === 'object' && value !== null && ('x' in value || 'y' in value);\n\n/** The `scrollTo` style a request becomes on its target. */\nfunction command(request: TargetRequest): { anchor: UnitPoint | null; serial: number; axes?: ScrollAxes } {\n return request.axes ? { anchor: request.anchor, serial: request.serial, axes: request.axes } : { anchor: request.anchor, serial: request.serial };\n}\n\n/** The `scrollOffset` prop a point request becomes on a scroll view. */\nfunction offsetCommand(request: PointRequest): ScrollOffsetCommand {\n const out: ScrollOffsetCommand = { serial: request.serial };\n if (typeof request.point.x === 'number') out.x = request.point.x;\n if (typeof request.point.y === 'number') out.y = request.point.y;\n return out;\n}\n\nexport const ScrollRequestContext = createContext<ScrollRequest | null>(null);\nlet nextSerial = 1;\n\nexport interface ScrollViewProxy {\n /**\n * Scroll so `anchor` of the view with that `scrollID` meets the same point\n * of the visible area; no anchor: as little as shows it. Every scrolling\n * ancestor moves on its axes, or only on `axes` when given (a horizontal\n * pager inside a list: `{ axes: 'horizontal' }` leaves the list where it is).\n */\n scrollTo(id: string | number, anchor?: UnitPointValue, options?: { axes?: ScrollAxes }): void;\n /**\n * `ScrollPosition.scrollTo(x:y:)`: scroll the scroll views inside the\n * reader to a content offset (an axis left out keeps its offset),\n * smoothly inside `withAnimation`.\n */\n scrollTo(point: ScrollPoint): void;\n}\n\nexport function ScrollViewReader({ children }: { children: (proxy: ScrollViewProxy) => ReactNode }): ReactNode {\n const [request, setRequest] = useState<ScrollRequest | null>(null);\n const proxy: ScrollViewProxy = {\n scrollTo: (target: string | number | ScrollPoint, anchor?: UnitPointValue, options?: { axes?: ScrollAxes }) => {\n if (isPoint(target)) setRequest({ point: target, serial: nextSerial++ });\n else setRequest({ id: target, anchor: anchor === undefined ? null : unitPoint(anchor), serial: nextSerial++, ...(options?.axes ? { axes: options.axes } : {}) });\n },\n };\n return <ScrollRequestContext.Provider value={request}>{children(proxy)}</ScrollRequestContext.Provider>;\n}\n\nexport function ScrollTarget({ id, children }: { id: string | number; children?: ReactNode }): ReactNode {\n const request = useContext(ScrollRequestContext);\n const position = useContext(ScrollPositionContext);\n // Inside a `scrollPosition` scroll view the page tells the target at the anchor it is there.\n const on: EventHandlers | undefined = position ? { scrollposition: () => position.report(id) } : undefined;\n if (request && 'id' in request && request.id === id) return sb('styled', { style: { scrollID: true, scrollTo: command(request) } }, on, children);\n if (on) return sb('styled', { style: { scrollID: true } }, on, children);\n return styled({ scrollID: true }, children);\n}\n\n/** What a `scrollPosition` scroll view hands the targets inside it: where to say they came to the anchor. */\nexport const ScrollPositionContext = createContext<{ report: (id: string | number) => void } | null>(null);\n\n/** A `scrollID` (`ScrollPosition(idType:)`), a content offset (`ScrollPosition(point:)`), or nothing. */\nexport type ScrollPositionValue = string | number | ScrollPoint | null;\n\n/** A `scrollPosition` binding; its setter only ever hears ids, so a `useState` of ids serves. */\nexport type ScrollPositionBinding = readonly [ScrollPositionValue, (value: string | number | null) => void] | ScrollPositionValue;\n\n/**\n * `scrollPosition={[position, setPosition]}` on a `ScrollView`\n * (`.scrollPosition(id:anchor:)`, `.scrollPosition(_:)`): the scroll view\n * reports the target at its anchor when scrolling settles\n * (`reportsPosition`), and a value the app sets, the first included, scrolls\n * there: to that target, as `proxy.scrollTo` would, or to a point\n * (`{ x, y }`, `ScrollPosition.scrollTo(x:y:)`), as a `scrollOffset`\n * command. A value the page just reported scrolls nowhere. The position\n * reads back as ids (the target at the anchor), never as a point: an app\n * that wants the offset reads it with `onScrollGeometryChange`.\n */\nexport function useScrollPosition(binding: ScrollPositionBinding | undefined, anchor: UnitPointValue | undefined, axes: ScrollAxes): { props: Record<string, unknown>; provide(children: ReactNode): ReactNode } | null {\n const bound = binding !== undefined;\n const [value, set] = bound ? readBinding(binding as BindingValue<ScrollPositionValue>) : [null, (): void => undefined];\n const last = useRef<ScrollPositionValue | undefined>(undefined);\n const reported = useRef<ScrollPositionValue | undefined>(undefined);\n const request = useRef<ScrollRequest | null>(null);\n const outer = useContext(ScrollRequestContext);\n const point = anchor === undefined ? null : unitPoint(anchor);\n if (value !== last.current) {\n last.current = value;\n if (isPoint(value)) request.current = { point: value, serial: nextSerial++ };\n // Its own scroll view's axes only: a list the view sits in stays where it is.\n else if (value !== null && value !== reported.current) request.current = { id: value, anchor: point, serial: nextSerial++, axes };\n reported.current = undefined;\n }\n // The offset the view is asked for: its own binding's or the reader's above, whichever is newer.\n const own = request.current;\n const current = own && (!outer || own.serial > outer.serial) ? own : outer;\n const offset = useOffsetCommand(bound ? current : outer);\n if (!bound) return offset ? { props: offset, provide: (children) => children } : null;\n const props: Record<string, unknown> = { reportsPosition: true, ...offset };\n if (point) props['positionAnchor'] = point;\n const context = {\n report: (id: string | number) => {\n reported.current = id;\n set(id);\n },\n };\n // A reader above keeps its say for the targets inside: a point request is this view's alone.\n const inner = current && 'point' in current ? outer && 'id' in outer ? outer : null : current;\n return {\n props,\n provide: (children) => (\n <ScrollPositionContext.Provider value={context}>\n <ScrollRequestContext.Provider value={inner}>{children}</ScrollRequestContext.Provider>\n </ScrollPositionContext.Provider>\n ),\n };\n}\n\n/**\n * The `scrollOffset` prop for the newest point request the scroll view has\n * seen: kept on the element after the pass that brought it (the page carries\n * each serial out once), so the prop is stable until the next request.\n */\nfunction useOffsetCommand(request: ScrollRequest | null): { scrollOffset: ScrollOffsetCommand } | null {\n const seen = useRef<ScrollOffsetCommand | null>(null);\n if (request && 'point' in request && (!seen.current || request.serial > seen.current.serial)) seen.current = offsetCommand(request);\n return seen.current ? { scrollOffset: seen.current } : null;\n}\n","/**\n * The scroll modifiers that pass down to the scroll views below, as SwiftUI's\n * environment does: `.scrollEdgeEffectStyle(_:for:)`,\n * `.scrollEdgeEffectHidden(_:for:)` and `.contentMargins(_:_:for:)`. A\n * `ScrollView` or `List` reads them from above and from its own props, the\n * closer setting winning edge by edge.\n */\n\nimport type { EdgeEffectProps, EdgeInsets } from '@swiftbrowser/web/src/protocol';\nimport { Children, createContext, createElement, useContext, type ReactNode } from 'react';\nimport { sb } from './host/sb';\nimport { padding, type PaddingValue } from './values';\n\nexport type ScrollEdgeEffectStyle = 'automatic' | 'hard' | 'soft';\n/** The vertical edges a scroll edge effect sits on. */\nexport type ScrollEdges = 'top' | 'bottom' | 'all' | 'vertical' | ('top' | 'bottom')[];\n\n/**\n * `.scrollEdgeEffectStyle(.hard, for: .top)` is `[\"hard\", \"top\"]`; a bare\n * style applies to both edges.\n */\nexport type ScrollEdgeEffectStyleValue = ScrollEdgeEffectStyle | [ScrollEdgeEffectStyle, ScrollEdges];\n/** `.scrollEdgeEffectHidden()` is `true`; `.scrollEdgeEffectHidden(true, for: .bottom)` is `[true, \"bottom\"]`. */\nexport type ScrollEdgeEffectHiddenValue = boolean | [boolean, ScrollEdges];\n\n/** The scroll settings in force at a point of the tree. */\nexport interface ScrollSettings {\n /** Per edge: a style (`hard`, `soft`; absent or undefined is automatic, an undefined key clearing an outer one) or hidden. */\n topStyle?: 'hard' | 'soft' | undefined;\n bottomStyle?: 'hard' | 'soft' | undefined;\n topHidden?: boolean;\n bottomHidden?: boolean;\n /** `.contentMargins`: padding inside the scroll views below. */\n margins?: EdgeInsets;\n}\n\nconst ScrollSettingsContext = createContext<ScrollSettings>({});\n\nfunction edgesOf(edges: ScrollEdges): { top: boolean; bottom: boolean } {\n const list = Array.isArray(edges) ? edges : [edges];\n const all = list.some((edge) => edge === 'all' || edge === 'vertical');\n return { top: all || list.includes('top'), bottom: all || list.includes('bottom') };\n}\n\n/** The settings one modifier adds. */\nexport function edgeStyleSettings(value: ScrollEdgeEffectStyleValue): ScrollSettings {\n const [style, edges] = Array.isArray(value) ? value : [value, 'all' as const];\n const on = edgesOf(edges);\n const name = style === 'automatic' ? undefined : style;\n const result: ScrollSettings = {};\n // `automatic` clears what an outer modifier set, so the key is kept.\n if (on.top) result.topStyle = name;\n if (on.bottom) result.bottomStyle = name;\n return result;\n}\n\nexport function edgeHiddenSettings(value: ScrollEdgeEffectHiddenValue): ScrollSettings {\n const [hidden, edges] = Array.isArray(value) ? value : [value, 'all' as const];\n const on = edgesOf(edges);\n const result: ScrollSettings = {};\n if (on.top) result.topHidden = hidden;\n if (on.bottom) result.bottomHidden = hidden;\n return result;\n}\n\n/** `contentMargins={12}`, `{[\"horizontal\", 20]}` or insets; `true` is the default 16. */\nexport type ContentMarginsValue = PaddingValue;\n\nexport function marginSettings(value: ContentMarginsValue): ScrollSettings {\n return { margins: padding(value) };\n}\n\n/** `inner` over `outer`, edge by edge. */\nexport function mergeScrollSettings(outer: ScrollSettings, inner: ScrollSettings): ScrollSettings {\n const result: ScrollSettings = { ...outer };\n for (const key of ['topStyle', 'bottomStyle', 'topHidden', 'bottomHidden'] as const) {\n if (key in inner) (result as Record<string, unknown>)[key] = inner[key];\n }\n if (inner.margins) result.margins = { ...outer.margins, ...inner.margins };\n return result;\n}\n\n/** The views below see `settings` added to the ones around them. */\nexport function withScrollSettings(settings: ScrollSettings, children: ReactNode): ReactNode {\n return createElement(ScrollSettingsExtender, { settings }, children);\n}\n\nfunction ScrollSettingsExtender({ settings, children }: { settings: ScrollSettings; children?: ReactNode }): ReactNode {\n const outer = useContext(ScrollSettingsContext);\n return createElement(ScrollSettingsContext.Provider, { value: mergeScrollSettings(outer, settings) }, children);\n}\n\n/** The settings in force here, with a scroll view's own modifiers applied over them. */\nexport function useScrollSettings(own: ScrollSettings): ScrollSettings {\n return mergeScrollSettings(useContext(ScrollSettingsContext), own);\n}\n\n/** The `edgeEffect` prop of a `list` or `scrollview`, absent when both edges are automatic. */\nexport function edgeEffectProp(settings: ScrollSettings): EdgeEffectProps | undefined {\n const edges: EdgeEffectProps = {};\n const top = settings.topHidden ? 'hidden' : settings.topStyle;\n const bottom = settings.bottomHidden ? 'hidden' : settings.bottomStyle;\n if (top) edges.top = top;\n if (bottom) edges.bottom = bottom;\n return top || bottom ? edges : undefined;\n}\n\n/**\n * A scroll view's content with its content margins as padding inside it\n * (several children first become the stack the scroll view would make).\n */\nexport function marginedContent(children: ReactNode, margins: EdgeInsets | undefined, axis: 'horizontal' | 'vertical'): ReactNode {\n if (!margins || Object.values(margins).every((value) => !value)) return children;\n const list = Children.toArray(children);\n const content = list.length === 1 ? list[0] : sb(axis === 'horizontal' ? 'hstack' : 'vstack', { spacing: null, alignment: 'center' }, undefined, children);\n return sb('styled', { style: { padding: margins } }, undefined, content);\n}\n\n","/**\n * Lazy rows (docs/ops-protocol.md, \"Lazy rows\"): inside a `List`,\n * `LazyVStack` or `LazyHStack`, a `ForEach` of more rows than a batch mounts\n * the first batch and a `lazyspacer`; the page reports the spacer when it\n * nears the visible area (`lazy`), and the next batch mounts, with a new\n * spacer after it.\n */\n\nimport { createContext, createElement, isValidElement, useContext, useEffect, useState, type ReactElement, type ReactNode } from 'react';\nimport { ScrollRequestContext } from './scrollReader';\nimport { sb } from './host/sb';\n\nexport const LAZY_BATCH = 12;\n\nexport const LazyContext = createContext<'vertical' | 'horizontal' | null>(null);\n\nexport interface LazyGroupProps {\n rows: ReactElement[];\n /** Set by a list: the group's first row's index among the container's children. */\n start?: number;\n /** Set by a list: wraps each row (selection tags) given its index among the container's children. */\n wrap?: (row: ReactElement, containerIndex: number) => ReactNode;\n}\n\nexport function LazyGroup({ rows, start = 0, wrap }: LazyGroupProps): ReactNode {\n const axis = useContext(LazyContext);\n const request = useContext(ScrollRequestContext);\n const [count, setCount] = useState(LAZY_BATCH);\n // A `scrollTo` whose target is a row not built yet builds the rows up to it\n // first, as SwiftUI does, so the target is on the page when it scrolls.\n const target = request && 'id' in request ? rows.findIndex((row) => rowMatches(row, request.id)) : -1;\n const needed = target >= 0 ? Math.ceil((target + 1) / LAZY_BATCH) * LAZY_BATCH : 0;\n useEffect(() => {\n if (needed > count) setCount(needed);\n }, [needed, count]);\n const visible = Math.max(count, needed);\n const shown = axis === null ? rows : rows.slice(0, visible);\n const built = shown.map((row, index) => (wrap ? wrap(row, start + index) : row));\n if (axis === null || shown.length >= rows.length) return built;\n return [\n ...built,\n createElement(\n LazySpacer,\n { key: `lazy-${visible}`, axis, remaining: rows.length - shown.length, more: () => setCount(visible + LAZY_BATCH) },\n ),\n ];\n}\n\nfunction LazySpacer({ axis, remaining, more }: { axis: 'vertical' | 'horizontal'; remaining: number; more: () => void }): ReactNode {\n return sb('lazyspacer', { axis, remaining }, { lazy: more });\n}\n\n/** Whether a row is a scroll target's: its key (a `ForEach` id), or a `scrollID` on the row's view. */\nfunction rowMatches(row: ReactElement, id: string | number): boolean {\n if (row.key !== null && row.key === String(id)) return true;\n let element: ReactElement | null = row;\n for (let depth = 0; element && depth < 3; depth++) {\n const props = element.props as { scrollID?: unknown; children?: unknown };\n if (props.scrollID === id) return true;\n element = isValidElement(props.children) ? (props.children as ReactElement) : null;\n }\n return false;\n}\n","import type { FrameAlignment, GridItem as GridItemProps, GridRowAlignment, HStackAlignment, PinnedView, ScrollAxes, ScrollGeometryEvent, VStackAlignment } from '@swiftbrowser/web/src/protocol';\nimport { Children, Fragment, createContext, createElement, isValidElement, useRef, useState, type Key, type ReactElement, type ReactNode } from 'react';\nimport { useViewEnvironment } from '../environment';\nimport type { EventHandlers } from '../host/instance';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, takeModifier, type ModifierEntry, type ViewModifiers } from '../modifiers';\nimport { unitPoint, type UnitPointValue } from '../values';\nimport { useScrollPosition, type ScrollPositionBinding } from '../scrollReader';\nimport {\n edgeEffectProp,\n edgeHiddenSettings,\n edgeStyleSettings,\n marginSettings,\n marginedContent,\n mergeScrollSettings,\n useScrollSettings,\n withScrollSettings,\n type ContentMarginsValue,\n type ScrollEdgeEffectHiddenValue,\n type ScrollEdgeEffectStyleValue,\n type ScrollSettings,\n} from '../scrollEnvironment';\nimport { Row, type RowProps } from './row';\nimport { LAZY_BATCH, LazyGroup, type LazyGroupProps } from '../lazy';\n\n/**\n * `PinnedScrollableViews`: what a lazy stack or grid keeps in view\n * (`pinnedViews: [.sectionHeaders]`): each `Section`'s header stays at the\n * scroll view's leading edge while its section passes, pushed out by the\n * next section's; a footer stays at the trailing edge the same way.\n */\nexport type PinnedViews = PinnedView[];\n\n/** The pinned views of the lazy stack or grid around a `Section` (its string header then becomes a view, so it can pin). */\nexport const PinnedContext = createContext<PinnedViews | null>(null);\n\n/** `children` under the stack's pinned views, when it has any. */\nfunction pinning(pinnedViews: PinnedViews | undefined, children: ReactNode): ReactNode {\n return pinnedViews && pinnedViews.length > 0 ? <PinnedContext.Provider value={pinnedViews}>{children}</PinnedContext.Provider> : children;\n}\n\nexport interface VStackProps extends ViewModifiers {\n alignment?: VStackAlignment;\n spacing?: number | null;\n /** `.scrollTargetLayout()`: the children are the enclosing scroll view's snap points. */\n scrollTargetLayout?: boolean;\n /** `LazyVStack(pinnedViews:)` (a `LazyVStack`'s; see `PinnedViews`). */\n pinnedViews?: PinnedViews;\n children?: ReactNode;\n}\n\nexport function VStack(props: VStackProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const stack: Record<string, unknown> = { spacing: own.spacing ?? null, alignment: own.alignment ?? 'center' };\n if (own.scrollTargetLayout) stack['scrollTarget'] = true;\n if (own.pinnedViews && own.pinnedViews.length > 0) stack['pinned'] = own.pinnedViews;\n return applyModifiers(sb('vstack', stack, undefined, pinning(own.pinnedViews, own.children)), modifiers);\n}\n\nexport interface HStackProps extends ViewModifiers {\n alignment?: HStackAlignment | 'firstTextBaseline' | 'lastTextBaseline';\n spacing?: number | null;\n scrollTargetLayout?: boolean;\n /** `LazyHStack(pinnedViews:)` (a `LazyHStack`'s; see `PinnedViews`). */\n pinnedViews?: PinnedViews;\n children?: ReactNode;\n}\n\nexport function HStack(props: HStackProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const stack: Record<string, unknown> = { spacing: own.spacing ?? null, alignment: own.alignment ?? 'center' };\n if (own.scrollTargetLayout) stack['scrollTarget'] = true;\n if (own.pinnedViews && own.pinnedViews.length > 0) stack['pinned'] = own.pinnedViews;\n return applyModifiers(sb('hstack', stack, undefined, pinning(own.pinnedViews, own.children)), modifiers);\n}\n\nexport interface ZStackProps extends ViewModifiers {\n alignment?: FrameAlignment;\n children?: ReactNode;\n}\n\nexport function ZStack(props: ZStackProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n return applyModifiers(sb('zstack', { alignment: own.alignment ?? 'center' }, undefined, own.children), modifiers);\n}\n\nexport interface SpacerProps extends ViewModifiers {\n minLength?: number | null;\n}\n\nexport function Spacer(props: SpacerProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n return applyModifiers(sb('spacer', { minLength: own.minLength ?? null }), modifiers);\n}\n\nexport function Divider(props: ViewModifiers): ReactNode {\n const { modifiers } = splitProps(props);\n return applyModifiers(sb('divider', {}), modifiers);\n}\n\nexport interface ScrollViewProps extends ViewModifiers {\n axes?: ScrollAxes;\n /** `.scrollTargetBehavior(_:)`: snap to the `scrollTargetLayout` children, or a page at a time. */\n scrollTargetBehavior?: 'viewAligned' | 'paging';\n /**\n * `.scrollDismissesKeyboard(_:)`: `true` or `immediately` dismisses the\n * keyboard as scrolling starts; `interactively` lets it follow the finger\n * down and back up, as Messages does (natively; a page dismisses it at once).\n */\n scrollDismissesKeyboard?: boolean | 'immediately' | 'interactively' | 'never';\n /** `.scrollIndicators(_:)`: `hidden` draws no scroll bars (a pager's). */\n scrollIndicators?: 'automatic' | 'visible' | 'hidden';\n /**\n * `.defaultScrollAnchor(_:)`: where the content starts (`\"bottom\"`: its end\n * in view, as a chat) and stays when it grows while the viewer is there;\n * a viewer who scrolled away is left where they are.\n */\n defaultScrollAnchor?: UnitPointValue;\n /**\n * `.scrollPosition(id:anchor:)`: the `scrollID` of the view at the anchor\n * (the leading edge unless `scrollPositionAnchor` says otherwise), set\n * when scrolling settles; setting it scrolls there.\n */\n scrollPosition?: ScrollPositionBinding;\n scrollPositionAnchor?: UnitPointValue;\n /**\n * `.onScrollGeometryChange(for:of:action:)`: hears the scroll view's\n * geometry (its content offset and size, its own size, the visible\n * rectangle) as it scrolls and lays out. A function is called on every\n * change; `{ of, action }` calls `action(value, oldValue)` only when `of`\n * (the `for:` transform) answers differently, so an app that watches the\n * content size alone is not rendered per frame of a scroll.\n */\n onScrollGeometryChange?: ScrollGeometryChangeHandler;\n children?: ReactNode;\n}\n\n/** SwiftUI's `ScrollGeometry`. */\nexport interface ScrollGeometry {\n /** The visible area's origin in the content. */\n contentOffset: { x: number; y: number };\n contentSize: { width: number; height: number };\n /** The scroll view's own size. */\n containerSize: { width: number; height: number };\n /** Space the view scrolls into past its content (under a bar covering its bottom). */\n contentInsets: { top: number; leading: number; bottom: number; trailing: number };\n /** The content's part in view: `contentOffset` and `containerSize`. */\n visibleRect: { x: number; y: number; width: number; height: number };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- the spec's value type is the transform's to infer\nexport type ScrollGeometryChangeHandler = ((geometry: ScrollGeometry) => void) | ScrollGeometryChangeSpec<any>;\n\nexport interface ScrollGeometryChangeSpec<T> {\n /** The `for:` transform: what of the geometry the action watches. */\n of: (geometry: ScrollGeometry) => T;\n action: (value: T, oldValue: T) => void;\n}\n\n/** The geometry a `scrollgeometry` event reports. */\nexport function scrollGeometryOf(event: ScrollGeometryEvent): ScrollGeometry {\n return {\n contentOffset: { x: event.offset.x, y: event.offset.y },\n contentSize: { width: event.contentSize.width, height: event.contentSize.height },\n containerSize: { width: event.containerSize.width, height: event.containerSize.height },\n contentInsets: { ...event.contentInsets },\n visibleRect: { x: event.offset.x, y: event.offset.y, width: event.containerSize.width, height: event.containerSize.height },\n };\n}\n\n/**\n * The `reportsGeometry` prop and `scrollgeometry` handler for an\n * `onScrollGeometryChange`: the `of` transform's last answer is kept so the\n * action hears a change once.\n */\nfunction useScrollGeometryChange(handler: ScrollGeometryChangeHandler | undefined): { props: Record<string, unknown>; handlers?: EventHandlers } {\n const last = useRef<{ value: unknown } | null>(null);\n if (!handler) return { props: {} };\n return {\n props: { reportsGeometry: true },\n handlers: {\n scrollgeometry: (event) => {\n const geometry = scrollGeometryOf(event);\n if (typeof handler === 'function') return handler(geometry);\n const value = handler.of(geometry);\n const previous = last.current;\n if (previous && JSON.stringify(previous.value) === JSON.stringify(value)) return;\n last.current = { value };\n handler.action(value, previous ? previous.value : value);\n },\n },\n };\n}\n\nexport function ScrollView(props: ScrollViewProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const refresh = useRefreshable(takeModifier(modifiers, 'refreshable'));\n const ownSettings = takeScrollSettings(modifiers);\n const settings = useScrollSettings(ownSettings);\n const axes = own.axes ?? 'vertical';\n const geometry = useScrollGeometryChange(own.onScrollGeometryChange);\n const scroll: Record<string, unknown> = { axes, ...refresh.props, ...geometry.props };\n const handlers: EventHandlers | undefined = refresh.handlers || geometry.handlers ? { ...refresh.handlers, ...geometry.handlers } : undefined;\n if (own.scrollTargetBehavior) scroll['snap'] = own.scrollTargetBehavior;\n if (own.scrollDismissesKeyboard === true || own.scrollDismissesKeyboard === 'immediately') scroll['dismissesKeyboard'] = true;\n else if (own.scrollDismissesKeyboard === 'interactively') scroll['dismissesKeyboard'] = 'interactively';\n if (own.scrollIndicators === 'hidden') scroll['showsIndicators'] = false;\n if (own.defaultScrollAnchor !== undefined) scroll['defaultScrollAnchor'] = unitPoint(own.defaultScrollAnchor);\n const edgeEffect = edgeEffectProp(settings);\n if (edgeEffect) scroll['edgeEffect'] = edgeEffect;\n const position = useScrollPosition(own.scrollPosition, own.scrollPositionAnchor, axes);\n if (position) Object.assign(scroll, position.props);\n const content = marginedContent(own.children, settings.margins, axes === 'horizontal' ? 'horizontal' : 'vertical');\n const inner = providingScrollSettings(ownSettings, content);\n return applyModifiers(sb('scrollview', scroll, handlers, position ? position.provide(inner) : inner), modifiers);\n}\n\n/**\n * The scroll modifiers written on a `ScrollView` or `List` itself: they apply\n * to it, and pass on to the scroll views inside as from above.\n */\nexport function takeScrollSettings(modifiers: ModifierEntry[]): ScrollSettings {\n let settings: ScrollSettings = {};\n // Each sets different fields, so their order does not matter.\n const own: ScrollSettings[] = [];\n for (const key of ['scrollEdgeEffectStyle', 'scrollEdgeEffectHidden', 'contentMargins'] as const) {\n const value = takeModifier(modifiers, key);\n if (value === undefined) continue;\n if (key === 'scrollEdgeEffectStyle') own.push(edgeStyleSettings(value as ScrollEdgeEffectStyleValue));\n else if (key === 'scrollEdgeEffectHidden') own.push(edgeHiddenSettings(value as ScrollEdgeEffectHiddenValue));\n else own.push(marginSettings(value as ContentMarginsValue));\n }\n for (const each of own) settings = mergeScrollSettings(settings, each);\n return settings;\n}\n\n/** `children` under the settings a scroll view was given itself (when there are any). */\nexport function providingScrollSettings(settings: ScrollSettings, children: ReactNode): ReactNode {\n return Object.keys(settings).length > 0 ? withScrollSettings(settings, children) : children;\n}\n\n/**\n * `.refreshable` above a `List` or `ScrollView`: its props (`refreshable`,\n * `refreshing` while the action runs) and the `refresh` handler.\n */\nexport function useRefreshable(own?: () => unknown): { props: Record<string, unknown>; handlers?: EventHandlers } {\n // `.refreshable` on the list or scroll view itself, else from above it.\n const environment = useViewEnvironment();\n const refresh = own ?? environment.refresh;\n const [refreshing, setRefreshing] = useState(false);\n if (!refresh) return { props: {} };\n return {\n props: { refreshable: true, refreshing },\n handlers: {\n refresh: () => {\n if (refreshing) return;\n setRefreshing(true);\n Promise.resolve()\n .then(refresh)\n .catch((error: unknown) => console.error(error))\n .finally(() => setRefreshing(false));\n },\n },\n };\n}\n\nexport interface GroupProps extends ViewModifiers {\n children?: ReactNode;\n}\n\n/** `Group { }`: the modifiers apply to each child. */\nexport function Group(props: GroupProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n if (modifiers.length === 0) return own.children;\n return Children.map(own.children, (child) => applyModifiers(child, modifiers));\n}\n\nexport interface ForEachProps<T> extends ViewModifiers {\n data: readonly T[];\n /** The identity of each element (`id: \\.self` by default, or `.id` when the element has one). */\n id?: (element: T, index: number) => Key;\n /** `.onDelete`: the rows become deletable (a swipe, or edit mode's minus); called with the offsets to remove. */\n onDelete?: (offsets: number[]) => void;\n /** `.deleteDisabled`, per element. */\n deleteDisabled?: (element: T, index: number) => boolean;\n /**\n * `.onMove`: the rows become movable (a grip in edit mode, a long press\n * otherwise); called like `move(fromOffsets:toOffset:)`, with the offsets\n * moved and the offset they go before, counted before the move\n * (`moveItems` applies it to an array).\n */\n onMove?: (offsets: number[], to: number) => void;\n /** `.moveDisabled`, per element. */\n moveDisabled?: (element: T, index: number) => boolean;\n children: (element: T, index: number) => ReactNode;\n}\n\n/** `Array.move(fromOffsets:toOffset:)`: the array with `offsets` moved before `to` (counted before the move). */\nexport function moveItems<T>(items: readonly T[], offsets: readonly number[], to: number): T[] {\n const moving = new Set(offsets);\n const picked = items.filter((_, index) => moving.has(index));\n const rest = items.filter((_, index) => !moving.has(index));\n const before = offsets.filter((offset) => offset < to).length;\n const at = to - before;\n return [...rest.slice(0, at), ...picked, ...rest.slice(at)];\n}\n\n/** `ForEach(data, id:) { }`: one keyed child per element. */\nexport function ForEach<T>(props: ForEachProps<T>): ReactNode {\n const { own, modifiers } = splitProps(props);\n const rows = own.data.map((element, index): ReactElement => {\n const key = own.id ? own.id(element, index) : keyOf(element, index);\n const content = applyModifiers(own.children(element, index), modifiers);\n if (!own.onDelete && !own.onMove) return createElement(Fragment, { key }, content);\n const { onDelete, onMove } = own;\n const row: RowProps = { tag: key, index };\n if (onDelete) {\n row.onDelete = () => onDelete([index]);\n row.deletable = !own.deleteDisabled?.(element, index);\n }\n if (onMove) {\n row.onMove = (to) => onMove([index], to);\n row.movable = !own.moveDisabled?.(element, index);\n }\n return createElement(Row, { key, ...row }, content);\n });\n // A long group builds its rows lazily inside a list or a lazy stack.\n return rows.length > LAZY_BATCH ? createElement(LazyGroup, { rows }) : rows;\n}\n\nfunction keyOf(element: unknown, index: number): Key {\n if (typeof element === 'string' || typeof element === 'number') return element;\n if (typeof element === 'object' && element !== null && 'id' in element) {\n const id = (element as { id: unknown }).id;\n if (typeof id === 'string' || typeof id === 'number') return id;\n }\n return index;\n}\n\n/**\n * The elements of `children`, through fragments, arrays and `ForEach`, so\n * `Picker` and `TabView` can read their options and tabs.\n */\nexport function flattenChildren(children: ReactNode, options: { keepLazy?: boolean } = {}): ReactElement[] {\n const result: ReactElement[] = [];\n const visit = (node: ReactNode): void => {\n if (node === null || node === undefined || typeof node === 'boolean') return;\n if (Array.isArray(node)) {\n node.forEach(visit);\n return;\n }\n if (!isValidElement(node)) return;\n const element = node as ReactElement<Record<string, unknown>>;\n if (element.type === Fragment) {\n const inner = element.props['children'] as ReactNode;\n // A keyed fragment around one view (a `ForEach` row) hands its key on,\n // so the row keeps its identity when the rows reorder.\n if (element.key !== null && isValidElement(inner) && inner.key === null && inner.type !== Fragment) {\n visit({ ...inner, key: element.key });\n return;\n }\n visit(inner);\n return;\n }\n if (element.type === ForEach) {\n // Expand it as it would render (keys, modifiers and `onDelete` rows included).\n visit(ForEach(element.props as unknown as ForEachProps<unknown>));\n return;\n }\n if (element.type === LazyGroup && !options.keepLazy) {\n visit((element.props as unknown as LazyGroupProps).rows);\n return;\n }\n result.push(element);\n };\n visit(children);\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Grids\n// ---------------------------------------------------------------------------\n\nexport interface GridItemSpec {\n size?: { fixed: number } | { flexible: { minimum?: number; maximum?: number } } | { adaptive: { minimum: number; maximum?: number } };\n spacing?: number | null | undefined;\n alignment?: FrameAlignment | null | undefined;\n}\n\n/** `GridItem(.flexible(), spacing: 8)`; `GridItem.flexible()` for short. */\nexport function GridItem(spec: GridItemSpec = {}): GridItemProps {\n const dimension = (n: number | undefined): number | 'infinity' => (n === undefined || n === Infinity ? 'infinity' : n);\n let size: GridItemProps['size'];\n if (spec.size && 'fixed' in spec.size) size = { kind: 'fixed', value: spec.size.fixed };\n else if (spec.size && 'adaptive' in spec.size) {\n size = { kind: 'adaptive', minimum: spec.size.adaptive.minimum, maximum: dimension(spec.size.adaptive.maximum) };\n } else {\n const flexible = spec.size && 'flexible' in spec.size ? spec.size.flexible : {};\n size = { kind: 'flexible', minimum: flexible.minimum ?? 10, maximum: dimension(flexible.maximum) };\n }\n return { size, spacing: spec.spacing ?? null, alignment: spec.alignment ?? null };\n}\nGridItem.flexible = (options: { minimum?: number; maximum?: number; spacing?: number; alignment?: FrameAlignment } = {}): GridItemProps =>\n GridItem({ size: { flexible: options }, spacing: options.spacing, alignment: options.alignment });\nGridItem.fixed = (value: number, options: { spacing?: number; alignment?: FrameAlignment } = {}): GridItemProps =>\n GridItem({ size: { fixed: value }, spacing: options.spacing, alignment: options.alignment });\nGridItem.adaptive = (options: { minimum: number; maximum?: number; spacing?: number; alignment?: FrameAlignment }): GridItemProps =>\n GridItem({ size: { adaptive: options }, spacing: options.spacing, alignment: options.alignment });\n\nexport interface LazyVGridProps extends ViewModifiers {\n columns: GridItemProps[];\n alignment?: FrameAlignment;\n spacing?: number | null;\n /** `LazyVGrid(pinnedViews:)`: the `Section` headers (footers) stay in view as their cells scroll. */\n pinnedViews?: PinnedViews;\n children?: ReactNode;\n}\n\nexport function LazyVGrid(props: LazyVGridProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const grid: Record<string, unknown> = { columns: own.columns, spacing: own.spacing ?? null, alignment: own.alignment ?? 'center' };\n if (own.pinnedViews && own.pinnedViews.length > 0) grid['pinned'] = own.pinnedViews;\n return applyModifiers(sb('lazyvgrid', grid, undefined, pinning(own.pinnedViews, own.children)), modifiers);\n}\n\nexport interface LazyHGridProps extends ViewModifiers {\n rows: GridItemProps[];\n /** How each cell sits in its slot: `top`, `center` (the default) or `bottom`. */\n alignment?: 'top' | 'center' | 'bottom' | 'firstTextBaseline' | 'lastTextBaseline';\n /** Between the columns (8 by default). */\n spacing?: number | null;\n /** `LazyHGrid(pinnedViews:)`: as for `LazyVGrid`, along the leading edge. */\n pinnedViews?: PinnedViews;\n children?: ReactNode;\n}\n\n/**\n * `LazyHGrid(rows:)`: the rows share the height it is proposed and the cells\n * fill them column by column, usually inside a horizontal `ScrollView`.\n */\nexport function LazyHGrid(props: LazyHGridProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const grid: Record<string, unknown> = { rows: own.rows, spacing: own.spacing ?? null, alignment: (own.alignment ?? 'center') as FrameAlignment };\n if (own.pinnedViews && own.pinnedViews.length > 0) grid['pinned'] = own.pinnedViews;\n return applyModifiers(sb('lazyhgrid', grid, undefined, pinning(own.pinnedViews, own.children)), modifiers);\n}\n\nexport interface GridProps extends ViewModifiers {\n alignment?: FrameAlignment;\n horizontalSpacing?: number | null;\n verticalSpacing?: number | null;\n children?: ReactNode;\n}\n\nexport function Grid(props: GridProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n return applyModifiers(\n sb(\n 'grid',\n { horizontalSpacing: own.horizontalSpacing ?? null, verticalSpacing: own.verticalSpacing ?? null, alignment: own.alignment ?? 'center' },\n undefined,\n own.children,\n ),\n modifiers,\n );\n}\n\nexport interface GridRowProps extends ViewModifiers {\n alignment?: GridRowAlignment | null;\n children?: ReactNode;\n}\n\nexport function GridRow(props: GridRowProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n return applyModifiers(sb('gridrow', { alignment: own.alignment ?? null }, undefined, own.children), modifiers);\n}\n","import type { Color, Font, ShapeStyle, TextRun } from '@swiftbrowser/web/src/protocol';\nimport { Fragment, isValidElement, type ReactElement, type ReactNode } from 'react';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, styled, takeModifier, type ViewModifiers } from '../modifiers';\nimport { useViewEnvironment } from '../environment';\nimport { color, font, shapeStyle, type ColorValue, type FontValue, type StyleValue } from '../values';\nimport { HStack } from './stacks';\nimport { bitmapExtent, type Bitmap } from '../bitmaps';\n\nexport interface TextProps extends ViewModifiers {\n /**\n * Strings and numbers, nested `<Text>`s (`Text + Text`) and inline\n * `<Image>`s. A nested text's `font`, `bold`, `foregroundStyle` and\n * `background` (a colour behind its glyphs, as `AttributedString`'s\n * `backgroundColor`) style its own run; the outer text's wrap the whole.\n */\n children?: ReactNode;\n italic?: boolean;\n underline?: boolean | { color?: ColorValue };\n strikethrough?: boolean | { color?: ColorValue };\n /** Points between characters (`.tracking` / `.kerning`). */\n tracking?: number;\n kerning?: number;\n baselineOffset?: number;\n /** A tap on the text opens this URL. */\n link?: string;\n}\n\n/** The run-level style of one `Text` (nested texts inherit the outer one). */\ninterface RunStyle {\n italic?: boolean;\n underline?: { color?: unknown };\n strikethrough?: { color?: unknown };\n kerning?: number;\n baselineOffset?: number;\n link?: string;\n font?: Font;\n foreground?: ShapeStyle;\n background?: Color;\n}\n\ntype Segment = { text: string; style: RunStyle } | { image: Record<string, unknown>; style: RunStyle };\n\nfunction runStyleOf(props: TextProps, inherited: RunStyle, nested: boolean): RunStyle {\n const style: RunStyle = { ...inherited };\n if (props.italic) style.italic = true;\n if (props.underline) style.underline = typeof props.underline === 'object' && props.underline.color ? { color: color(props.underline.color) } : {};\n if (props.strikethrough) {\n style.strikethrough = typeof props.strikethrough === 'object' && props.strikethrough.color ? { color: color(props.strikethrough.color) } : {};\n }\n const kerning = props.tracking ?? props.kerning;\n if (kerning !== undefined) style.kerning = kerning;\n if (props.baselineOffset !== undefined) style.baselineOffset = props.baselineOffset;\n if (props.link) style.link = props.link;\n if (nested) {\n // A nested text's font and color modifiers style its run; the outer\n // text's wrap the whole element (as `styled`), like the shim.\n let runFont: Font | undefined = props.font !== undefined ? font(props.font as FontValue) : undefined;\n if (props.bold) runFont = { ...(runFont ?? {}), weight: 'bold' };\n if (props.fontWeight) runFont = { ...(runFont ?? {}), weight: props.fontWeight };\n if (props.monospacedDigit) runFont = { ...(runFont ?? {}), monospacedDigit: true };\n if (runFont) style.font = { ...(style.font ?? {}), ...runFont };\n // A run takes one color: the primary of a layered style.\n if (props.foregroundStyle !== undefined) {\n style.foreground = shapeStyle((Array.isArray(props.foregroundStyle) ? props.foregroundStyle[0] : props.foregroundStyle) as StyleValue);\n }\n // A colour behind the run's glyphs; a view, a shape or a gradient is no run's.\n const background = runBackground(props.background);\n if (background) style.background = background;\n }\n return style;\n}\n\n/** A nested text's `background` as a run's colour: a name or a hex string, or a Color object; nothing for a view, a shape or a style with no colour. */\nfunction runBackground(value: unknown): Color | undefined {\n if (typeof value === 'string') {\n const made = color(value as ColorValue);\n return 'hierarchical' in made ? undefined : made;\n }\n if (typeof value !== 'object' || value === null || isValidElement(value) || 'in' in value) return undefined;\n return 'r' in value || 'name' in value || 'named' in value ? (value as Color) : undefined;\n}\n\n/** The segments of a text: raw strings merge into one; nested texts and images are their own. */\nfunction segmentsOf(children: ReactNode, style: RunStyle, into: Segment[]): void {\n const visit = (node: ReactNode): void => {\n if (node === null || node === undefined || typeof node === 'boolean') return;\n if (typeof node === 'string' || typeof node === 'number') {\n const last = into[into.length - 1];\n if (last && 'text' in last && last.style === style) last.text += String(node);\n else into.push({ text: String(node), style });\n return;\n }\n if (Array.isArray(node)) {\n node.forEach(visit);\n return;\n }\n if (!isValidElement(node)) return;\n const element = node as ReactElement<Record<string, unknown>>;\n if (element.type === Fragment) {\n visit(element.props['children'] as ReactNode);\n return;\n }\n if (element.type === Text) {\n const props = element.props as TextProps;\n segmentsOf(props.children, runStyleOf(props, style, true), into);\n return;\n }\n if (element.type === Image) {\n const props = element.props as ImageProps;\n into.push({ image: imageProps(props), style });\n return;\n }\n };\n visit(children);\n}\n\nfunction isPlainStyle(style: RunStyle): boolean {\n return Object.keys(style).length === 0;\n}\n\nexport function Text(props: TextProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const environment = useViewEnvironment();\n const style = runStyleOf(props, {}, false);\n const segments: Segment[] = [];\n segmentsOf(own.children, style, segments);\n const textCase = takeModifier(modifiers, 'textCase') ?? environment.textCase;\n if (textCase) {\n for (const segment of segments) {\n if ('text' in segment) segment.text = textCase === 'uppercase' ? segment.text.toUpperCase() : segment.text.toLowerCase();\n }\n }\n const redacted = takeModifier(modifiers, 'redacted') ?? environment.redacted;\n const content = segments.map((segment) => ('text' in segment ? segment.text : '')).join('');\n const plain = segments.length <= 1 && (segments.length === 0 || ('text' in segments[0]! && isPlainStyle(segments[0]!.style)));\n if (plain) return applyModifiers(placeholder(sb('text', { text: content }), redacted), modifiers);\n const runs: TextRun[] = segments.map((segment) => {\n const run: Record<string, unknown> = { ...segment.style };\n if ('text' in segment) run['text'] = segment.text;\n else run['image'] = segment.image;\n return run as TextRun;\n });\n const hasLinks = segments.some((segment) => segment.style.link);\n const handlers = hasLinks ? { link: (event: { value: string }) => openURL(event.value) } : undefined;\n return applyModifiers(placeholder(sb('text', { text: content, runs }, handlers), redacted), modifiers);\n}\n\n/**\n * `.redacted(reason: .placeholder)`: the view keeps its size and draws as a\n * rounded block of the tertiary fill, as iOS draws placeholder content.\n */\nexport function placeholder(node: ReactNode, redacted: boolean | undefined): ReactNode {\n if (!redacted) return node;\n return styled({ background: { hierarchical: 3 }, backgroundCornerRadius: 4 }, styled({ foreground: { name: 'clear' } }, node));\n}\n\n/** Opens a link: the system's opener in a SwiftBrowser Native app (its bridge's `openURL`), else a new tab. */\nexport function openURL(url: string): void {\n const native = (globalThis as { __sbNative?: { openURL?: (url: string) => boolean } }).__sbNative;\n if (native?.openURL) {\n native.openURL(url);\n return;\n }\n if (typeof window !== 'undefined') window.open(url, '_blank', 'noopener');\n}\n\n// ---------------------------------------------------------------------------\n// Image\n// ---------------------------------------------------------------------------\n\nexport interface ImageProps extends ViewModifiers {\n /** An SF Symbol name. */\n systemName?: string;\n /** An asset-catalog image name (the renderer needs the catalog manifest). */\n name?: string;\n /** A remote image whose pixel size is known; `AsyncImage` loads one to learn it. */\n url?: string;\n width?: number;\n height?: number;\n resizable?: boolean;\n /**\n * Its accessible name in place of the symbol's or the image's\n * (`.accessibilityLabel(_:)`); an icon-only `Label` names its icon by its\n * title, as on iOS.\n */\n accessibilityLabel?: string | undefined;\n /**\n * `Image(uiImage:)` of a Core Image recipe: a source registered with\n * `bitmapSource` and the steps to draw it with (bitmaps.ts). Its size is\n * the recipe's extent in pixels over `scale`; a clamped (infinite) image\n * has none until it is cropped.\n */\n bitmap?: Bitmap;\n /** Pixels per point of a `bitmap` (`UIImage`'s `scale`): 1 by default. */\n scale?: number;\n /** `.interpolation(.none)`: a `bitmap` scaled up without smoothing (a QR code, pixel art). */\n interpolation?: 'none';\n}\n\nfunction imageProps(props: ImageProps): Record<string, unknown> {\n if (props.systemName !== undefined) return { systemName: props.systemName };\n if (props.bitmap !== undefined) {\n const { source, steps = [], version } = props.bitmap;\n const extent = bitmapExtent(source, steps);\n const finite = Number.isFinite(extent.width) && Number.isFinite(extent.height);\n const width = finite ? Math.max(0, Math.round(extent.width)) : 0;\n const height = finite ? Math.max(0, Math.round(extent.height)) : 0;\n const scale = props.scale !== undefined && props.scale > 0 ? props.scale : 1;\n return {\n bitmap: { source: source?.key ?? null, steps, width, height, ...(version !== undefined ? { version } : {}) },\n resizable: props.resizable ?? false,\n width: width / scale,\n height: height / scale,\n ...(props.interpolation === 'none' ? { interpolation: 'none' } : {}),\n };\n }\n if (props.url !== undefined) return { url: props.url, resizable: props.resizable ?? false, width: props.width ?? 0, height: props.height ?? 0 };\n return { name: props.name ?? '', resizable: props.resizable ?? false };\n}\n\nexport function Image(props: ImageProps): ReactNode {\n const { modifiers } = splitProps(props);\n const environment = useViewEnvironment();\n const redacted = takeModifier(modifiers, 'redacted') ?? environment.redacted;\n // `.palette`: an enclosed filled symbol draws its disc in the secondary\n // level and its glyph in the primary (`.foregroundStyle(.white, .indigo)`).\n const mode = takeModifier(modifiers, 'symbolRenderingMode') ?? environment.symbolRenderingMode;\n const own = imageProps(props);\n const element: Record<string, unknown> = props.systemName !== undefined && mode === 'palette' ? { ...own, renderingMode: 'palette' } : own;\n if (props.accessibilityLabel) element['accessibilityLabel'] = props.accessibilityLabel;\n return applyModifiers(placeholder(sb('image', element), redacted), modifiers);\n}\n\n// ---------------------------------------------------------------------------\n// Label, LabeledContent, Link\n// ---------------------------------------------------------------------------\n\nexport interface LabelProps extends ViewModifiers {\n title: ReactNode;\n systemImage?: string;\n image?: string;\n /** A custom icon view instead of a symbol. */\n icon?: ReactNode;\n}\n\n/** `Label(\"Favorites\", systemImage: \"heart.fill\")`: an 8pt-spaced `HStack` of icon and title. */\nexport function Label(props: LabelProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const environment = useViewEnvironment();\n const style = takeModifier(modifiers, 'labelStyle') ?? environment.labelStyle ?? 'automatic';\n const icon = own.icon ?? (own.systemImage !== undefined ? <Image systemName={own.systemImage} /> : own.image !== undefined ? <Image name={own.image} /> : null);\n const title = typeof own.title === 'string' || typeof own.title === 'number' ? <Text>{own.title}</Text> : own.title;\n if (style === 'iconOnly') {\n // As on iOS, the title stays the icon's accessible name (a toolbar\n // button's), as the Swift shim's label does.\n const name = typeof own.title === 'string' || typeof own.title === 'number' ? String(own.title) : undefined;\n const named =\n own.icon === undefined && name !== undefined\n ? own.systemImage !== undefined\n ? <Image systemName={own.systemImage} accessibilityLabel={name} />\n : own.image !== undefined\n ? <Image name={own.image} accessibilityLabel={name} />\n : icon\n : icon;\n return applyModifiers(named, modifiers);\n }\n if (style === 'titleOnly') return applyModifiers(title, modifiers);\n // The marked icon makes the stack a `Label` to the native renderer, which\n // iOS lays out as one: the icon column of a list row, the icon alone in a\n // bar. An explicit `titleAndIcon` asks for both wherever it is, so it is a\n // plain stack of the two.\n return applyModifiers(\n <HStack spacing={8}>\n {style === 'titleAndIcon' ? icon : styled({ labelIcon: true }, icon)}\n {title}\n </HStack>,\n modifiers,\n );\n}\n\nexport interface LabeledContentProps extends ViewModifiers {\n label: ReactNode;\n value?: ReactNode;\n children?: ReactNode;\n}\n\n/** `LabeledContent(\"Storage\", value: \"2.4 GB\")`: the label, a spacer, the value in the secondary color. */\nexport function LabeledContent(props: LabeledContentProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const label = typeof own.label === 'string' || typeof own.label === 'number' ? <Text>{own.label}</Text> : own.label;\n const content = own.children ?? own.value;\n const value = typeof content === 'string' || typeof content === 'number' ? <Text>{content}</Text> : content;\n return applyModifiers(\n <HStack>\n {label}\n {sb('spacer', { minLength: null })}\n {styled({ foreground: { hierarchical: 2 } }, value)}\n </HStack>,\n modifiers,\n );\n}\n\nexport interface LinkProps extends ViewModifiers {\n destination: string;\n title?: string;\n children?: ReactNode;\n}\n\n/** `Link(\"Visit the website\", destination:)`: a plain button that opens the URL. */\nexport function Link(props: LinkProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const label = own.title !== undefined ? <Text>{own.title}</Text> : own.children;\n return applyModifiers(sb('button', { role: null, style: 'automatic' }, { tap: () => openURL(own.destination) }, label), modifiers);\n}\n","import { Fragment, isValidElement, useContext, useRef, useState, type ReactNode } from 'react';\nimport { readBinding, type BindingValue } from '../binding';\nimport { DismissContext, useViewEnvironment } from '../environment';\nimport { HostTreeContext } from '../host/root';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, takeModifier, type ViewModifiers } from '../modifiers';\nimport { NavigationContext, RegisterDestination, ScreenDepthContext, useNavigation, type NavigationContextValue } from '../navigation-context';\nimport { ListSelectionContext } from './row';\nimport { SplitSelectionContext } from './split';\nimport { Text } from './text';\n\nexport interface NavigationStackProps extends ViewModifiers {\n /** `NavigationStack(path:)`: the pushed values. */\n path?: BindingValue<readonly unknown[]>;\n onPathChange?: (path: readonly unknown[]) => void;\n /** `.navigationDestination(for:)`, for every pushed value. */\n destination?: (value: never) => ReactNode;\n children?: ReactNode;\n}\n\n/** A pushed destination view (`NavigationLink(destination:)`), kept in the path. */\ninterface PushedView {\n view: ReactNode;\n}\n\nconst isPushedView = (value: unknown): value is PushedView => typeof value === 'object' && value !== null && 'view' in value && isValidElement((value as PushedView).view);\n\n/**\n * A pushed value as plain data (strings, finite numbers, booleans, null, and\n * arrays and plain objects of them), or undefined for anything else (a view,\n * a function, a class instance). In a tree another draws (a remote root), a\n * pushed screen carries it as `route`, so the tree that hosts it (`RemoteTree`) can name the screen, in a URL\n * say, and set the path back from it (`setpath`), as SwiftUI's\n * `NavigationPath` of `Codable` values can be saved and restored.\n */\nexport function routeOf(value: unknown, depth = 0): unknown {\n if (depth > 8) return undefined;\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return value;\n if (typeof value === 'number') return Number.isFinite(value) ? value : undefined;\n if (Array.isArray(value)) {\n const items = value.map((item) => routeOf(item, depth + 1));\n return items.every((item) => item !== undefined) ? items : undefined;\n }\n if (typeof value === 'object' && !isPushedView(value)) {\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null) return undefined;\n const out: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value)) {\n if (item === undefined) continue;\n const plain = routeOf(item, depth + 1);\n if (plain === undefined) return undefined;\n out[key] = plain;\n }\n return out;\n }\n return undefined;\n}\n\nexport function NavigationStack(props: NavigationStackProps): ReactNode {\n const enclosing = useNavigation();\n // A stack inside another stack's screen is flattened, as SwiftUI does: its\n // content renders in place and its links push onto the enclosing stack.\n if (enclosing) return <FlattenedStack {...props} />;\n return <OwnStack {...props} />;\n}\n\nfunction FlattenedStack(props: NavigationStackProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n return applyModifiers(\n <>\n {own.destination && <RegisterDestination destination={own.destination} />}\n {own.children}\n </>,\n modifiers,\n );\n}\n\nfunction OwnStack(props: NavigationStackProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n // Routes are for a tree another draws (RemoteTree); a renderer has no use for them.\n const remote = useContext(HostTreeContext)?.remote ?? false;\n const [internalPath, setInternalPath] = useState<readonly unknown[]>([]);\n const [path, setPath] = own.path !== undefined ? readBinding(own.path, own.onPathChange) : [internalPath, setInternalPath];\n const destination = useRef<((value: unknown) => ReactNode) | null>(null);\n destination.current = (own.destination as ((value: unknown) => ReactNode) | undefined) ?? null;\n const context: NavigationContextValue = {\n push: (value) => setPath([...path, value]),\n pop: () => setPath(path.slice(0, -1)),\n path,\n setPath: (next) => setPath(next),\n registerDestination: (builder) => {\n destination.current = builder;\n },\n };\n const screens: ReactNode[] = [\n <Fragment key=\"root\">\n {sb('navscreen', { title: '', displayMode: 'automatic', depth: 0 }, { tap: context.pop }, <ScreenDepthContext.Provider value={0}>{own.children}</ScreenDepthContext.Provider>)}\n </Fragment>,\n ];\n path.forEach((value, index) => {\n const pop = (): void => setPath(path.slice(0, index));\n const route = remote ? routeOf(value) : undefined;\n screens.push(\n <Fragment key={index + 1}>\n {sb(\n 'navscreen',\n { title: '', displayMode: 'automatic', depth: index + 1, ...(route === undefined ? {} : { route }) },\n { tap: pop },\n <DismissContext.Provider value={pop}>\n <ScreenDepthContext.Provider value={index + 1}>\n <PathScreen value={value} destination={destination} />\n </ScreenDepthContext.Provider>\n </DismissContext.Provider>,\n )}\n </Fragment>,\n );\n });\n return applyModifiers(\n sb('navstack', {}, { setpath: (event) => setPath(Array.isArray(event.path) ? event.path : []) }, <NavigationContext.Provider value={context}>{screens}</NavigationContext.Provider>),\n modifiers,\n );\n}\n\n/** Rendered after the root screen, so a destination the root registered is known. */\nfunction PathScreen({ value, destination }: { value: unknown; destination: { current: ((value: unknown) => ReactNode) | null } }): ReactNode {\n if (isPushedView(value)) return value.view;\n return destination.current ? destination.current(value) : null;\n}\n\nexport interface NavigationLinkProps extends ViewModifiers {\n title?: string;\n /** The value to push (`navigationDestination` builds the screen). */\n value?: unknown;\n /** The screen to push. */\n destination?: ReactNode;\n children?: ReactNode;\n}\n\nexport function NavigationLink(props: NavigationLinkProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const navigation = useNavigation();\n const environment = useViewEnvironment();\n const label = own.title !== undefined ? <Text>{own.title}</Text> : own.children;\n // In a split view's sidebar, a `List(selection:)`'s value link selects its\n // value instead of pushing it, and the split shows the detail for it (or,\n // compact, pushes it), as SwiftUI does.\n const listSelection = useContext(ListSelectionContext);\n const sidebar = useContext(SplitSelectionContext) !== null && listSelection !== null && own.destination === undefined && own.value !== undefined;\n const tap = (): void => {\n if (sidebar) {\n listSelection.select(own.value);\n return;\n }\n if (!navigation) return;\n if (own.destination !== undefined) navigation.push({ view: own.destination } satisfies PushedView);\n else navigation.push(own.value);\n };\n // Under `.buttonStyle(.plain)` (its own or around it) the label keeps the\n // foreground it is in instead of the tint.\n const style = takeModifier(modifiers, 'buttonStyle') ?? environment.buttonStyle;\n const linkProps: Record<string, unknown> = style === 'plain' ? { style: 'plain' } : {};\n // A sidebar's link is its row's selection: natively the cell takes the\n // touch and selects itself, as in SwiftUI's split view, rather than the\n // link's button setting the selection after it.\n if (sidebar) linkProps['selects'] = true;\n return applyModifiers(sb('navlink', linkProps, { tap }, label), modifiers);\n}\n","/**\n * `NavigationSplitView`: in a regular width a `navsplit` of two columns (the\n * sidebar's stack and the detail's), the sidebar toggled by the bar button;\n * in a compact width one stack rooted at the sidebar that pushes the detail\n * while the sidebar's list has a selection, as on iOS.\n */\n\nimport { createContext, isValidElement, useLayoutEffect, useRef, useState, type ReactNode } from 'react';\nimport { readBinding, type BindingValue } from '../binding';\nimport { useHorizontalSizeClass } from '../environment';\nimport { withAnimation } from '../host/root';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, type ViewModifiers } from '../modifiers';\nimport { NavigationContext } from '../navigation-context';\nimport { NavigationStack, type NavigationStackProps } from './navigation';\n\nexport type NavigationSplitViewVisibility = 'automatic' | 'all' | 'doubleColumn' | 'detailOnly';\n\n/**\n * What the sidebar's `List(selection:)`s tell their split view: whether\n * each has something selected, and how to clear it. Each list reports under\n * its own key and retracts when it unmounts; the split pushes the detail in\n * a compact width while any of them has a selection.\n */\nexport interface SplitSelection {\n report(key: object, selected: boolean, clear: () => void): void;\n retract(key: object): void;\n}\n\nexport const SplitSelectionContext = createContext<SplitSelection | null>(null);\n\n/**\n * `.navigationSplitViewColumnWidth`: a number is a fixed width; `{ min, ideal,\n * max }` a flexible one, the column starting at `ideal` and, on a Mac, dragged\n * between `min` and `max`.\n */\nexport type SplitColumnWidth = number | { min?: number; ideal: number; max?: number };\n\nexport interface NavigationSplitViewProps extends ViewModifiers {\n sidebar: ReactNode;\n detail: ReactNode;\n columnVisibility?: BindingValue<NavigationSplitViewVisibility>;\n onColumnVisibilityChange?: (visibility: NavigationSplitViewVisibility) => void;\n /**\n * The sidebar column's width (SwiftUI's `.navigationSplitViewColumnWidth` on\n * the sidebar's content); absent, the platform's default (140 on a Mac,\n * 320 on an iPad).\n */\n sidebarWidth?: SplitColumnWidth;\n /**\n * The sidebar was dragged to a new width (a Mac's column divider), once\n * the drag ends: keep it and pass it back as `sidebarWidth`'s `ideal` to\n * start there next time, as a Mac app restores its columns.\n */\n onSidebarWidthChange?: (width: number) => void;\n}\n\n/** The `splitColumnWidth` hint a `sidebarWidth` sends: `{ min?, ideal, max? }`, a fixed width being all three. */\nfunction splitColumnWidthHint(width: SplitColumnWidth): Record<string, number> {\n if (typeof width === 'number') return { min: width, ideal: width, max: width };\n return { ...(width.min !== undefined ? { min: width.min } : {}), ideal: width.ideal, ...(width.max !== undefined ? { max: width.max } : {}) };\n}\n\nexport function NavigationSplitView(props: NavigationSplitViewProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const sizeClass = useHorizontalSizeClass();\n const [selected, setSelected] = useState(false);\n // Each sidebar list's selection and its latest way to clear it (a new\n // closure each render; not state). The split follows whether any has one,\n // so two lists settle instead of overruling each other.\n // One object for the split's life: the lists key their reports by it, and\n // a new one each render would retract and re-report them every pass.\n const reporters = useRef(new Map<object, { selected: boolean; clear: () => void }>());\n // `setSelected` with an unchanged value is a no-op, so the lists settle.\n const settle = (): void => setSelected([...reporters.current.values()].some((entry) => entry.selected));\n const [report] = useState<SplitSelection>(() => {\n return {\n report: (key, nowSelected, clear) => {\n reporters.current.set(key, { selected: nowSelected, clear });\n settle();\n },\n retract: (key) => {\n if (reporters.current.delete(key)) settle();\n },\n };\n });\n // A pop clears the selection and the split's record of it together, so the\n // detail goes in the commit that unmarks the row.\n const clear = (): void => {\n for (const entry of reporters.current.values()) {\n if (!entry.selected) continue;\n entry.clear();\n entry.selected = false;\n }\n settle();\n };\n const [internal, setInternal] = useState<NavigationSplitViewVisibility>('automatic');\n const [visibility, setVisibility] =\n own.columnVisibility !== undefined ? readBinding(own.columnVisibility, own.onColumnVisibilityChange) : [internal, setInternal];\n\n if (sizeClass === 'compact') {\n return applyModifiers(<CompactSplit sidebar={own.sidebar} detail={own.detail} report={report} selected={selected} clear={clear} />, modifiers);\n }\n\n const sidebarVisible = visibility !== 'detailOnly';\n const toggle = (): void => withAnimation(() => setVisibility(sidebarVisible ? 'detailOnly' : 'all'));\n const detail = isValidElement(own.detail) && own.detail.type === NavigationStack ? own.detail : <NavigationStack>{own.detail}</NavigationStack>;\n // The width rides on the sidebar content's styled wrapper, as the shim's modifier sends it.\n const sidebar = own.sidebarWidth !== undefined ? sb('styled', { style: { splitColumnWidth: splitColumnWidthHint(own.sidebarWidth) } }, undefined, own.sidebar) : own.sidebar;\n return applyModifiers(\n sb('navsplit', { sidebarVisible }, { tap: toggle, columnwidth: (event: { width: number }) => own.onSidebarWidthChange?.(event.width) }, [\n <SplitColumn key=\"sidebar\" report={report}>\n <NavigationStack>{sidebar}</NavigationStack>\n </SplitColumn>,\n <SplitColumn key=\"detail\" report={null}>\n {detail}\n </SplitColumn>,\n ]),\n modifiers,\n );\n}\n\n/** A column: its own navigation scope (no enclosing stack), and the sidebar's selection reporting. */\nfunction SplitColumn({ report, children }: { report: SplitSelection | null; children?: ReactNode }): ReactNode {\n return (\n <NavigationContext.Provider value={null}>\n <SplitSelectionContext.Provider value={report}>{children}</SplitSelectionContext.Provider>\n </NavigationContext.Provider>\n );\n}\n\nfunction CompactSplit({\n sidebar,\n detail,\n report,\n selected,\n clear,\n}: {\n sidebar: ReactNode;\n detail: ReactNode;\n report: SplitSelection;\n selected: boolean;\n clear: () => void;\n}): ReactNode {\n // Pushes made from the detail, after it. A detail that is a NavigationStack\n // with a path binding keeps them there, as it would in its own column in a\n // regular width: the app sees the same path either way (and can set it).\n const [internal, setInternal] = useState<readonly unknown[]>([]);\n const detailStack = isValidElement(detail) && detail.type === NavigationStack ? (detail.props as NavigationStackProps) : null;\n const [extra, setExtra] = detailStack?.path !== undefined ? readBinding(detailStack.path, detailStack.onPathChange) : [internal, setInternal];\n const base = selected ? [{ view: detail }] : [];\n const path = [...base, ...extra];\n const setPath = (next: readonly unknown[]): void => {\n if (selected && next.length === 0) {\n setExtra([]);\n clear();\n return;\n }\n setExtra(next.slice(base.length));\n };\n // Only the sidebar reports its selection: the screens pushed over it (the\n // detail, and what the detail pushes) are outside it, so a selectable list\n // there (a folder's, for Select) keeps its links pushing.\n return (\n <NavigationContext.Provider value={null}>\n <SplitSelectionContext.Provider value={null}>\n <NavigationStack path={[path, setPath]}>\n <SplitSelectionContext.Provider value={report}>{sidebar}</SplitSelectionContext.Provider>\n </NavigationStack>\n </SplitSelectionContext.Provider>\n </NavigationContext.Provider>\n );\n}\n\n/**\n * Used by `List(selection:)`: tells the enclosing split view whether the\n * sidebar has a selection. A list without a selection binding (a `Form`, a\n * plain list) passes `active: false` and says nothing.\n */\nexport function useReportSplitSelection(\n split: SplitSelection | null,\n selected: boolean,\n clear: () => void,\n active = true,\n): (selected: boolean, clear: () => void) => void {\n const key = useRef({}).current;\n useLayoutEffect(() => {\n if (active) split?.report(key, selected, clear);\n else split?.retract(key);\n });\n useLayoutEffect(() => () => split?.retract(key), [split, key]);\n // A selection made by a tap, reported in the same update as the list's\n // own: a compact split then pushes the detail in the commit that marks the\n // row, rather than in the next one (natively the root screen would change\n // a frame before the push began, and lose its large title at once).\n return (nowSelected, nowClear) => {\n if (active) split?.report(key, nowSelected, nowClear);\n };\n}\n\n/** Presented content (a sheet, a popover, an inspector) is outside its presenter's split column. */\nexport function OutsideSplit({ children }: { children?: ReactNode }): ReactNode {\n return <SplitSelectionContext.Provider value={null}>{children}</SplitSelectionContext.Provider>;\n}\n","/**\n * Sheets and alerts: presented content becomes a root-level `sheet` / `alert`\n * element after the app's tree, as the Swift core emits them.\n */\n\nimport type { Detent, Style } from '@swiftbrowser/web/src/protocol';\nimport { useEffect, type ReactNode } from 'react';\nimport { readBinding, type BindingValue } from './binding';\nimport { DismissContext, withEnvironment } from './environment';\nimport { HOIST_KIND, PREF_KIND } from './host/instance';\nimport { NavigationContext } from './navigation-context';\nimport { OutsideSplit } from './components/split';\nimport { sb } from './host/sb';\nimport { replayStyles, useInheritedStyles } from './inheritedStyle';\n\nexport interface SheetModifier {\n isPresented: BindingValue<boolean>;\n onDismiss?: () => void;\n content: ReactNode;\n /** `.fullScreenCover` */\n fullScreen?: boolean;\n}\n\n/**\n * A sheet, a full-screen cover or a popover. Its content inherits the\n * presenter's environment, as SwiftUI's presentations do: the inherited\n * styles set around the presenter (`inheritedStyle.ts`), then `inherited`,\n * those its own view sets around it, outermost first.\n */\nexport function SheetPresenter({ isPresented, onDismiss, content, fullScreen, inherited }: SheetModifier & { inherited?: readonly Style[] }): ReactNode {\n const around = useInheritedStyles();\n const [presented, setPresented] = readBinding(isPresented);\n if (!presented) return null;\n const dismiss = (): void => {\n setPresented(false);\n onDismiss?.();\n };\n const detents: Detent[] = fullScreen ? ['full'] : ['large'];\n return sb(\n HOIST_KIND,\n undefined,\n undefined,\n sb(\n 'sheet',\n { detents },\n { tap: dismiss },\n replayStyles(\n inherited && inherited.length > 0 ? [...around, ...inherited] : around,\n <NavigationContext.Provider value={null}>\n <OutsideSplit>\n <DismissContext.Provider value={dismiss}>{content}</DismissContext.Provider>\n </OutsideSplit>\n </NavigationContext.Provider>,\n ),\n ),\n 'root',\n );\n}\n\n/** `.presentationDetents([.medium])`, inside a sheet's content. */\nexport type DetentValue = Detent | { height: number } | { fraction: number };\n\nexport function presentationDetents(detents: DetentValue[]): ReactNode {\n const encoded = detents.map(\n (detent): Detent => (typeof detent === 'string' ? detent : 'height' in detent ? `height:${detent.height}` : `fraction:${detent.fraction}`),\n );\n return sb(PREF_KIND, { detents: encoded }, undefined, undefined, 'sheet');\n}\n\nexport interface AlertModifier {\n title: string;\n isPresented: BindingValue<boolean>;\n message?: string;\n /**\n * The buttons, each dismissing the alert when tapped, and any `TextField`s\n * (`.alert { TextField(\"Name\", text: $name); Button(\"Rename\") { } }`),\n * drawn in the card between the message and the buttons.\n */\n actions?: ReactNode;\n /** `.confirmationDialog` */\n style?: 'alert' | 'dialog';\n}\n\nexport function AlertPresenter({ title, isPresented, message, actions, style }: AlertModifier): ReactNode {\n const [presented, setPresented] = readBinding(isPresented);\n if (!presented) return null;\n const dismiss = (): void => setPresented(false);\n return sb(\n HOIST_KIND,\n undefined,\n undefined,\n sb(\n 'alert',\n { title, message: message ?? null, style: style ?? 'alert' },\n { tap: dismiss },\n withEnvironment({ dismissAlert: dismiss }, actions),\n ),\n 'root',\n );\n}\n\n/** `.onAppear` / `.onDisappear` */\nexport function Lifecycle({ onAppear, onDisappear }: { onAppear?: () => void; onDisappear?: () => void }): null {\n useEffect(() => {\n onAppear?.();\n return () => onDisappear?.();\n // Once per mount, like SwiftUI.\n }, []);\n return null;\n}\n","/**\n * `.inspector(isPresented:)`: in a regular width an `inspector` element, the\n * view and a trailing `inspectorpanel` the renderer slides in and out; in a\n * compact width a sheet with the inspector's content.\n */\n\nimport type { ReactNode } from 'react';\nimport { readBinding } from './binding';\nimport { useHorizontalSizeClass } from './environment';\nimport { sb } from './host/sb';\nimport type { InspectorModifier } from './modifiers';\nimport { SheetPresenter } from './presentation';\nimport { OutsideSplit } from './components/split';\n\nexport function Inspector({ isPresented, content, columnWidth, children }: InspectorModifier & { children?: ReactNode }): ReactNode {\n const sizeClass = useHorizontalSizeClass();\n const [presented, setPresented] = readBinding(isPresented);\n if (sizeClass === 'compact') {\n return (\n <>\n {children}\n <SheetPresenter isPresented={[presented, setPresented]} content={content} />\n </>\n );\n }\n // The panel is beside the content, not part of its split column.\n const outside = <OutsideSplit>{content}</OutsideSplit>;\n const panelContent = columnWidth !== undefined ? sb('styled', { style: { inspectorColumnWidth: columnWidth } }, undefined, outside) : outside;\n return sb('inspector', { presented }, undefined, [\n <InspectorPart key=\"content\">{children}</InspectorPart>,\n <InspectorPart key=\"panel\">{sb('inspectorpanel', {}, undefined, panelContent)}</InspectorPart>,\n ]);\n}\n\nfunction InspectorPart({ children }: { children?: ReactNode }): ReactNode {\n return children;\n}\n","/** `.task` and `.onChange(of:)`, as components the modifiers place beside the view. */\n\nimport { useEffect, useRef } from 'react';\n\nexport function Task({ id, action }: { id: unknown; action: (signal: AbortSignal) => unknown }): null {\n const latest = useRef(action);\n latest.current = action;\n useEffect(() => {\n const controller = new AbortController();\n Promise.resolve()\n .then(() => latest.current(controller.signal))\n .catch((error: unknown) => {\n // A cancelled task's rejection is expected, as Swift's CancellationError is.\n if (!controller.signal.aborted) console.error(error);\n });\n return () => controller.abort();\n }, [id]);\n return null;\n}\n\nexport function OnChange({\n value,\n action,\n initial,\n}: {\n value: unknown;\n action: (oldValue: unknown, newValue: unknown) => void;\n initial?: boolean;\n}): null {\n const previous = useRef<{ value: unknown } | null>(null);\n const latest = useRef(action);\n latest.current = action;\n useEffect(() => {\n const last = previous.current;\n previous.current = { value };\n if (last === null) {\n if (initial) latest.current(value, value);\n return;\n }\n if (!Object.is(last.value, value)) latest.current(last.value, value);\n }, [value, initial]);\n return null;\n}\n","/**\n * Named coordinate spaces: `.coordinateSpace(name:)` reports where its view\n * is on screen (a layout-transparent `zstack` with `reportsFrame`), and a\n * `GeometryReader` inside answers `frame({ named })` relative to it.\n */\n\nimport { createContext, useContext, useState, type ReactNode } from 'react';\nimport { sb } from './host/sb';\n\nexport interface SpaceFrame {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/** The named spaces around a view: their frames on screen (null until reported). */\nexport const CoordinateSpacesContext = createContext<Readonly<Record<string, SpaceFrame | null>>>({});\n\nexport function useCoordinateSpaces(): Readonly<Record<string, SpaceFrame | null>> {\n return useContext(CoordinateSpacesContext);\n}\n\nexport function CoordinateSpace({ name, children }: { name: string; children?: ReactNode }): ReactNode {\n const spaces = useContext(CoordinateSpacesContext);\n const [frame, setFrame] = useState<SpaceFrame | null>(null);\n return (\n <CoordinateSpacesContext.Provider value={{ ...spaces, [name]: frame }}>\n {sb(\n 'zstack',\n { alignment: 'center', reportsSize: true, reportsFrame: true },\n {\n geometry: (event) => {\n const next = { x: event.x ?? 0, y: event.y ?? 0, width: event.width, height: event.height };\n if (!frame || frame.x !== next.x || frame.y !== next.y || frame.width !== next.width || frame.height !== next.height) setFrame(next);\n },\n },\n children,\n )}\n </CoordinateSpacesContext.Provider>\n );\n}\n","/**\n * `GeometryReader` and custom `Layout`: both are round trips with the\n * renderer. The engine lays the element out and reports what it found (a\n * `geometry` event with the size, a `layout` event with the children's\n * measurements); the component answers by rendering again.\n */\n\nimport type { Dimension, GeometryEvent, LayoutChildMeasurement, LayoutProposal as ProtocolProposal } from '@swiftbrowser/web/src/protocol';\nimport { useEffect, useLayoutEffect, useRef, useState, type ReactElement, type ReactNode } from 'react';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, type ModifierKey, type ViewModifiers } from '../modifiers';\nimport { unitPoint, type UnitPointValue } from '../values';\nimport { flattenChildren } from './stacks';\nimport { useCoordinateSpaces } from '../coordinateSpace';\n\nexport interface Size {\n width: number;\n height: number;\n}\n\nexport interface Rect extends Size {\n x: number;\n y: number;\n}\n\n/** A reader's safe-area insets, every edge given. */\nexport interface SafeAreaInsets {\n top: number;\n leading: number;\n bottom: number;\n trailing: number;\n}\n\n/** `GeometryProxy`: what the reader's content is told. */\nexport interface GeometryProxy {\n size: Size;\n /**\n * The reader's frame: in its own space (`local`, the default), on the\n * root's screen (`global`), or relative to an enclosing view marked\n * `coordinateSpace=\"name\"` (`{ named: 'name' }`), scrolling included, kept\n * current as the views around it scroll.\n */\n frame(space?: 'local' | 'global' | { named: string }): Rect;\n /**\n * `bounds(of: .scrollView)`: the visible part of the scroll view (or list)\n * the reader is in, in the reader's own coordinates; null outside one.\n */\n bounds(of: 'scrollView'): Rect | null;\n /** How far the device's safe area (the status bar, the home indicator) reaches into the reader. */\n safeAreaInsets: SafeAreaInsets;\n}\n\nexport interface GeometryReaderProps extends ViewModifiers {\n children: (proxy: GeometryProxy) => ReactNode;\n}\n\n/** What the page last reported about a reader. */\nexport interface ReportedGeometry {\n size: Size;\n origin: { x: number; y: number } | null;\n safeArea: SafeAreaInsets;\n /** The enclosing scroll view's visible rectangle on screen, and its axis. */\n scrollView: (Rect & { axis: 'horizontal' | 'vertical' }) | null;\n}\n\nconst NO_INSETS: SafeAreaInsets = { top: 0, leading: 0, bottom: 0, trailing: 0 };\n\nexport const NO_GEOMETRY: ReportedGeometry = { size: { width: 0, height: 0 }, origin: null, safeArea: NO_INSETS, scrollView: null };\n\n/** The reader's record after a `geometry` event. */\nexport function nextGeometry(event: GeometryEvent, reported: ReportedGeometry): ReportedGeometry {\n const hasOrigin = event.x !== undefined && event.y !== undefined;\n return {\n size: { width: event.width, height: event.height },\n origin: hasOrigin ? { x: event.x!, y: event.y! } : reported.origin,\n safeArea: event.safeArea ?? reported.safeArea,\n // A frame report without a scroll view means the reader is in none.\n scrollView: hasOrigin ? (event.scrollView ?? null) : reported.scrollView,\n };\n}\n\n/**\n * The proxy over a reader's record. `onReadFrame` is called when the content\n * reads anything that needs the reader's place on screen.\n */\nexport function geometryProxy(reported: ReportedGeometry, spaces: Readonly<Record<string, { x: number; y: number } | null>>, onReadFrame: () => void): GeometryProxy {\n return {\n size: reported.size,\n frame: (space = 'local') => {\n if (space === 'local') return { x: 0, y: 0, ...reported.size };\n onReadFrame();\n const origin = reported.origin ?? { x: 0, y: 0 };\n if (space === 'global') return { ...origin, ...reported.size };\n const named = spaces[space.named];\n return { x: origin.x - (named?.x ?? 0), y: origin.y - (named?.y ?? 0), ...reported.size };\n },\n bounds: () => {\n onReadFrame();\n const view = reported.scrollView;\n if (!view || !reported.origin) return null;\n return { x: view.x - reported.origin.x, y: view.y - reported.origin.y, width: view.width, height: view.height };\n },\n get safeAreaInsets() {\n onReadFrame();\n return reported.safeArea;\n },\n };\n}\n\n/**\n * `GeometryReader { proxy in }`: fills its proposal and reports its size.\n * The content renders with a zero size first and again with the real one in\n * the same event cycle, before the page paints. A content that reads the\n * global frame, the scroll view's bounds or the safe-area insets asks the\n * page for them from then on.\n */\nexport function GeometryReader(props: GeometryReaderProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const [reported, setReported] = useState<ReportedGeometry>(NO_GEOMETRY);\n const [needsFrame, setNeedsFrame] = useState(false);\n let readFrame = false;\n const proxy = geometryProxy(reported, useCoordinateSpaces(), () => {\n readFrame = true;\n });\n const content = own.children(proxy);\n useEffect(() => {\n if (readFrame && !needsFrame) setNeedsFrame(true);\n });\n return applyModifiers(\n sb(\n 'geometry',\n needsFrame ? { reportsFrame: true } : {},\n {\n geometry: (event) => {\n const next = nextGeometry(event, reported);\n if (JSON.stringify(next) !== JSON.stringify(reported)) setReported(next);\n },\n },\n content,\n ),\n modifiers,\n );\n}\n\n// ---------------------------------------------------------------------------\n// `.onGeometryChange`\n// ---------------------------------------------------------------------------\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- the spec's value type is the transform's to infer\nexport type GeometryChangeHandler = ((proxy: GeometryProxy) => void) | GeometryChangeSpec<any>;\n\nexport interface GeometryChangeSpec<T> {\n /** The `of:` transform: what of the view's geometry the action watches (`proxy.size`, `proxy.frame('global')`…). */\n of: (proxy: GeometryProxy) => T;\n /** Called when the transform's answer changes, with the new and the old value (the first time, both the new). */\n action: (value: T, oldValue: T) => void;\n}\n\n/**\n * `.onGeometryChange(for:of:action:)` (iOS 18): the view in a box that\n * reports its size (and its frame on screen once the transform reads it,\n * kept current as the page scrolls) without changing its layout; the\n * action runs after the render that heard a change, as SwiftUI's does, so it\n * may set state. It runs in the commit (a layout effect), before anything is\n * painted: state it sets renders and lays out synchronously, so a layout\n * that depends on its own measurement settles within the frame, as a\n * `GeometryReader`'s does in SwiftUI, instead of one round per frame with\n * the page painting each. A function form is called with the proxy on\n * every change.\n */\nexport function GeometryChangeView({ handler, children }: { handler: GeometryChangeHandler; children?: ReactNode }): ReactNode {\n const [reported, setReported] = useState<ReportedGeometry>(NO_GEOMETRY);\n const [needsFrame, setNeedsFrame] = useState(false);\n const last = useRef<{ value: unknown } | null>(null);\n const spaces = useCoordinateSpaces();\n let readFrame = false;\n const proxy = geometryProxy(reported, spaces, () => {\n readFrame = true;\n });\n // Nothing is known before the first report; the transform runs from then on.\n const heard = reported !== NO_GEOMETRY;\n const value = heard && typeof handler !== 'function' ? handler.of(proxy) : undefined;\n useLayoutEffect(() => {\n if (readFrame && !needsFrame) setNeedsFrame(true);\n });\n useLayoutEffect(() => {\n if (!heard) return;\n if (typeof handler === 'function') {\n handler(proxy);\n return;\n }\n const previous = last.current;\n if (previous && JSON.stringify(previous.value) === JSON.stringify(value)) return;\n last.current = { value };\n handler.action(value, previous ? previous.value : value);\n });\n return sb(\n 'zstack',\n { alignment: 'center', reportsSize: true, ...(needsFrame ? { reportsFrame: true } : {}) },\n {\n geometry: (event) => {\n const next = nextGeometry(event, reported);\n if (JSON.stringify(next) !== JSON.stringify(reported)) setReported(next);\n },\n },\n children,\n );\n}\n\n// ---------------------------------------------------------------------------\n// Custom layouts\n// ---------------------------------------------------------------------------\n\n/** A proposal axis: points, `Infinity`, or `null` (unspecified). */\nexport interface LayoutProposal {\n width: number | null;\n height: number | null;\n}\n\nexport interface LayoutSubview {\n /** The engine's answers for a zero, unspecified and infinite proposal. */\n min: Size;\n ideal: Size;\n max: Size;\n /** `.layoutPriority` of the subview (0 by default). */\n priority: number;\n /** `.layoutValue(key:value:)`s of the subview (`subview[Key.self]`). */\n values: Readonly<Record<string, unknown>>;\n /** `ViewSpacing`: the space the subview wants beside another, iOS's default 8 between views. */\n spacing: ViewSpacing;\n /** The size for a proposal: `ideal` on an unspecified axis, else clamped to min…max. */\n sizeThatFits(proposal: LayoutProposal): Size;\n /** Place the subview: `at` is the point `anchor` (default top leading) lands on, in the layout's bounds. */\n place(options: { x: number; y: number; anchor?: UnitPointValue; proposal?: LayoutProposal }): void;\n}\n\n/** `ViewSpacing`: what a subview wants between itself and a neighbor. */\nexport interface ViewSpacing {\n /** `distance(to:along:)`: the space between this subview and `next` on an axis. */\n distance(next: ViewSpacing, axis: 'horizontal' | 'vertical'): number;\n}\n\n/** iOS's default space between two views, the renderer's stack spacing when none is given. */\nexport const DEFAULT_VIEW_SPACING: ViewSpacing = { distance: () => 8 };\n\nexport type LayoutGuide = 'leading' | 'horizontalCenter' | 'trailing' | 'top' | 'verticalCenter' | 'bottom' | 'firstTextBaseline' | 'lastTextBaseline';\n\n/** SwiftUI's `Layout` protocol: the two methods, an optional cache shared by them, and explicit alignment guides. */\nexport interface CustomLayout<Cache = unknown> {\n sizeThatFits(proposal: LayoutProposal, subviews: readonly LayoutSubview[], cache: Cache): Size;\n placeSubviews(bounds: Rect, proposal: LayoutProposal, subviews: readonly LayoutSubview[], cache: Cache): void;\n /** `makeCache(subviews:)`: computed once for the subviews, before sizing and placing. */\n makeCache?(subviews: readonly LayoutSubview[]): Cache;\n /**\n * `explicitAlignment(of:in:proposal:subviews:cache:)`: where the layout\n * puts a guide, in its bounds (null: the guide's default). A stack, frame\n * or overlay aligning the layout by that guide uses it.\n */\n explicitAlignment?(guide: LayoutGuide, bounds: Rect, proposal: LayoutProposal, subviews: readonly LayoutSubview[], cache: Cache): number | null;\n /** `spacing(subviews:cache:)`: accepted; the engine spaces the layout like any view (8 by default). */\n spacing?(subviews: readonly LayoutSubview[], cache: Cache): ViewSpacing;\n}\n\n/** What `Layout` reads from each subview's element besides the engine's measurements. */\nexport interface SubviewTraits {\n priority: number;\n values: Record<string, unknown>;\n}\n\nexport interface LayoutProps<Cache = unknown> extends ViewModifiers {\n layout: CustomLayout<Cache>;\n children?: ReactNode;\n}\n\n/** Each subview's `layoutPriority` and `layoutValue`s, read from its element's props. */\nfunction subviewTraits(children: ReactNode): SubviewTraits[] {\n return flattenChildren(children).map((element: ReactElement) => {\n const props = element.props as { layoutPriority?: number; layoutValue?: Record<string, unknown> };\n return { priority: props.layoutPriority ?? 0, values: props.layoutValue ?? {} };\n });\n}\n\ninterface LayoutRecord {\n proposal: LayoutProposal;\n children: LayoutChildMeasurement[];\n}\n\nconst fromDimension = (value: Dimension | null): number | null => (value === 'infinity' ? Infinity : value);\nconst toDimension = (value: number): Dimension => (Number.isFinite(value) ? Math.round(value * 100) / 100 : 'infinity');\nconst toSize = (size: { width: Dimension; height: Dimension }): Size => ({\n width: fromDimension(size.width) ?? 0,\n height: fromDimension(size.height) ?? 0,\n});\n\nconst GUIDES: readonly LayoutGuide[] = ['leading', 'horizontalCenter', 'trailing', 'top', 'verticalCenter', 'bottom', 'firstTextBaseline', 'lastTextBaseline'];\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.min(Math.max(value, min), max);\n}\n\n/** Run the layout for a record: the size, the frames and the min/ideal/max sizes. */\nexport function answerLayout<Cache>(\n layout: CustomLayout<Cache>,\n record: LayoutRecord,\n traits: readonly SubviewTraits[] = [],\n): {\n size: Size;\n frames: Rect[];\n sizes: { min: Size; ideal: Size; max: Size; atWidth?: Size };\n guides: Partial<Record<LayoutGuide, number>>;\n} {\n const frames: (Rect | null)[] = record.children.map(() => null);\n const subviews: LayoutSubview[] = record.children.map((measurement, index) => {\n const min = toSize(measurement.min);\n const ideal = toSize(measurement.ideal);\n const max = toSize(measurement.max);\n const sizeThatFits = (proposal: LayoutProposal): Size => ({\n width: proposal.width === null ? ideal.width : clamp(proposal.width, min.width, max.width),\n height: proposal.height === null ? ideal.height : clamp(proposal.height, min.height, max.height),\n });\n return {\n min,\n ideal,\n max,\n priority: traits[index]?.priority ?? 0,\n values: traits[index]?.values ?? {},\n spacing: DEFAULT_VIEW_SPACING,\n sizeThatFits,\n place: ({ x, y, anchor, proposal }) => {\n const size = sizeThatFits(proposal ?? { width: null, height: null });\n const point = unitPoint(anchor ?? 'topLeading');\n frames[index] = { x: x - point.x * size.width, y: y - point.y * size.height, ...size };\n },\n };\n });\n const cache = (layout.makeCache ? layout.makeCache(subviews) : undefined) as Cache;\n const measure = (proposal: LayoutProposal): Size => layout.sizeThatFits(proposal, subviews, cache);\n const size = measure(record.proposal);\n layout.placeSubviews({ x: 0, y: 0, ...size }, record.proposal, subviews, cache);\n const placed = frames.map((frame, index) => {\n if (frame) return frame;\n // An unplaced subview sits centered, as in SwiftUI.\n const own = subviews[index]!.sizeThatFits({ width: size.width, height: size.height });\n return { x: (size.width - own.width) / 2, y: (size.height - own.height) / 2, ...own };\n });\n const guides: Partial<Record<LayoutGuide, number>> = {};\n if (layout.explicitAlignment) {\n const bounds = { x: 0, y: 0, ...size };\n for (const guide of GUIDES) {\n const value = layout.explicitAlignment(guide, bounds, record.proposal, subviews, cache);\n if (value !== null && value !== undefined && Number.isFinite(value)) guides[guide] = value;\n }\n }\n const sizes: { min: Size; ideal: Size; max: Size; atWidth?: Size } = {\n min: measure({ width: 0, height: 0 }),\n ideal: measure({ width: null, height: null }),\n max: measure({ width: Infinity, height: Infinity }),\n };\n // The size at the answered width with no height: what a grid or stack\n // measuring the layout at the width it has asks (the Swift core sends the\n // same, docs/ops-protocol.md \"`layout` (custom `Layout`)\").\n const { width, height } = record.proposal;\n if (width !== null && Number.isFinite(width) && height !== null) sizes.atWidth = measure({ width, height: null });\n return { size, frames: placed, guides, sizes };\n}\n\n/**\n * `Layout`: a custom layout the engine asks for sizes and frames. Until the\n * first answer the element fills its proposal; then it answers from the\n * layout's own `sizeThatFits` and `placeSubviews`.\n */\nexport function Layout<Cache = unknown>(props: LayoutProps<Cache>): ReactNode {\n const { own, modifiers } = splitProps(props);\n const [record, setRecord] = useState<LayoutRecord | null>(null);\n let layoutProps: Record<string, unknown> = { proposal: null, size: null, frames: null };\n // The explicit guides the last answer gave, as alignment guides of the layout's box.\n const guideModifiers: [ModifierKey, unknown][] = [];\n if (record) {\n const answer = answerLayout(own.layout, record, subviewTraits(own.children));\n for (const [guide, value] of Object.entries(answer.guides)) guideModifiers.push(['alignmentGuide', { guide, value: () => value }]);\n const encode = (size: Size): { width: Dimension; height: Dimension } => ({ width: toDimension(size.width), height: toDimension(size.height) });\n const round = (value: number): number => Math.round(value * 100) / 100;\n layoutProps = {\n proposal: {\n width: record.proposal.width === null ? null : toDimension(record.proposal.width),\n height: record.proposal.height === null ? null : toDimension(record.proposal.height),\n },\n size: { width: round(answer.size.width), height: round(answer.size.height) },\n frames: answer.frames.map((frame) => ({ x: round(frame.x), y: round(frame.y), width: round(frame.width), height: round(frame.height) })),\n sizes: {\n min: encode(answer.sizes.min),\n ideal: encode(answer.sizes.ideal),\n max: encode(answer.sizes.max),\n ...(answer.sizes.atWidth ? { atWidth: encode(answer.sizes.atWidth) } : {}),\n },\n };\n }\n return applyModifiers(\n sb(\n 'layout',\n layoutProps,\n {\n layout: (event) => {\n const proposal: ProtocolProposal = event.proposal;\n setRecord({\n proposal: { width: fromDimension(proposal.width), height: fromDimension(proposal.height) },\n children: event.children,\n });\n },\n },\n own.children,\n ),\n [...guideModifiers, ...modifiers],\n );\n}\n","/**\n * `.visualEffect { content, proxy in … }` and `.scrollTransition { content, phase in … }`.\n *\n * Both draw effects that depend on where the view is, without changing its\n * layout. A visual effect's view is wrapped in a layout-transparent box that\n * reports its frame on screen (and the visible rectangle of the scroll view\n * it is in), kept current as the page scrolls; the effects apply inside that\n * box, so they never move what is measured. A scroll transition's three\n * phases go to the renderer, which draws them as the view scrolls.\n */\n\nimport type { Rotation3D, ScrollTransition, ScrollTransitionEffect, Style } from '@swiftbrowser/web/src/protocol';\nimport { useEffect, useState, type ReactNode } from 'react';\nimport { useCoordinateSpaces } from './coordinateSpace';\nimport { geometryProxy, nextGeometry, NO_GEOMETRY, type GeometryProxy, type ReportedGeometry } from './components/geometry';\nimport { sb } from './host/sb';\nimport { unitPoint, type UnitPoint, type UnitPointValue } from './values';\n\ninterface EffectValues {\n offsetX: number;\n offsetY: number;\n scaleX: number;\n scaleY: number;\n scaleAnchor?: UnitPoint;\n rotation: number;\n rotationAnchor?: UnitPoint;\n rotation3D?: Rotation3D;\n opacity: number;\n blur: number;\n brightness: number;\n contrast: number;\n saturation: number;\n grayscale: number;\n hueRotation: number;\n}\n\nconst IDENTITY: EffectValues = {\n offsetX: 0,\n offsetY: 0,\n scaleX: 1,\n scaleY: 1,\n rotation: 0,\n opacity: 1,\n blur: 0,\n brightness: 0,\n contrast: 1,\n saturation: 1,\n grayscale: 0,\n hueRotation: 0,\n};\n\n/**\n * SwiftUI's `VisualEffect`: the effects a `visualEffect` or `scrollTransition`\n * closure returns, chained from the `effect` it is handed\n * (`effect.offset({ y: 20 }).opacity(0.5)`). Chained effects compose:\n * offsets and rotations add, scales and opacities multiply.\n */\nexport class VisualEffect {\n /** @internal */\n constructor(readonly values: EffectValues = IDENTITY) {}\n\n private with(patch: Partial<EffectValues>): VisualEffect {\n return new VisualEffect({ ...this.values, ...patch });\n }\n\n offset(offset: { x?: number; y?: number }): VisualEffect {\n return this.with({ offsetX: this.values.offsetX + (offset.x ?? 0), offsetY: this.values.offsetY + (offset.y ?? 0) });\n }\n\n scaleEffect(scale: number | { x?: number; y?: number }, anchor?: UnitPointValue): VisualEffect {\n const x = typeof scale === 'number' ? scale : (scale.x ?? 1);\n const y = typeof scale === 'number' ? scale : (scale.y ?? 1);\n return this.with({ scaleX: this.values.scaleX * x, scaleY: this.values.scaleY * y, ...(anchor !== undefined ? { scaleAnchor: unitPoint(anchor) } : {}) });\n }\n\n /** Degrees. */\n rotationEffect(degrees: number, anchor?: UnitPointValue): VisualEffect {\n return this.with({ rotation: this.values.rotation + degrees, ...(anchor !== undefined ? { rotationAnchor: unitPoint(anchor) } : {}) });\n }\n\n rotation3DEffect(spec: { angle: number; axis: { x: number; y: number; z: number }; anchor?: UnitPointValue; perspective?: number }): VisualEffect {\n const rotation: Rotation3D = { angle: spec.angle, axis: spec.axis };\n if (spec.anchor !== undefined) rotation.anchor = unitPoint(spec.anchor);\n if (spec.perspective !== undefined) rotation.perspective = spec.perspective;\n return this.with({ rotation3D: rotation });\n }\n\n opacity(opacity: number): VisualEffect {\n return this.with({ opacity: this.values.opacity * opacity });\n }\n\n blur(radius: number): VisualEffect {\n return this.with({ blur: this.values.blur + radius });\n }\n\n brightness(amount: number): VisualEffect {\n return this.with({ brightness: this.values.brightness + amount });\n }\n\n contrast(amount: number): VisualEffect {\n return this.with({ contrast: this.values.contrast * amount });\n }\n\n saturation(amount: number): VisualEffect {\n return this.with({ saturation: this.values.saturation * amount });\n }\n\n grayscale(amount: number): VisualEffect {\n return this.with({ grayscale: Math.min(1, this.values.grayscale + amount) });\n }\n\n /** Degrees. */\n hueRotation(degrees: number): VisualEffect {\n return this.with({ hueRotation: this.values.hueRotation + degrees });\n }\n}\n\n/** The effect a closure starts from. */\nexport const EMPTY_EFFECT = new VisualEffect();\n\nconst round = (value: number): number => Math.round(value * 1000) / 1000;\n\n/** The `styled` style that draws `values` (identity fields left out). */\nexport function effectStyle(values: EffectValues): Style {\n const style: Style = {};\n if (values.offsetX !== 0 || values.offsetY !== 0) style.offset = { x: round(values.offsetX), y: round(values.offsetY) };\n if (values.scaleX !== 1 || values.scaleY !== 1) {\n style.scale = { x: round(values.scaleX), y: round(values.scaleY) };\n if (values.scaleAnchor) style.scaleAnchor = values.scaleAnchor;\n }\n if (values.rotation !== 0) {\n style.rotation = round(values.rotation);\n if (values.rotationAnchor) style.rotationAnchor = values.rotationAnchor;\n }\n if (values.rotation3D && values.rotation3D.angle !== 0) style.rotation3D = { ...values.rotation3D, angle: round(values.rotation3D.angle) };\n if (values.opacity !== 1) style.opacity = round(values.opacity);\n if (values.blur !== 0) style.blur = round(values.blur);\n if (values.brightness !== 0) style.brightness = round(values.brightness);\n if (values.contrast !== 1) style.contrast = round(values.contrast);\n if (values.saturation !== 1) style.saturation = round(values.saturation);\n if (values.grayscale !== 0) style.grayscale = round(values.grayscale);\n if (values.hueRotation !== 0) style.hueRotation = round(values.hueRotation);\n return style;\n}\n\n// ---------------------------------------------------------------------------\n// The measured box\n// ---------------------------------------------------------------------------\n\n/**\n * Renders `children` styled by `style(reported, markRead)` inside a box that\n * reports its geometry; the frame on screen is asked for once `markRead` is\n * called.\n */\nfunction EffectBox({ render, children }: { render: (reported: ReportedGeometry, markRead: () => void) => Style; children?: ReactNode }): ReactNode {\n const [reported, setReported] = useState<ReportedGeometry>(NO_GEOMETRY);\n const [needsFrame, setNeedsFrame] = useState(false);\n let readFrame = false;\n const style = render(reported, () => {\n readFrame = true;\n });\n useEffect(() => {\n if (readFrame && !needsFrame) setNeedsFrame(true);\n });\n const content = Object.keys(style).length > 0 ? sb('styled', { style }, undefined, children) : children;\n return sb(\n 'zstack',\n { alignment: 'center', reportsSize: true, ...(needsFrame ? { reportsFrame: true } : {}) },\n {\n geometry: (event) => {\n const next = nextGeometry(event, reported);\n if (JSON.stringify(next) !== JSON.stringify(reported)) setReported(next);\n },\n },\n content,\n );\n}\n\nexport type VisualEffectClosure = (effect: VisualEffect, proxy: GeometryProxy) => VisualEffect;\n\n/** `.visualEffect { content, proxy in … }`. */\nexport function VisualEffectView({ effect, children }: { effect: VisualEffectClosure; children?: ReactNode }): ReactNode {\n const spaces = useCoordinateSpaces();\n return <EffectBox render={(reported, markRead) => effectStyle(effect(EMPTY_EFFECT, geometryProxy(reported, spaces, markRead)).values)}>{children}</EffectBox>;\n}\n\n// ---------------------------------------------------------------------------\n// Scroll transitions\n// ---------------------------------------------------------------------------\n\n/**\n * Where a view is in its scroll view: `topLeading` (going out past the top or\n * leading edge), `identity` (in view) or `bottomTrailing`, with `value` -1, 0\n * or 1. An `interactive` transition draws the effect partway between phases\n * as the view crosses the edge.\n */\nexport interface ScrollTransitionPhase {\n phase: 'topLeading' | 'identity' | 'bottomTrailing';\n value: -1 | 0 | 1;\n isIdentity: boolean;\n}\n\nconst PHASES = {\n topLeading: { phase: 'topLeading', value: -1, isIdentity: false },\n identity: { phase: 'identity', value: 0, isIdentity: true },\n bottomTrailing: { phase: 'bottomTrailing', value: 1, isIdentity: false },\n} as const satisfies Record<string, ScrollTransitionPhase>;\n\nexport type ScrollTransitionClosure = (effect: VisualEffect, phase: ScrollTransitionPhase) => VisualEffect;\n\nexport interface ScrollTransitionSpec {\n transition: ScrollTransitionClosure;\n /**\n * `interactive` (the default) follows the scrolling, drawing the effect\n * partway as the view crosses the edge; `animated` switches phases once the\n * view is partly out; `identity` never leaves the identity phase.\n */\n configuration?: 'interactive' | 'animated' | 'identity';\n /** The axis to follow; the scroll view's own by default. */\n axis?: 'horizontal' | 'vertical';\n}\n\n/**\n * `.scrollTransition { content, phase in … }`: the closure called once for\n * each phase, and the three effects handed to the renderer, which draws them\n * as the view scrolls (between phases by how far out it is, for\n * `interactive`) without asking the app on every step.\n */\nexport function ScrollTransitionView({ spec, children }: { spec: ScrollTransitionSpec; children?: ReactNode }): ReactNode {\n const phase = (which: keyof typeof PHASES): ScrollTransitionEffect => effectStyle(spec.transition(EMPTY_EFFECT, PHASES[which]).values);\n const transition: ScrollTransition = {\n configuration: spec.configuration ?? 'interactive',\n identity: phase('identity'),\n topLeading: phase('topLeading'),\n bottomTrailing: phase('bottomTrailing'),\n };\n if (spec.axis) transition.axis = spec.axis;\n return sb('styled', { style: { scrollTransition: transition } }, undefined, children);\n}\n","/**\n * Modifiers for a page with a mouse and a keyboard, and the effects the\n * renderer draws for them: hover, tooltips, cursors, keyboard shortcuts,\n * key presses, symbol effects, matched geometry, haptics.\n */\n\nimport type { SymbolEffectStyle } from '@swiftbrowser/web/src/protocol';\nimport { useEffect, useId, useRef, type ReactNode } from 'react';\nimport { useCoordinateSpaces } from './coordinateSpace';\nimport { sb } from './host/sb';\nimport { styled, type ContinuousHoverModifier } from './modifiers';\n\nexport function Hover({ action, children }: { action: (hovering: boolean) => void; children?: ReactNode }): ReactNode {\n return sb('styled', { style: { hover: true } }, { hover: (event) => action(event.value) }, children);\n}\n\n/**\n * `.onContinuousHover(coordinateSpace:perform:)`: the box sends where the\n * mouse is as it moves (one event per frame) and that it left. `local` and\n * `global` are the renderer's; a named space is the global point less the\n * frame `coordinateSpace` reported for that name, as a drag's is.\n */\nexport function ContinuousHover({ spec, children }: { spec: ContinuousHoverModifier; children?: ReactNode }): ReactNode {\n const spaces = useCoordinateSpaces();\n const space = spec.coordinateSpace ?? 'local';\n const named = typeof space === 'object' ? spaces[space.named] : null;\n const inSpace = (point: { x: number; y: number }): { x: number; y: number } => (named ? { x: point.x - named.x, y: point.y - named.y } : point);\n return sb(\n 'styled',\n { style: { continuousHover: space === 'local' ? 'local' : 'global' } },\n { continuoushover: (event) => spec.action(event.phase === 'active' ? { kind: 'active', location: inSpace(event.location) } : { kind: 'ended' }) },\n children,\n );\n}\n\nconst CURSORS: Record<string, string> = {\n link: 'pointer',\n automatic: 'auto',\n default: 'default',\n text: 'text',\n verticalText: 'vertical-text',\n grabIdle: 'grab',\n grabActive: 'grabbing',\n rectSelection: 'crosshair',\n columnResize: 'col-resize',\n rowResize: 'row-resize',\n};\n\nexport function cursorFor(style: string): string {\n return CURSORS[style] ?? style;\n}\n\n// ---------------------------------------------------------------------------\n// Symbol effects\n// ---------------------------------------------------------------------------\n\nexport interface SymbolEffectModifier {\n effect: SymbolEffectStyle['effect'];\n direction?: 'up' | 'down';\n speed?: number;\n repeat?: number | 'forever';\n /** `.symbolEffect(_:isActive:)`: the effect runs while true (true by default). */\n isActive?: boolean;\n /** `.symbolEffect(_:value:)`: the effect plays once each time this changes. */\n value?: unknown;\n}\n\nexport function SymbolEffect({ spec, children }: { spec: SymbolEffectModifier; children?: ReactNode }): ReactNode {\n const serial = useRef<{ value: unknown; count: number } | null>(null);\n const discrete = 'value' in spec;\n if (discrete) {\n if (!serial.current) serial.current = { value: spec.value, count: 0 };\n else if (!Object.is(serial.current.value, spec.value)) serial.current = { value: spec.value, count: serial.current.count + 1 };\n }\n if (!discrete && spec.isActive === false) return children;\n const effect: SymbolEffectStyle = { effect: spec.effect };\n if (spec.direction) effect.direction = spec.direction;\n if (spec.speed !== undefined) effect.speed = spec.speed;\n if (spec.repeat !== undefined) effect.repeat = spec.repeat;\n if (discrete) effect.trigger = serial.current!.count;\n return styled({ symbolEffect: effect }, children);\n}\n\n// ---------------------------------------------------------------------------\n// Matched geometry\n// ---------------------------------------------------------------------------\n\n/** `@Namespace`: a namespace for `matchedGeometryEffect` ids. */\nexport function useNamespace(): string {\n return useId();\n}\n\n// ---------------------------------------------------------------------------\n// Keyboard\n// ---------------------------------------------------------------------------\n\nexport type KeyEquivalent = 'return' | 'escape' | 'delete' | 'tab' | 'space' | 'upArrow' | 'downArrow' | 'leftArrow' | 'rightArrow' | (string & {});\nexport type EventModifier = 'command' | 'shift' | 'option' | 'control';\n\nexport interface KeyboardShortcut {\n key: KeyEquivalent;\n /** `command` by default, as SwiftUI's; `[]` for none. `command` is Ctrl off Apple platforms. */\n modifiers?: EventModifier[];\n}\n\nconst KEY_NAMES: Record<string, string> = {\n return: 'Enter',\n escape: 'Escape',\n delete: 'Backspace',\n tab: 'Tab',\n space: ' ',\n upArrow: 'ArrowUp',\n downArrow: 'ArrowDown',\n leftArrow: 'ArrowLeft',\n rightArrow: 'ArrowRight',\n};\n\nconst isApple = (): boolean => typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent);\n\nexport function matchesKey(event: KeyboardEvent, key: KeyEquivalent): boolean {\n const name = KEY_NAMES[key] ?? key;\n return name.length === 1 ? event.key.toLowerCase() === name.toLowerCase() : event.key === name;\n}\n\nfunction matchesShortcut(event: KeyboardEvent, shortcut: KeyboardShortcut): boolean {\n if (!matchesKey(event, shortcut.key)) return false;\n const wanted = new Set(shortcut.modifiers ?? ['command']);\n const command = isApple() ? event.metaKey : event.ctrlKey;\n const control = isApple() ? event.ctrlKey : false;\n return (\n command === wanted.has('command') &&\n event.shiftKey === wanted.has('shift') &&\n event.altKey === wanted.has('option') &&\n control === (isApple() && wanted.has('control'))\n );\n}\n\n/** A shortcut that runs `action` while the component is mounted. */\nexport function useKeyboardShortcut(shortcut: KeyboardShortcut | undefined, action: () => void): void {\n const latest = useRef(action);\n latest.current = action;\n const key = shortcut ? `${shortcut.key}:${(shortcut.modifiers ?? ['command']).join('+')}` : '';\n useEffect(() => {\n if (!shortcut || typeof document === 'undefined') return;\n const onKey = (event: KeyboardEvent): void => {\n if (event.defaultPrevented || !matchesShortcut(event, shortcut)) return;\n event.preventDefault();\n latest.current();\n };\n document.addEventListener('keydown', onKey);\n return () => document.removeEventListener('keydown', onKey);\n }, [key]);\n}\n\nexport interface KeyPress {\n key: string;\n characters: string;\n modifiers: EventModifier[];\n phase: 'down' | 'repeat';\n}\n\nexport interface OnKeyPressModifier {\n /** Only these keys (`KeyEquivalent`s or characters); every key when absent. */\n keys?: KeyEquivalent[];\n /** Return `'handled'` to stop the key there. */\n action: (press: KeyPress) => 'handled' | 'ignored' | void;\n}\n\n/**\n * `.onKeyPress`: keys pressed while the view is on screen and no text field\n * has the focus (the page has no focus for a plain view, so the screen\n * stands in for it).\n */\nexport function KeyPressListener({ spec }: { spec: OnKeyPressModifier }): null {\n const latest = useRef(spec);\n latest.current = spec;\n useEffect(() => {\n if (typeof document === 'undefined') return;\n const onKey = (event: KeyboardEvent): void => {\n const target = event.target as HTMLElement | null;\n if (event.defaultPrevented || target?.closest('input, textarea, [contenteditable]')) return;\n const { keys, action } = latest.current;\n if (keys && !keys.some((key) => matchesKey(event, key))) return;\n const modifiers: EventModifier[] = [];\n if (event.metaKey) modifiers.push('command');\n if (event.shiftKey) modifiers.push('shift');\n if (event.altKey) modifiers.push('option');\n if (event.ctrlKey) modifiers.push('control');\n const result = action({ key: event.key, characters: event.key.length === 1 ? event.key : '', modifiers, phase: event.repeat ? 'repeat' : 'down' });\n if (result === 'handled') event.preventDefault();\n };\n document.addEventListener('keydown', onKey);\n return () => document.removeEventListener('keydown', onKey);\n }, []);\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Sensory feedback\n// ---------------------------------------------------------------------------\n\nexport type SensoryFeedback = 'success' | 'warning' | 'error' | 'selection' | 'increase' | 'decrease' | 'start' | 'stop' | 'alignment' | 'levelChange' | 'impact';\n\nconst PATTERNS: Record<SensoryFeedback, number | number[]> = {\n success: [12, 60, 18],\n warning: [18, 80, 18],\n error: [24, 50, 24, 50, 24],\n selection: 8,\n increase: 10,\n decrease: 10,\n start: 14,\n stop: 14,\n alignment: 6,\n levelChange: 10,\n impact: 16,\n};\n\n/** `.sensoryFeedback(_:trigger:)`: a vibration where the browser and device have one (Android), nothing elsewhere. */\nexport function SensoryFeedbackPlayer({ feedback, trigger }: { feedback: SensoryFeedback; trigger: unknown }): null {\n const first = useRef(true);\n useEffect(() => {\n if (first.current) {\n first.current = false;\n return;\n }\n if (typeof navigator !== 'undefined' && typeof navigator.vibrate === 'function') navigator.vibrate(PATTERNS[feedback]);\n }, [trigger, feedback]);\n return null;\n}\n","/**\n * View modifiers as props. Every component accepts them, and applies them in\n * the order they are written, innermost first, exactly like a SwiftUI\n * modifier chain reads: `<Text padding background=\"red\" />` is\n * `Text().padding().background(.red)`. Each modifier that changes layout or\n * style wraps the view in a `styled` element, as the Swift shim does; the\n * environment ones wrap it in a context; the navigation and presentation ones\n * attach preferences and hoisted elements beside it.\n */\n\nimport type {\n Animation,\n ButtonStyle,\n EdgeInsets,\n FixedSize,\n FontWeight,\n FrameAlignment,\n GestureMode,\n DragPhase,\n TouchPoint as ProtocolTouchPoint,\n ImageScale,\n PickerStyle,\n ToggleStyle,\n Style,\n TextAlignment,\n ToolbarPlacement,\n Transition,\n} from '@swiftbrowser/web/src/protocol';\nimport { Children, Fragment, cloneElement, createElement, isValidElement, useRef, type ReactElement, type ReactNode } from 'react';\nimport type { BindingValue } from './binding';\nimport { readBinding } from './binding';\nimport { useViewEnvironment, withEnvironment, type ControlSize, type KeyboardType, type SymbolRenderingMode, type TextContentType, type TextInputHints, type ViewEnvironment } from './environment';\nimport { Draggable, DropDestination } from './dragDrop';\nimport { FileImporterPresenter, type FileImporterModifier } from './fileImporter';\nimport { FileExporterPresenter, type FileExporterModifier } from './fileExporter';\nimport { Inspector } from './inspector';\nimport { OnChange, Task } from './lifecycle';\nimport { ScrollTarget } from './scrollReader';\nimport { CoordinateSpace, useCoordinateSpaces } from './coordinateSpace';\nimport {\n edgeHiddenSettings,\n edgeStyleSettings,\n marginSettings,\n withScrollSettings,\n type ContentMarginsValue,\n type ScrollEdgeEffectHiddenValue,\n type ScrollEdgeEffectStyleValue,\n} from './scrollEnvironment';\nimport { ScrollTransitionView, VisualEffectView, type ScrollTransitionClosure, type ScrollTransitionSpec, type VisualEffectClosure } from './visualEffect';\nimport { GeometryChangeView, type GeometryChangeHandler } from './components/geometry';\nimport {\n ContinuousHover,\n Hover,\n KeyPressListener,\n SensoryFeedbackPlayer,\n SymbolEffect,\n cursorFor,\n type KeyEquivalent,\n type KeyboardShortcut,\n type OnKeyPressModifier,\n type SensoryFeedback,\n type SymbolEffectModifier,\n} from './pointer';\nimport { HOIST_KIND, PREF_KIND } from './host/instance';\nimport { INHERITED_STYLE_KEYS, InheritStyle, PRESENTATION_KEYS, styleOf } from './inheritedStyle';\nimport { sb } from './host/sb';\nimport { RegisterDestination } from './navigation-context';\nimport {\n AlertPresenter,\n Lifecycle,\n SheetPresenter,\n presentationDetents,\n type AlertModifier,\n type DetentValue,\n type SheetModifier,\n} from './presentation';\nimport {\n color,\n font,\n frame,\n padding,\n rgb,\n shapeStyle,\n unitPoint,\n type ColorValue,\n type UnitPointValue,\n type FontValue,\n type FrameValue,\n type PaddingValue,\n type StyleValue,\n} from './values';\n\n/** A shape component carries its protocol kind; `RoundedRectangle` reads the radius from its props. */\nexport interface ShapeSpec {\n kind: string;\n cornerRadius: number | null;\n}\n\n/** `.background(style, in: shape)` */\nexport interface BackgroundInShape {\n fill: StyleValue;\n in: ReactElement;\n}\n\nexport type BackgroundValue = StyleValue | BackgroundInShape | ReactElement;\n\nexport interface SearchableModifier {\n text: BindingValue<string>;\n onChange?: (text: string) => void;\n prompt?: string;\n}\n\n/** `CoordinateSpace`: a view's own, the screen's, or one named with `coordinateSpace` on an ancestor. */\nexport type CoordinateSpaceValue = 'local' | 'global' | { named: string };\n\n/** `DragGesture.Value`: the renderer's drag event, its points in the gesture's `coordinateSpace` (the view's own by default). */\nexport interface DragValue {\n translation: { width: number; height: number };\n location: { x: number; y: number };\n startLocation: { x: number; y: number };\n velocity: { width: number; height: number };\n}\n\n/** `HoverPhase`: where a mouse is over the view, or that it left. */\nexport type HoverPhase = { kind: 'active'; location: { x: number; y: number } } | { kind: 'ended' };\n\n/** `.onContinuousHover(coordinateSpace:perform:)` with a space other than the view's own. */\nexport interface ContinuousHoverModifier {\n /** The space of an `active` phase's `location`: the view's own by default; `global` or a `{ named }` space stays put as the view moves. */\n coordinateSpace?: CoordinateSpaceValue;\n action: (phase: HoverPhase) => void;\n}\n\nexport interface DragGestureModifier {\n minimumDistance?: number;\n /**\n * `DragGesture(coordinateSpace:)`: the space of `location` and\n * `startLocation`. `local` (the default) moves with the view when the drag\n * moves it; `global` or a `{ named }` space stays put, as a canvas needs.\n */\n coordinateSpace?: CoordinateSpaceValue;\n onChanged?: (value: DragValue) => void;\n onEnded?: (value: DragValue) => void;\n}\n\n/** `.onTapGesture(count:perform:)`: `count` taps (1 by default; 2 is a double tap) run `action`. */\n/** `{ count, action }`, or `{ count, perform }` to hear where the tap landed (`location` on the `tapgesture`). */\nexport type TapGestureModifier = { count?: number; action: () => void } | { count?: number; perform: (location: { x: number; y: number }) => void };\n\n/**\n * The gesture `.simultaneousGesture` or `.highPriorityGesture` takes, as the\n * gesture modifier it would otherwise be: `{ dragGesture: { … } }`,\n * `{ magnifyGesture: { … } }`, `{ rotateGesture: { … } }` or\n * `{ onLongPressGesture: … }`.\n */\nexport type GestureValue = Pick<ViewModifiers, 'dragGesture' | 'magnifyGesture' | 'rotateGesture' | 'onLongPressGesture'>;\n\n/** One pointer on a view with `onTouches`: a stable `id` while it is down and its point in the view's coordinates. */\nexport type TouchPoint = ProtocolTouchPoint;\n/** What changed in an `onTouches` call: `began`, `changed`, `ended` or `cancelled`. */\nexport type TouchesPhase = DragPhase;\nexport type TouchesHandler = (touches: TouchPoint[], phase: TouchesPhase) => void;\n\n/** `MagnifyGesture.Value` / `RotateGesture.Value`: the renderer's pinch event. */\nexport interface PinchValue {\n /** The scale since the gesture began (1 at the start). */\n magnification: number;\n /** The turn since the gesture began, in degrees, clockwise positive. */\n rotation: number;\n /** Per second. */\n magnificationVelocity: number;\n rotationVelocity: number;\n startLocation: { x: number; y: number };\n startAnchor: { x: number; y: number };\n /**\n * Where the fingers' midpoint is now (not in SwiftUI's values): with\n * `startLocation`, two fingers pan as they zoom. `startLocation` where the\n * renderer cannot tell.\n */\n location: { x: number; y: number };\n}\n\nexport interface MagnifyGestureModifier {\n minimumScaleDelta?: number;\n onChanged?: (value: PinchValue) => void;\n onEnded?: (value: PinchValue) => void;\n}\n\nexport interface RotateGestureModifier {\n /** Degrees. */\n minimumAngleDelta?: number;\n onChanged?: (value: PinchValue) => void;\n onEnded?: (value: PinchValue) => void;\n}\n\nexport interface SwipeActionsModifier {\n edge?: 'leading' | 'trailing';\n allowsFullSwipe?: boolean;\n /** The actions: `Button`s (a `tint` colors one, a `destructive` role makes it red). */\n children: ReactNode;\n}\n\nexport type ToolbarItemPlacementName =\n | 'automatic'\n | 'topBarLeading'\n | 'topBarTrailing'\n | 'navigationBarLeading'\n | 'navigationBarTrailing'\n | 'cancellationAction'\n | 'confirmationAction'\n | 'destructiveAction'\n | 'primaryAction'\n | 'navigation'\n | 'principal'\n | 'largeTitle'\n | 'bottomBar'\n | 'secondaryAction'\n | 'keyboard';\n\n/** `.toolbar(_:for:)`: `automatic` leaves a bar as it is. */\nexport type Visibility = 'automatic' | 'visible' | 'hidden';\n/** `.toolbarRole(_:)`: `editor` shows a regular-width screen's secondary actions in its bar. */\nexport type ToolbarRole = 'automatic' | 'navigationStack' | 'browser' | 'editor';\n\nexport function toolbarPlacement(name: ToolbarItemPlacementName | undefined): ToolbarPlacement {\n switch (name) {\n case 'topBarLeading':\n case 'navigationBarLeading':\n case 'cancellationAction':\n case 'navigation':\n return 'leading';\n case 'principal':\n return 'principal';\n case 'largeTitle':\n // iOS 26: in the large title row in place of the title's text.\n return 'largeTitle';\n case 'bottomBar':\n return 'bottom';\n case 'keyboard':\n // A bar above the keyboard while a text input of the screen is focused.\n return 'keyboard';\n case 'secondaryAction':\n // Collapsed into the bar's More menu (inline for an editor role in a regular width).\n return 'secondary';\n default:\n return 'trailing';\n }\n}\n\n/**\n * `.foregroundStyle(primary, secondary[, tertiary])`: the first paints, the\n * others are the `.secondary` and `.tertiary` levels below (a palette symbol's\n * other layers).\n */\nexport type ForegroundLayers = readonly [StyleValue, StyleValue] | readonly [StyleValue, StyleValue, StyleValue];\n\nexport interface ViewModifiers {\n padding?: PaddingValue;\n font?: FontValue;\n fontWeight?: FontWeight;\n bold?: boolean;\n /** `.monospacedDigit()`: digits of one width in the text inside. */\n monospacedDigit?: boolean;\n /** A style, or `[primary, secondary(, tertiary)]` (`.foregroundStyle(.white, .indigo)`). */\n foregroundStyle?: StyleValue | ForegroundLayers;\n background?: BackgroundValue;\n overlay?: ReactElement | { content: ReactElement; alignment?: FrameAlignment };\n frame?: FrameValue;\n cornerRadius?: number;\n clipShape?: ReactElement;\n clipped?: boolean;\n /**\n * `.compositingGroup()`: drawn as one layer before the effects around it, so a `shadow` after it (or around it) is\n * cast by the view as a whole, not by each view inside it, as SwiftUI's `.shadow` on a container otherwise is.\n */\n compositingGroup?: boolean;\n opacity?: number;\n disabled?: boolean;\n hidden?: boolean;\n layoutPriority?: number;\n /** A count, `null` to lift a limit, or a range `[min, max]` (`.lineLimit(2...4)`; `max` null for `2...`). */\n lineLimit?: number | null | readonly [number, number | null];\n multilineTextAlignment?: TextAlignment;\n fixedSize?: boolean | FixedSize;\n offset?: { x?: number; y?: number };\n /** Degrees, clockwise; `{ degrees, anchor }` turns around another point. */\n rotationEffect?: number | { degrees: number; anchor?: UnitPointValue };\n scaleEffect?: number | { x: number; y: number; anchor?: UnitPointValue };\n shadow?: { color?: ColorValue; radius: number; x?: number; y?: number };\n tint?: ColorValue;\n badge?: string | number | null;\n listRowInsets?: EdgeInsets;\n /** `.listRowBackground(_:)`: the row's background in a list, in place of the cell color. */\n listRowBackground?: ColorValue;\n imageScale?: ImageScale;\n /** `.symbolRenderingMode(_:)`: the mode the images below (or this image) draw their symbols in. */\n symbolRenderingMode?: SymbolRenderingMode;\n transition?: Transition;\n /** `.animation(_:value:)`: animate this subtree's changes whenever `value` changes. */\n animation?: { animation?: Animation; value: unknown };\n gridColumnAlignment?: 'leading' | 'center' | 'trailing';\n gridCellColumns?: number;\n // Environment\n buttonStyle?: ButtonStyle;\n controlSize?: ControlSize;\n pickerStyle?: PickerStyle;\n /** `.toggleStyle`: how the toggles below draw (`button` is a button tinted while on). */\n toggleStyle?: ToggleStyle;\n labelsHidden?: boolean;\n // Navigation and presentation\n navigationTitle?: string;\n /** `.navigationSubtitle`: a second line under the title in a Mac's unified title bar (after it in a plain one). */\n navigationSubtitle?: string;\n navigationBarTitleDisplayMode?: 'automatic' | 'inline' | 'large';\n /** `.toolbarRole(.editor)`: the screen's secondary actions show inline in a regular width. */\n toolbarRole?: ToolbarRole;\n /**\n * `.toolbarVisibility(_:for:)` (`.toolbar(_:for:)` on iOS 16): hides the\n * screen's navigation bar (with its title, back button and items; the\n * content starts under the status bar) or its bottom bar, or shows one\n * again. Changed in `withAnimation`, the bars fade. The tab bar cannot be\n * hidden yet.\n */\n toolbarVisibility?: Partial<Record<'navigationBar' | 'bottomBar', Visibility>>;\n /** `.statusBarHidden(_:)`: natively the status bar hides with this screen; the page's frame mode hides the one it draws. */\n statusBarHidden?: boolean;\n /** `ToolbarItem` elements. */\n toolbar?: ReactNode;\n searchable?: SearchableModifier;\n navigationDestination?: (value: never) => ReactNode;\n sheet?: SheetModifier;\n fullScreenCover?: SheetModifier;\n alert?: AlertModifier;\n confirmationDialog?: AlertModifier;\n presentationDetents?: DetentValue[];\n // Gestures and lifecycle\n /**\n * `.onScrollVisibilityChange(threshold:_:)`: `action` hears `true` when at\n * least `threshold` (0.5 by default) of the view is inside its scroll\n * view's visible area (below a bar it scrolls under), `false` when it falls\n * below that, and the view's state when it first appears.\n */\n onScrollVisibilityChange?: ((visible: boolean) => void) | { threshold?: number; action: (visible: boolean) => void };\n /**\n * `.onGeometryChange(for:of:action:)`: `{ of, action }` runs `action(value,\n * oldValue)` when `of(proxy)` (the view's size, its frame on screen, its\n * scroll view's bounds) answers differently; a function hears the proxy on\n * every change. The view's layout is untouched.\n */\n onGeometryChange?: GeometryChangeHandler;\n /**\n * `.onTapGesture { }`, or `{ count: 2, action }` for a double tap. A view\n * with both (the double tap first, inside: `onTapGesture={{ count: 2, … }}\n * modifiers={[{ onTapGesture: … }]}`) delays the single tap until a double\n * tap can no longer land, as iOS does. `{ perform(location) }` is\n * `.onTapGesture { location in }`, the point in the view's coordinates.\n */\n onTapGesture?: (() => void) | TapGestureModifier;\n /** `.gesture(DragGesture().onChanged { }.onEnded { })` */\n dragGesture?: DragGestureModifier;\n /** `.gesture(MagnifyGesture().onChanged { }.onEnded { })`: two fingers or a trackpad pinch. */\n magnifyGesture?: MagnifyGestureModifier;\n /** `.gesture(RotateGesture().onChanged { }.onEnded { })` */\n rotateGesture?: RotateGestureModifier;\n /** `.onLongPressGesture { }` */\n onLongPressGesture?: (() => void) | { minimumDuration?: number; action: () => void };\n /**\n * `.onTouches { touches, phase in }`, a SwiftBrowser addition: every pointer\n * down on the view, in its coordinates, for chords and glissandi (a piano,\n * a drum pad). `phase` is `began` (one came down), `changed` (they moved),\n * `ended` (one lifted) or `cancelled` (the renderer lost them all);\n * `touches` is every pointer still down, so the handler reads its state\n * from each call instead of pairing ups with downs. The view owns its\n * pointers: nothing above it scrolls or swipes with them.\n */\n onTouches?: TouchesHandler;\n /**\n * `.simultaneousGesture(_:)`: a gesture that runs beside the view's others\n * and those of the views inside it, instead of competing with them: it\n * begins when its own distance is met and ends when the pointer lifts,\n * whoever else owns the pointer.\n */\n simultaneousGesture?: GestureValue;\n /** `.highPriorityGesture(_:)`: a gesture asked before the gestures of the views inside it. */\n highPriorityGesture?: GestureValue;\n /** `.contextMenu { items }`: a long press or right click opens the items. */\n contextMenu?: ReactNode;\n /** `.swipeActions(edge:allowsFullSwipe:) { buttons }`, on a list row. */\n swipeActions?: SwipeActionsModifier | SwipeActionsModifier[];\n onAppear?: () => void;\n onDisappear?: () => void;\n /** `.tag(_:)`: read by `Picker` options and `TabView` tabs. */\n tag?: unknown;\n /** Extra modifiers in order, for one that must apply twice (`.padding().background().padding()`). */\n modifiers?: ViewModifiers[];\n // Visual effects\n /** `.aspectRatio(_:contentMode:)`: a ratio (width / height), or `{ ratio, contentMode }`; `ratio: null` keeps the view's own. */\n aspectRatio?: number | { ratio?: number | null; contentMode?: 'fit' | 'fill' };\n scaledToFit?: boolean;\n scaledToFill?: boolean;\n blur?: number;\n brightness?: number;\n contrast?: number;\n saturation?: number;\n grayscale?: number;\n /** Degrees. */\n hueRotation?: number;\n colorInvert?: boolean;\n colorMultiply?: ColorValue;\n /** A CSS `mix-blend-mode` name (`multiply`, `screen`, `overlay`…), as `.blendMode` maps them. */\n blendMode?: string;\n /** `.mask(_:)` with a style: the view shows through its alpha (a gradient fades it). */\n mask?: StyleValue;\n /** `.position(x:y:)` */\n position?: { x: number; y: number };\n zIndex?: number;\n /** `.allowsHitTesting(false)` lets taps through to what is under the view. */\n allowsHitTesting?: boolean;\n /**\n * `.contentShape(Rectangle())`: the whole frame takes taps and gestures,\n * what is drawn in it or not (a clear fill, an outline, the gaps in a\n * stack), as SwiftUI hits only what a view draws.\n */\n contentShape?: 'rectangle';\n /** `.ignoresSafeArea()` (`true`), or the edges. */\n ignoresSafeArea?: true | ('top' | 'bottom' | 'leading' | 'trailing')[];\n /** `.rotation3DEffect(_:axis:anchor:perspective:)`, the angle in degrees. */\n rotation3DEffect?: { angle: number; axis: { x: number; y: number; z: number }; anchor?: UnitPointValue; perspective?: number };\n /** `.gridCellAnchor(_:)` */\n gridCellAnchor?: UnitPointValue;\n /**\n * `.alignmentGuide(_:computeValue:)`: moves the view's guide. `value` gets\n * the view's dimensions; it is sampled at three sizes, so it must be linear\n * in them (`d.width + 4`, `d.height / 2`, a constant), as the shim requires.\n */\n alignmentGuide?: { guide: AlignmentGuideName; value: (d: { width: number; height: number }) => number };\n /** `.preferredColorScheme(_:)`: asks the page for that appearance (`null`: the viewer's). */\n preferredColorScheme?: 'light' | 'dark' | null;\n /** `.refreshable { }`: the nearest `List` or `ScrollView` below shows pull to refresh. */\n refreshable?: () => unknown;\n /** `.submitLabel(_:)` for the text fields below: `done`, `go`, `send`, `search`, `next`… */\n submitLabel?: string;\n /** `.keyboardType(_:)` for the text fields below: the on-screen keyboard. */\n keyboardType?: KeyboardType;\n /** `.textContentType(_:)` for the text fields below: what autofill offers. */\n textContentType?: TextContentType | null;\n /** `.textInputAutocapitalization(_:)` for the text fields below. */\n textInputAutocapitalization?: 'never' | 'words' | 'sentences' | 'characters' | null;\n /** `.autocorrectionDisabled()` for the text fields below. */\n autocorrectionDisabled?: boolean;\n /** `.labelStyle(_:)` for the `Label`s below. */\n labelStyle?: 'automatic' | 'titleAndIcon' | 'titleOnly' | 'iconOnly';\n /**\n * `.task { }`: runs when the view appears, cancelled (the signal aborts)\n * when it disappears. `{ id, action }` restarts it when `id` changes.\n */\n task?: ((signal: AbortSignal) => unknown) | { id: unknown; action: (signal: AbortSignal) => unknown };\n /** `.onChange(of:initial:) { old, new in }` */\n onChangeOf?: { value: unknown; action: (oldValue: unknown, newValue: unknown) => void; initial?: boolean };\n /** `.id(_:)` inside a `ScrollViewReader`: the target `proxy.scrollTo` scrolls to. */\n scrollID?: string | number;\n /** `.draggable(_:)`: a long press or a 10 pt drag lifts the view, carrying `payload`. */\n draggable?: unknown;\n /** `.dropDestination(for:)`: takes what is dropped on the view. */\n dropDestination?: DropDestinationModifier;\n /** `.inspector(isPresented:)`: a trailing panel in a regular width, a sheet in a compact one. */\n inspector?: InspectorModifier;\n /** `.onHover { hovering in }`: a mouse entering and leaving the view. */\n onHover?: (hovering: boolean) => void;\n /** `.onContinuousHover { phase in }`: where a mouse is as it moves over the view (`active`, with the location), and that it left (`ended`). */\n onContinuousHover?: ((phase: HoverPhase) => void) | ContinuousHoverModifier;\n /** `.help(_:)`: a tooltip. */\n help?: string;\n /** `.pointerStyle(_:)`: `link`, `text`, `grabIdle`, `grabActive`… or any CSS cursor. */\n pointerStyle?: string;\n /** `.symbolEffect(_:options:isActive:)` / `.symbolEffect(_:options:value:)` */\n symbolEffect?: SymbolEffectModifier;\n /** `.matchedGeometryEffect(id:in:)`: `namespace` from `useNamespace()`. */\n matchedGeometryEffect?: { id: string | number; namespace?: string };\n /** `.layoutValue(key:value:)`: values a custom `Layout` reads from this subview. */\n layoutValue?: Record<string, unknown>;\n /** `.safeAreaInset(edge:spacing:) { content }`: content beside the view, which the view makes room for. */\n safeAreaInset?: { edge: 'top' | 'bottom' | 'leading' | 'trailing'; spacing?: number; alignment?: 'leading' | 'center' | 'trailing' | 'top' | 'bottom'; content: ReactNode };\n /** `.popover(isPresented:)`: presented as a sheet, as on an iPhone. */\n popover?: SheetModifier;\n /** `.fileImporter(isPresented:allowedContentTypes:…)`: the browser's file chooser, opened from a tap. */\n fileImporter?: FileImporterModifier;\n /** `.fileExporter(isPresented:document:contentType:defaultFilename:…)`: a save dialog, a download or the Files app, opened from a tap. */\n fileExporter?: FileExporterModifier;\n /** `.redacted(reason: .placeholder)` (`true`) and `.unredacted()` (`false`). */\n redacted?: boolean;\n /** `.keyboardShortcut(_:modifiers:)` on a `Button`: the shortcut runs its action. */\n keyboardShortcut?: KeyboardShortcut | KeyEquivalent;\n /** `.onKeyPress(keys:action:)` */\n onKeyPress?: OnKeyPressModifier;\n /** `.sensoryFeedback(_:trigger:)` */\n sensoryFeedback?: { feedback: SensoryFeedback; trigger: unknown };\n /** `.textCase(_:)` */\n textCase?: 'uppercase' | 'lowercase' | null;\n /** `.textSelection(_:)`: `enabled` lets the text below be selected (none is otherwise, as on iOS). */\n textSelection?: 'enabled' | 'disabled';\n /** `.coordinateSpace(name:)`: readers inside answer `frame({ named })` relative to this view. */\n coordinateSpace?: string;\n /**\n * `.contentTransition(_:)`: how the texts below change in an animated pass\n * (`numericText` rolls them up, or down when the new number is smaller;\n * `{ numericText: { countsDown } }` fixes the direction; `opacity` and\n * `interpolate` crossfade; `identity` swaps).\n */\n contentTransition?: 'numericText' | 'opacity' | 'interpolate' | 'identity' | { numericText: { countsDown?: boolean } };\n /**\n * `.scrollDisabled(_:)`: the views below do not scroll; a `TextEditor` is\n * as tall as its lines. Natively every scroll view below takes it; the web\n * renderer reads it in text editors.\n */\n scrollDisabled?: boolean;\n /**\n * `.environment(\\.defaultMinListRowHeight, _)`: every list below (this\n * view's own, a sidebar's, an app's drawn through `RemoteTree`) spaces its\n * rows at least this tall, unless the list sets its own `minRowHeight`. A\n * Mac content list's rows are 24 by default; Apple's Mac apps space them\n * like a sidebar's, 32, which one modifier at the top of an app gives every\n * list. A Mac grouped form keeps its form rows (36).\n */\n defaultMinListRowHeight?: number;\n /**\n * `.scrollEdgeEffectStyle(_:for:)` for the scroll views and lists below\n * (and this one): `hard`, `soft` or `automatic` on both edges, or\n * `[\"hard\", \"top\"]` for some.\n */\n scrollEdgeEffectStyle?: ScrollEdgeEffectStyleValue;\n /** `.scrollEdgeEffectHidden(_:for:)`: `true` for both edges, or `[true, \"bottom\"]`. */\n scrollEdgeEffectHidden?: ScrollEdgeEffectHiddenValue;\n /**\n * `.contentMargins(_:_:)`: padding inside the scroll views below (and this\n * one), which their content scrolls under. Takes what `padding` takes.\n */\n contentMargins?: ContentMarginsValue;\n /**\n * `.containerRelativeFrame(_:)`: the view's size along `axes` follows the\n * nearest container (the scroll view's visible area, else the screen):\n * the whole of it, `span` of `count` columns `spacing` apart, or what\n * `length(containerLength, axis)` answers (a linear function of it).\n */\n containerRelativeFrame?: ContainerRelativeFrameValue;\n /**\n * `.visualEffect { content, proxy in … }`: effects (offset, scale,\n * rotation, opacity, blur, color adjustments) computed from the view's\n * geometry, without changing its layout. `proxy.frame('global')` and\n * `proxy.bounds('scrollView')` stay current as the page scrolls.\n */\n visualEffect?: VisualEffectClosure;\n /**\n * `.scrollTransition { content, phase in … }`: effects as the view goes out\n * of its scroll view's visible area and comes back. A closure, or\n * `{ transition, configuration, axis }`.\n */\n scrollTransition?: ScrollTransitionClosure | ScrollTransitionSpec;\n}\n\n/** The axes `containerRelativeFrame` sizes. */\nexport type ContainerAxes = 'horizontal' | 'vertical' | 'both';\n\nexport type ContainerRelativeFrameValue =\n | ContainerAxes\n | {\n axes: ContainerAxes;\n /** `count:span:spacing:`: `span` of `count` equal columns separated by `spacing`. */\n count?: number;\n span?: number;\n spacing?: number;\n /** The closure form: the length for a container length (sampled as a linear function). */\n length?: (containerLength: number, axis: 'horizontal' | 'vertical') => number;\n alignment?: FrameAlignment;\n };\n\n/** The `containerRelativeFrame` style hint for a modifier value. */\nexport function containerRelativeFrame(value: ContainerRelativeFrameValue): NonNullable<Style['containerRelativeFrame']> {\n const spec = typeof value === 'string' ? { axes: value } : value;\n const horizontal = spec.axes !== 'vertical';\n const vertical = spec.axes !== 'horizontal';\n let a = 1;\n let b = 0;\n if (spec.length) {\n const axis = horizontal ? 'horizontal' : 'vertical';\n b = spec.length(0, axis);\n a = (spec.length(1000, axis) - b) / 1000;\n } else if (spec.count !== undefined) {\n // SwiftUI: (container − spacing × (count − 1)) × span / count + spacing × (span − 1).\n const n = Math.max(spec.count, 1);\n const span = Math.max(spec.span ?? 1, 1);\n const spacing = spec.spacing ?? 0;\n a = span / n;\n b = (-spacing * (n - 1) * span) / n + spacing * (span - 1);\n }\n return { ...(horizontal ? { horizontal: true } : {}), ...(vertical ? { vertical: true } : {}), a, b, alignment: spec.alignment ?? 'center' };\n}\n\nexport type AlignmentGuideName =\n | 'leading'\n | 'trailing'\n | 'horizontalCenter'\n | 'top'\n | 'bottom'\n | 'verticalCenter'\n | 'firstTextBaseline'\n | 'lastTextBaseline'\n | 'listRowSeparatorLeading'\n | 'listRowSeparatorTrailing';\n\nexport interface DropDestinationModifier {\n /**\n * Called on a drop: the payloads of an in-app drag (what `draggable` carried),\n * or the items dragged in from outside the page. Return false to refuse.\n */\n action: (items: unknown[], location: { x: number; y: number }) => boolean | void;\n /** While a drag is over the view. */\n isTargeted?: (targeted: boolean) => void;\n /** The MIME patterns taken from outside the page (`text/plain`, `image/*`…); none by default. */\n accepts?: string[];\n}\n\nexport interface InspectorModifier {\n isPresented: BindingValue<boolean>;\n content: ReactNode;\n /** `.inspectorColumnWidth(_:)` */\n columnWidth?: number;\n}\n\nexport type ModifierKey = keyof ViewModifiers;\nexport type ModifierEntry = [ModifierKey, unknown];\n\nconst MODIFIER_KEYS: ReadonlySet<string> = new Set<ModifierKey>([\n 'padding',\n 'font',\n 'fontWeight',\n 'bold',\n 'monospacedDigit',\n 'foregroundStyle',\n 'background',\n 'overlay',\n 'frame',\n 'cornerRadius',\n 'clipShape',\n 'clipped',\n 'compositingGroup',\n 'opacity',\n 'disabled',\n 'hidden',\n 'layoutPriority',\n 'lineLimit',\n 'multilineTextAlignment',\n 'fixedSize',\n 'offset',\n 'rotationEffect',\n 'scaleEffect',\n 'shadow',\n 'tint',\n 'badge',\n 'listRowInsets',\n 'listRowBackground',\n 'imageScale',\n 'symbolRenderingMode',\n 'transition',\n 'animation',\n 'gridColumnAlignment',\n 'gridCellColumns',\n 'buttonStyle',\n 'controlSize',\n 'pickerStyle',\n 'toggleStyle',\n 'labelsHidden',\n 'navigationTitle',\n 'navigationSubtitle',\n 'navigationBarTitleDisplayMode',\n 'toolbarRole',\n 'toolbarVisibility',\n 'statusBarHidden',\n 'toolbar',\n 'searchable',\n 'navigationDestination',\n 'sheet',\n 'fullScreenCover',\n 'alert',\n 'confirmationDialog',\n 'presentationDetents',\n 'onScrollVisibilityChange',\n 'onGeometryChange',\n 'onTapGesture',\n 'dragGesture',\n 'magnifyGesture',\n 'rotateGesture',\n 'onLongPressGesture',\n 'onTouches',\n 'simultaneousGesture',\n 'highPriorityGesture',\n 'contextMenu',\n 'swipeActions',\n 'onAppear',\n 'onDisappear',\n 'tag',\n 'modifiers',\n 'aspectRatio',\n 'scaledToFit',\n 'scaledToFill',\n 'blur',\n 'brightness',\n 'contrast',\n 'saturation',\n 'grayscale',\n 'hueRotation',\n 'colorInvert',\n 'colorMultiply',\n 'blendMode',\n 'mask',\n 'position',\n 'zIndex',\n 'allowsHitTesting',\n 'contentShape',\n 'ignoresSafeArea',\n 'rotation3DEffect',\n 'gridCellAnchor',\n 'alignmentGuide',\n 'preferredColorScheme',\n 'refreshable',\n 'submitLabel',\n 'keyboardType',\n 'textContentType',\n 'textInputAutocapitalization',\n 'autocorrectionDisabled',\n 'labelStyle',\n 'task',\n 'onChangeOf',\n 'scrollID',\n 'draggable',\n 'dropDestination',\n 'inspector',\n 'onHover',\n 'onContinuousHover',\n 'help',\n 'pointerStyle',\n 'symbolEffect',\n 'matchedGeometryEffect',\n 'layoutValue',\n 'safeAreaInset',\n 'popover',\n 'fileImporter',\n 'fileExporter',\n 'redacted',\n 'keyboardShortcut',\n 'onKeyPress',\n 'sensoryFeedback',\n 'textCase',\n 'textSelection',\n 'coordinateSpace',\n 'contentTransition',\n 'scrollDisabled',\n 'defaultMinListRowHeight',\n 'scrollEdgeEffectStyle',\n 'scrollEdgeEffectHidden',\n 'contentMargins',\n 'containerRelativeFrame',\n 'visualEffect',\n 'scrollTransition',\n]);\n\n/**\n * Separate a component's own props from the modifiers, keeping the modifiers\n * in the order they were written (object keys keep insertion order).\n */\nexport function splitProps<P extends object>(props: P): { own: Omit<P, ModifierKey>; modifiers: ModifierEntry[] } {\n const own: Record<string, unknown> = {};\n const modifiers: ModifierEntry[] = [];\n for (const [key, value] of Object.entries(props)) {\n if (MODIFIER_KEYS.has(key)) modifiers.push([key as ModifierKey, value]);\n else own[key] = value;\n }\n return { own: own as Omit<P, ModifierKey>, modifiers };\n}\n\n/** Remove and return one modifier a component handles itself. */\nexport function takeModifier<K extends ModifierKey>(modifiers: ModifierEntry[], key: K): ViewModifiers[K] | undefined {\n const at = modifiers.findIndex(([name]) => name === key);\n if (at < 0) return undefined;\n const [, value] = modifiers[at]!;\n modifiers.splice(at, 1);\n return value as ViewModifiers[K];\n}\n\nexport function styled(style: Style, child: ReactNode): ReactElement {\n return sb('styled', { style }, undefined, child);\n}\n\n/** The `gesture` element of a drag, pinch or long-press modifier, in a composition `mode` (`.gesture` when absent). */\nfunction gesture(key: keyof GestureValue, value: unknown, node: ReactNode, mode?: GestureMode): ReactNode {\n const base: Record<string, unknown> = { drag: false, longPress: false, minimumDistance: 10, minimumDuration: 0.5 };\n if (mode) base['mode'] = mode;\n switch (key) {\n case 'dragGesture':\n return createElement(DragGestureElement, { spec: value as DragGestureModifier, mode }, node);\n case 'magnifyGesture':\n case 'rotateGesture': {\n const pinch = value as MagnifyGestureModifier & RotateGestureModifier;\n if (key === 'magnifyGesture') {\n base['magnify'] = true;\n base['minimumScaleDelta'] = pinch.minimumScaleDelta ?? 0.01;\n } else {\n base['rotate'] = true;\n base['minimumAngleDelta'] = pinch.minimumAngleDelta ?? 1;\n }\n return sb('gesture', base, {\n pinch: (event) => {\n const pinchValue: PinchValue = {\n magnification: event.scale,\n rotation: event.rotation,\n magnificationVelocity: event.scaleVelocity,\n rotationVelocity: event.rotationVelocity,\n startLocation: event.startLocation,\n startAnchor: event.startAnchor,\n location: event.location ?? event.startLocation,\n };\n if (event.phase === 'ended' || event.phase === 'cancelled') pinch.onEnded?.(pinchValue);\n else pinch.onChanged?.(pinchValue);\n },\n }, node);\n }\n case 'onLongPressGesture': {\n const spec = typeof value === 'function' ? { action: value as () => void } : (value as { minimumDuration?: number; action: () => void });\n base['longPress'] = true;\n base['minimumDuration'] = spec.minimumDuration ?? 0.5;\n return sb('gesture', base, { longpress: () => spec.action() }, node);\n }\n }\n}\n\n/**\n * `.gesture(DragGesture(coordinateSpace:))`: `local` and `global` are the\n * renderer's; a named space is the global point less the frame\n * `coordinateSpace` reported for that name (as `GeometryReader`'s\n * `frame({ named })`), global when no ancestor names it.\n */\nfunction DragGestureElement({ spec, mode, children }: { spec: DragGestureModifier; mode?: GestureMode | undefined; children?: ReactNode }): ReactNode {\n const spaces = useCoordinateSpaces();\n const space = spec.coordinateSpace ?? 'local';\n const named = typeof space === 'object' ? spaces[space.named] : null;\n const props: Record<string, unknown> = { drag: true, longPress: false, minimumDistance: spec.minimumDistance ?? 10, minimumDuration: 0.5 };\n if (space !== 'local') props['coordinateSpace'] = 'global';\n if (mode) props['mode'] = mode;\n const inSpace = (point: { x: number; y: number }): { x: number; y: number } => (named ? { x: point.x - named.x, y: point.y - named.y } : point);\n return sb(\n 'gesture',\n props,\n {\n drag: (event) => {\n const dragValue: DragValue = {\n translation: event.translation,\n location: inSpace(event.location),\n startLocation: inSpace(event.startLocation),\n velocity: event.velocity,\n };\n if (event.phase === 'ended' || event.phase === 'cancelled') spec.onEnded?.(dragValue);\n else spec.onChanged?.(dragValue);\n },\n },\n children,\n );\n}\n\nfunction decorated(role: 'background' | 'overlay', alignment: FrameAlignment, content: ReactNode, decoration: ReactNode): ReactElement {\n return sb('decorated', { role, alignment }, undefined, [\n createElement(Fragment, { key: 'content' }, content),\n createElement(Fragment, { key: 'decoration' }, decoration),\n ]);\n}\n\nexport function shapeSpecOf(element: ReactElement): ShapeSpec | null {\n const spec = (element.type as { shape?: ShapeSpec }).shape;\n if (!spec) return null;\n const radius = (element.props as { cornerRadius?: number }).cornerRadius;\n return { kind: spec.kind, cornerRadius: spec.cornerRadius ?? radius ?? 0 };\n}\n\n/** `.animation(_:value:)`: a token that changes with the value. */\nfunction AnimatedStyle({ animation, value, children }: { animation: Animation; value: unknown; children?: ReactNode }): ReactElement {\n const last = useRef<{ value: unknown; token: number }>({ value, token: 0 });\n if (!Object.is(last.current.value, value)) last.current = { value, token: last.current.token + 1 };\n return styled({ animation, animationToken: last.current.token }, children);\n}\n\nfunction Searchable({ text, onChange, prompt }: SearchableModifier): ReactElement {\n const [value, setValue] = readBinding(text, onChange);\n return sb('searchfield', { text: value, placeholder: prompt ?? 'Search' }, { text: (event) => setValue(event.value) });\n}\n\n/**\n * Apply `modifiers` to `element`, in order. Styled wrappers nest around the\n * element; hoisted elements and lifecycle components come after it, in a\n * fragment. Preferences (`navigationTitle` and the bar's other settings, a\n * color scheme) come before it: the tree merges them in order, so one set\n * inside the view, met later, wins over the view's own, as in SwiftUI, where\n * the innermost `navigationTitle` is the screen's.\n */\nexport function applyModifiers(element: ReactNode, modifiers: readonly ModifierEntry[]): ReactNode {\n const sides: ReactNode[] = [];\n const node = wrap(element, modifiers, sides);\n const prefs = sides.filter(isPreference);\n const rest = sides.filter((side) => !isPreference(side));\n // always this shape (the preferences' fragment first, even empty), so a side modifier coming or going leaves the view in place\n return createElement(Fragment, null, createElement(Fragment, null, ...prefs), node, ...rest);\n}\n\nconst isPreference = (side: ReactNode): boolean => isValidElement<{ kind?: unknown }>(side) && side.props.kind === PREF_KIND;\n\nfunction wrap(element: ReactNode, modifiers: readonly ModifierEntry[], sides: ReactNode[]): ReactNode {\n let node = element;\n // A view that can hold others records its inherited styles for the presentations among them.\n const holds = holdsViews(element);\n /** This view's presentations, each with the inherited styles written after it (around it, in SwiftUI), innermost first. */\n const presentations: { at: number; after: Style[] }[] = [];\n for (const [key, value] of modifiers) {\n const inactive = value === undefined || (value === null && key !== 'lineLimit' && key !== 'badge');\n const before = sides.length;\n const next = inactive ? node : apply(key, value, node, sides);\n node = next === node ? neutral(key, node) : next;\n if (INHERITED_STYLE_KEYS.has(key)) {\n const style = styleOf(node);\n if (Object.keys(style).length > 0) for (const presentation of presentations) presentation.after.push(style);\n if (holds) node = createElement(InheritStyle, { style }, node);\n }\n if (PRESENTATION_KEYS.has(key) && sides.length > before) presentations.push({ at: before, after: [] });\n }\n for (const { at, after } of presentations) {\n const side = sides[at];\n if (after.length > 0 && isValidElement(side)) sides[at] = cloneElement(side, { inherited: after.reverse() } as object);\n }\n return node;\n}\n\n/**\n * Whether `element` can hold other views (and so a presentation below it):\n * anything but a host element written without children (a text, an\n * image, a shape). Decided by how the element is written, not by what it\n * holds now, so its wrappers stay the same as its content comes and goes.\n */\nfunction holdsViews(element: ReactNode): boolean {\n if (!isValidElement<{ children?: unknown }>(element)) return false;\n return element.type !== 'sb' || element.props.children !== undefined;\n}\n\n/** The modifiers whose wrapper is a `styled` node (a view `background` too). */\nconst STYLED_KEYS: ReadonlySet<ModifierKey> = new Set<ModifierKey>([\n 'padding', 'font', 'fontWeight', 'bold', 'monospacedDigit', 'foregroundStyle', 'background', 'frame', 'cornerRadius', 'clipShape', 'clipped', 'compositingGroup',\n 'opacity', 'disabled', 'hidden', 'layoutPriority', 'lineLimit', 'multilineTextAlignment', 'fixedSize', 'offset',\n 'rotationEffect', 'scaleEffect', 'shadow', 'tint', 'badge', 'listRowInsets', 'listRowBackground', 'imageScale', 'transition',\n 'gridColumnAlignment', 'gridCellColumns', 'aspectRatio', 'scaledToFit', 'scaledToFill', 'blur', 'brightness', 'contrast',\n 'saturation', 'grayscale', 'hueRotation', 'colorInvert', 'colorMultiply', 'blendMode', 'mask', 'position', 'zIndex',\n 'allowsHitTesting', 'contentShape', 'ignoresSafeArea', 'rotation3DEffect', 'gridCellAnchor', 'alignmentGuide', 'help', 'pointerStyle',\n 'matchedGeometryEffect', 'containerRelativeFrame', 'contentTransition', 'scrollDisabled', 'textSelection', 'defaultMinListRowHeight',\n]);\n\n/** The modifiers whose wrapper extends the view environment. */\nconst ENVIRONMENT_KEYS: ReadonlySet<ModifierKey> = new Set<ModifierKey>([\n 'buttonStyle', 'controlSize', 'pickerStyle', 'toggleStyle', 'labelsHidden', 'refreshable', 'submitLabel', 'labelStyle', 'redacted', 'textCase',\n 'symbolRenderingMode', 'keyboardType', 'textContentType', 'textInputAutocapitalization', 'autocorrectionDisabled',\n]);\n\n/** The modifiers whose wrapper extends the scroll settings. */\nconst SCROLL_KEYS: ReadonlySet<ModifierKey> = new Set<ModifierKey>(['scrollEdgeEffectStyle', 'scrollEdgeEffectHidden', 'contentMargins']);\n\n/**\n * A modifier that is written but does nothing (`undefined`, `false`) still\n * wraps the view, in the same kind of wrapper it has when it is on, with\n * nothing in it. Otherwise turning it on or off would change the element\n * types above the view and React would remount everything under it, as\n * SwiftUI never does for `.overlay { if open { … } }` or `.disabled(flag)`.\n */\nfunction neutral(key: ModifierKey, node: ReactNode): ReactNode {\n if (key === 'overlay') return decorated('overlay', 'center', node, null);\n if (STYLED_KEYS.has(key)) return styled({}, node);\n if (ENVIRONMENT_KEYS.has(key)) return withEnvironment({}, node);\n if (SCROLL_KEYS.has(key)) return withScrollSettings({}, node);\n return node;\n}\n\nfunction apply(key: ModifierKey, value: unknown, node: ReactNode, sides: ReactNode[]): ReactNode {\n switch (key) {\n case 'padding':\n return styled({ padding: padding(value as PaddingValue) }, node);\n case 'font':\n return styled({ font: font(value as FontValue) }, node);\n case 'fontWeight':\n return styled({ font: { weight: value as FontWeight } }, node);\n case 'bold':\n return value ? styled({ font: { weight: 'bold' } }, node) : node;\n case 'monospacedDigit':\n return value ? styled({ font: { monospacedDigit: true } }, node) : node;\n case 'foregroundStyle': {\n if (!Array.isArray(value)) return styled({ foreground: shapeStyle(value as StyleValue) }, node);\n const [primary, ...levels] = value as unknown as ForegroundLayers;\n return styled({ foreground: shapeStyle(primary), foregroundLevels: levels.map((level) => shapeStyle(level)) }, node);\n }\n case 'background': {\n if (isValidElement(value)) return decorated('background', 'center', node, value);\n const inShape = value as BackgroundInShape;\n if (typeof inShape === 'object' && inShape !== null && 'in' in inShape && isValidElement(inShape.in)) {\n return decorated('background', 'center', node, cloneElement(inShape.in, { fill: inShape.fill } as object));\n }\n return styled({ background: shapeStyle(value as StyleValue) }, node);\n }\n case 'overlay': {\n if (isValidElement(value)) return decorated('overlay', 'center', node, value);\n const spec = value as { content: ReactElement; alignment?: FrameAlignment };\n return decorated('overlay', spec.alignment ?? 'center', node, spec.content);\n }\n case 'frame':\n return styled({ frame: frame(value as FrameValue) }, node);\n case 'cornerRadius':\n return styled({ cornerRadius: value as number }, node);\n case 'clipShape': {\n const spec = isValidElement(value) ? shapeSpecOf(value) : null;\n return styled({ cornerRadius: spec?.cornerRadius ?? 0 }, node);\n }\n case 'clipped':\n return value ? styled({ clipped: true }, node) : node;\n case 'compositingGroup':\n return value ? styled({ compositingGroup: true }, node) : node;\n case 'opacity':\n return styled({ opacity: value as number }, node);\n case 'disabled':\n return value ? styled({ disabled: true }, node) : node;\n case 'hidden':\n return value ? styled({ hidden: true }, node) : node;\n case 'layoutPriority':\n return styled({ layoutPriority: value as number }, node);\n case 'lineLimit': {\n if (Array.isArray(value)) {\n const [min, max] = value as [number, number | null];\n return styled({ lineLimit: max, lineLimitMin: min }, node);\n }\n return styled({ lineLimit: value as number | null }, node);\n }\n case 'multilineTextAlignment':\n return styled({ multilineTextAlignment: value as TextAlignment }, node);\n case 'fixedSize':\n return value ? styled({ fixedSize: value === true ? { horizontal: true, vertical: true } : (value as FixedSize) }, node) : node;\n case 'offset': {\n const offset = value as { x?: number; y?: number };\n return styled({ offset: { x: offset.x ?? 0, y: offset.y ?? 0 } }, node);\n }\n case 'rotationEffect': {\n if (typeof value === 'number') return styled({ rotation: value }, node);\n const spec = value as { degrees: number; anchor?: UnitPointValue };\n const style: Style = { rotation: spec.degrees };\n if (spec.anchor !== undefined) style.rotationAnchor = unitPoint(spec.anchor);\n return styled(style, node);\n }\n case 'scaleEffect': {\n if (typeof value === 'number') return styled({ scale: { x: value, y: value } }, node);\n const spec = value as { x: number; y: number; anchor?: UnitPointValue };\n const style: Style = { scale: { x: spec.x, y: spec.y } };\n if (spec.anchor !== undefined) style.scaleAnchor = unitPoint(spec.anchor);\n return styled(style, node);\n }\n case 'shadow': {\n const shadow = value as { color?: ColorValue; radius: number; x?: number; y?: number };\n return styled(\n { shadow: { color: shadow.color ? color(shadow.color) : rgb(0, 0, 0, 0.33), radius: shadow.radius, x: shadow.x ?? 0, y: shadow.y ?? 0 } },\n node,\n );\n }\n case 'tint':\n return styled({ tint: color(value as ColorValue) }, node);\n case 'badge':\n return styled({ badge: value === null ? null : String(value) }, node);\n case 'listRowInsets':\n return styled({ listRowInsets: value as EdgeInsets }, node);\n case 'listRowBackground':\n return styled({ listRowBackground: color(value as ColorValue) }, node);\n case 'imageScale':\n return styled({ imageScale: value as ImageScale }, node);\n case 'transition':\n return styled({ transition: value as Transition }, node);\n case 'animation': {\n const spec = value as { animation?: Animation; value: unknown };\n return createElement(AnimatedStyle, { animation: spec.animation ?? { type: 'default' }, value: spec.value }, node);\n }\n case 'gridColumnAlignment':\n return styled({ gridColumnAlignment: value } as Style, node);\n case 'gridCellColumns':\n return styled({ gridCellColumns: value as number }, node);\n case 'buttonStyle':\n return withEnvironment({ buttonStyle: value as ButtonStyle }, node);\n case 'controlSize':\n return withEnvironment({ controlSize: value as ControlSize }, node);\n case 'symbolRenderingMode':\n return withEnvironment({ symbolRenderingMode: value as SymbolRenderingMode }, node);\n case 'pickerStyle':\n return withEnvironment({ pickerStyle: value as PickerStyle }, node);\n case 'toggleStyle':\n return withEnvironment({ toggleStyle: value as ToggleStyle }, node);\n case 'labelsHidden':\n return withEnvironment({ labelsHidden: Boolean(value) }, node);\n case 'navigationTitle':\n sides.push(sb(PREF_KIND, { title: value as string }, undefined, undefined, 'navscreen'));\n return node;\n case 'navigationSubtitle':\n sides.push(sb(PREF_KIND, { subtitle: value as string }, undefined, undefined, 'navscreen'));\n return node;\n case 'navigationBarTitleDisplayMode':\n sides.push(sb(PREF_KIND, { displayMode: value as string }, undefined, undefined, 'navscreen'));\n return node;\n case 'toolbarRole':\n sides.push(sb(PREF_KIND, { toolbarRole: value as string }, undefined, undefined, 'navscreen'));\n return node;\n case 'toolbarVisibility': {\n const bars = value as NonNullable<ViewModifiers['toolbarVisibility']>;\n const props: Record<string, boolean> = {};\n if (bars.navigationBar && bars.navigationBar !== 'automatic') props['navigationBarHidden'] = bars.navigationBar === 'hidden';\n if (bars.bottomBar && bars.bottomBar !== 'automatic') props['bottomBarHidden'] = bars.bottomBar === 'hidden';\n sides.push(sb(PREF_KIND, props, undefined, undefined, 'navscreen'));\n return node;\n }\n case 'statusBarHidden':\n sides.push(sb(PREF_KIND, { statusBarHidden: Boolean(value) }, undefined, undefined, 'navscreen'));\n return node;\n case 'toolbar':\n sides.push(sb(HOIST_KIND, undefined, undefined, value as ReactNode, 'navscreen'));\n return node;\n case 'searchable':\n sides.push(sb(HOIST_KIND, undefined, undefined, createElement(Searchable, value as SearchableModifier), 'navscreen'));\n return node;\n case 'navigationDestination':\n sides.push(createElement(RegisterDestination, { destination: value as (value: never) => ReactNode }));\n return node;\n case 'sheet':\n sides.push(createElement(SheetPresenter, value as SheetModifier));\n return node;\n case 'fullScreenCover':\n sides.push(createElement(SheetPresenter, { ...(value as SheetModifier), fullScreen: true }));\n return node;\n case 'alert':\n sides.push(createElement(AlertPresenter, value as AlertModifier));\n return node;\n case 'confirmationDialog':\n sides.push(createElement(AlertPresenter, { ...(value as AlertModifier), style: 'dialog' }));\n return node;\n case 'presentationDetents':\n sides.push(presentationDetents(value as DetentValue[]));\n return node;\n case 'onScrollVisibilityChange': {\n const spec = typeof value === 'function' ? { action: value as (visible: boolean) => void } : (value as { threshold?: number; action: (visible: boolean) => void });\n return sb('styled', { style: { scrollVisibility: { threshold: spec.threshold ?? 0.5 } } }, { scrollvisibility: (event) => spec.action(event.visible) }, node);\n }\n case 'onTapGesture': {\n const spec = typeof value === 'function' ? { action: value as () => void } : (value as TapGestureModifier);\n const count = Math.floor(spec.count ?? 1);\n const props: Record<string, unknown> = count > 1 ? { count } : {};\n if ('perform' in spec) {\n const { perform } = spec;\n return sb('tapgesture', { ...props, location: true }, { tap: (event) => perform({ x: event.x ?? 0, y: event.y ?? 0 }) }, node);\n }\n return sb('tapgesture', props, { tap: () => spec.action() }, node);\n }\n case 'onGeometryChange':\n return createElement(GeometryChangeView, { handler: value as GeometryChangeHandler }, node);\n case 'dragGesture':\n case 'magnifyGesture':\n case 'rotateGesture':\n case 'onLongPressGesture':\n return gesture(key, value, node);\n case 'onTouches': {\n const handler = value as TouchesHandler;\n return sb('touches', {}, { touches: (event) => handler(event.touches, event.phase) }, node);\n }\n case 'simultaneousGesture':\n case 'highPriorityGesture': {\n const mode: GestureMode = key === 'simultaneousGesture' ? 'simultaneous' : 'highPriority';\n let result = node;\n for (const [gestureKey, gestureValue] of Object.entries(value as GestureValue) as [keyof GestureValue, unknown][]) {\n if (gestureValue !== undefined) result = gesture(gestureKey, gestureValue, result, mode);\n }\n return result;\n }\n case 'contextMenu':\n return sb('contextmenu', {}, undefined, [createElement(Fragment, { key: 'content' }, node), createElement(Fragment, { key: 'items' }, value as ReactNode)]);\n case 'swipeActions': {\n const specs = Array.isArray(value) ? (value as SwipeActionsModifier[]) : [value as SwipeActionsModifier];\n const trailing: ReactNode[] = [];\n const leading: ReactNode[] = [];\n let fullSwipeTrailing = true;\n let fullSwipeLeading = true;\n for (const spec of specs) {\n const actions = Children.toArray(spec.children);\n if (spec.edge === 'leading') {\n leading.push(...actions);\n fullSwipeLeading = spec.allowsFullSwipe ?? true;\n } else {\n trailing.push(...actions);\n fullSwipeTrailing = spec.allowsFullSwipe ?? true;\n }\n }\n return sb(\n 'swipeactions',\n { trailing: trailing.length, leading: leading.length, fullSwipeTrailing, fullSwipeLeading },\n undefined,\n [createElement(Fragment, { key: 'content' }, node), ...trailing, ...leading],\n );\n }\n case 'onAppear':\n sides.push(createElement(Lifecycle, { onAppear: value as () => void }));\n return node;\n case 'onDisappear':\n sides.push(createElement(Lifecycle, { onDisappear: value as () => void }));\n return node;\n case 'tag':\n return node;\n case 'aspectRatio': {\n const spec = typeof value === 'number' ? { ratio: value } : (value as { ratio?: number | null; contentMode?: 'fit' | 'fill' });\n return styled({ aspectRatio: { ratio: spec.ratio ?? null, contentMode: spec.contentMode ?? 'fit' } }, node);\n }\n case 'scaledToFit':\n return value ? styled({ aspectRatio: { ratio: null, contentMode: 'fit' } }, node) : node;\n case 'scaledToFill':\n return value ? styled({ aspectRatio: { ratio: null, contentMode: 'fill' } }, node) : node;\n case 'blur':\n return styled({ blur: value as number }, node);\n case 'brightness':\n return styled({ brightness: value as number }, node);\n case 'contrast':\n return styled({ contrast: value as number }, node);\n case 'saturation':\n return styled({ saturation: value as number }, node);\n case 'grayscale':\n return styled({ grayscale: value as number }, node);\n case 'hueRotation':\n return styled({ hueRotation: value as number }, node);\n case 'colorInvert':\n return value ? styled({ colorInvert: true }, node) : node;\n case 'colorMultiply':\n return styled({ colorMultiply: color(value as ColorValue) }, node);\n case 'blendMode':\n return styled({ blendMode: value as string }, node);\n case 'mask':\n return styled({ mask: shapeStyle(value as StyleValue) }, node);\n case 'position':\n return styled({ position: value as { x: number; y: number } }, node);\n case 'zIndex':\n return styled({ zIndex: value as number }, node);\n case 'allowsHitTesting':\n return value === false ? styled({ hitTesting: false }, node) : node;\n case 'contentShape':\n return value === 'rectangle' ? styled({ contentShape: 'rectangle' }, node) : node;\n case 'ignoresSafeArea':\n // `true` is `.ignoresSafeArea()`: every edge and the keyboard region too.\n return styled(\n value === true ? { ignoresSafeArea: 'all', ignoresKeyboard: true } : { ignoresSafeArea: value as ('top' | 'bottom' | 'leading' | 'trailing')[] },\n node,\n );\n case 'rotation3DEffect': {\n const spec = value as { angle: number; axis: { x: number; y: number; z: number }; anchor?: UnitPointValue; perspective?: number };\n const rotation: Style['rotation3D'] = { angle: spec.angle, axis: spec.axis };\n if (spec.anchor !== undefined) rotation!.anchor = unitPoint(spec.anchor);\n if (spec.perspective !== undefined) rotation!.perspective = spec.perspective;\n return styled({ rotation3D: rotation }, node);\n }\n case 'gridCellAnchor':\n return styled({ gridCellAnchor: unitPoint(value as UnitPointValue) }, node);\n case 'alignmentGuide': {\n const spec = value as { guide: AlignmentGuideName; value: (d: { width: number; height: number }) => number };\n const at = (width: number, height: number): number => spec.value({ width, height });\n const a = at(0, 0);\n const round = (n: number): number => Math.round(n * 1e6) / 1e6;\n const vertical = ['top', 'bottom', 'verticalCenter', 'firstTextBaseline', 'lastTextBaseline'].includes(spec.guide);\n const name = spec.guide === 'horizontalCenter' || spec.guide === 'verticalCenter' ? 'center' : spec.guide;\n return styled(\n {\n alignmentGuide: {\n axis: vertical ? 'vertical' : 'horizontal',\n name,\n value: [round(a), round((at(100, 0) - a) / 100), round((at(0, 100) - a) / 100)],\n },\n },\n node,\n );\n }\n case 'preferredColorScheme':\n sides.push(sb(PREF_KIND, { colorScheme: value as 'light' | 'dark' | null }, undefined, undefined, 'root'));\n return node;\n case 'refreshable':\n return withEnvironment({ refresh: value as () => unknown }, node);\n case 'submitLabel':\n return withEnvironment({ submitLabel: value as string }, node);\n case 'keyboardType':\n return withTextInputHint({ keyboard: value as KeyboardType }, node);\n case 'textContentType':\n return withTextInputHint({ contentType: (value as TextContentType | null) ?? undefined }, node);\n case 'textInputAutocapitalization':\n return withTextInputHint({ autocapitalization: (value as TextInputHints['autocapitalization'] | null) ?? undefined }, node);\n case 'autocorrectionDisabled':\n return withTextInputHint({ autocorrectionDisabled: value === true }, node);\n case 'labelStyle':\n return withEnvironment({ labelStyle: value as ViewEnvironment['labelStyle'] }, node);\n case 'task': {\n const spec = typeof value === 'function' ? { id: undefined, action: value as (signal: AbortSignal) => unknown } : (value as { id: unknown; action: (signal: AbortSignal) => unknown });\n sides.push(createElement(Task, spec));\n return node;\n }\n case 'onChangeOf':\n sides.push(createElement(OnChange, value as { value: unknown; action: (oldValue: unknown, newValue: unknown) => void; initial?: boolean }));\n return node;\n case 'scrollID':\n return createElement(ScrollTarget, { id: value as string | number }, node);\n case 'draggable':\n return createElement(Draggable, { payload: value }, node);\n case 'dropDestination':\n return createElement(DropDestination, value as DropDestinationModifier, node);\n case 'inspector':\n return createElement(Inspector, value as InspectorModifier, node);\n case 'onHover':\n return createElement(Hover, { action: value as (hovering: boolean) => void }, node);\n case 'onContinuousHover':\n return createElement(ContinuousHover, { spec: typeof value === 'function' ? { action: value as (phase: HoverPhase) => void } : (value as ContinuousHoverModifier) }, node);\n case 'help':\n return styled({ help: value as string }, node);\n case 'pointerStyle':\n return styled({ pointerStyle: cursorFor(value as string) }, node);\n case 'symbolEffect':\n return createElement(SymbolEffect, { spec: value as SymbolEffectModifier }, node);\n case 'matchedGeometryEffect': {\n const spec = value as { id: string | number; namespace?: string };\n return styled({ matchedGeometry: `${spec.namespace ?? ''}:${spec.id}` }, node);\n }\n case 'layoutValue':\n // Read by the enclosing `Layout` from the subview's props; nothing to draw.\n return node;\n case 'safeAreaInset': {\n const spec = value as { edge: 'top' | 'bottom' | 'leading' | 'trailing'; spacing?: number; alignment?: string; content: ReactNode };\n const vertical = spec.edge === 'top' || spec.edge === 'bottom';\n const before = spec.edge === 'top' || spec.edge === 'leading';\n const children = before\n ? [createElement(Fragment, { key: 'inset' }, spec.content), createElement(Fragment, { key: 'content' }, node)]\n : [createElement(Fragment, { key: 'content' }, node), createElement(Fragment, { key: 'inset' }, spec.content)];\n return vertical\n ? sb('vstack', { spacing: spec.spacing ?? 0, alignment: spec.alignment ?? 'center' }, undefined, children)\n : sb('hstack', { spacing: spec.spacing ?? 0, alignment: spec.alignment ?? 'center' }, undefined, children);\n }\n case 'popover':\n sides.push(createElement(SheetPresenter, value as SheetModifier));\n return node;\n case 'fileImporter':\n sides.push(createElement(FileImporterPresenter, value as FileImporterModifier));\n return node;\n case 'fileExporter':\n sides.push(createElement(FileExporterPresenter, value as FileExporterModifier));\n return node;\n case 'redacted':\n return withEnvironment({ redacted: Boolean(value) }, node);\n case 'keyboardShortcut':\n // A `Button` takes its own shortcut; elsewhere it has no action to run.\n return node;\n case 'onKeyPress':\n sides.push(createElement(KeyPressListener, { spec: value as OnKeyPressModifier }));\n return node;\n case 'sensoryFeedback': {\n const spec = value as { feedback: SensoryFeedback; trigger: unknown };\n sides.push(createElement(SensoryFeedbackPlayer, spec));\n return node;\n }\n case 'textCase':\n return withEnvironment({ textCase: value as 'uppercase' | 'lowercase' | null }, node);\n case 'coordinateSpace':\n return createElement(CoordinateSpace, { name: value as string }, node);\n case 'scrollEdgeEffectStyle':\n return withScrollSettings(edgeStyleSettings(value as ScrollEdgeEffectStyleValue), node);\n case 'scrollEdgeEffectHidden':\n return withScrollSettings(edgeHiddenSettings(value as ScrollEdgeEffectHiddenValue), node);\n case 'contentMargins':\n return withScrollSettings(marginSettings(value as ContentMarginsValue), node);\n case 'containerRelativeFrame':\n return styled({ containerRelativeFrame: containerRelativeFrame(value as ContainerRelativeFrameValue) }, node);\n case 'visualEffect':\n return createElement(VisualEffectView, { effect: value as VisualEffectClosure }, node);\n case 'scrollTransition': {\n const spec = typeof value === 'function' ? { transition: value as ScrollTransitionClosure } : (value as ScrollTransitionSpec);\n return createElement(ScrollTransitionView, { spec }, node);\n }\n case 'scrollDisabled':\n return styled({ scrollDisabled: value === true }, node);\n case 'defaultMinListRowHeight':\n return typeof value === 'number' && Number.isFinite(value) ? styled({ defaultMinListRowHeight: Math.max(0, value) }, node) : styled({}, node);\n case 'textSelection':\n return styled({ textSelection: value === 'enabled' }, node);\n case 'contentTransition': {\n if (value === 'identity') return node;\n if (typeof value === 'object') {\n const countsDown = (value as { numericText: { countsDown?: boolean } }).numericText.countsDown;\n return styled({ contentTransition: { kind: 'numericText', ...(countsDown !== undefined ? { countsDown } : {}) } }, node);\n }\n return styled({ contentTransition: { kind: value as 'numericText' | 'opacity' | 'interpolate' } }, node);\n }\n case 'modifiers': {\n let result = node;\n for (const extra of value as ViewModifiers[]) {\n result = wrap(result, Object.entries(extra) as ModifierEntry[], sides);\n }\n return result;\n }\n default: {\n const unknown: never = key;\n throw new Error(`Unknown modifier ${String(unknown)}`);\n }\n }\n}\n\n/** One text input hint for the text fields below, over the ones above. */\nfunction withTextInputHint(hint: TextInputHints, node: ReactNode): ReactElement {\n return createElement(TextInputHint, { hint }, node);\n}\n\nfunction TextInputHint({ hint, children }: { hint: TextInputHints; children?: ReactNode }): ReactNode {\n const outer = useViewEnvironment().textInputHints;\n return withEnvironment({ textInputHints: { ...outer, ...hint } }, children);\n}\n","/**\n * `HostElement`: an element of a kind of the app's own (`'app:preview'`),\n * for a host that draws it. A tree drawn by another root's `RemoteTree`\n * (an app inside a platform's page) names the kind, with the props the\n * host's view wants, and the host draws its own view there (`RemoteTree`'s\n * `elements`): a file's preview, a map, whatever the host has and the app\n * has not. The modifiers apply around it as around any view. Where no host\n * draws the kind, the renderer draws nothing for it.\n */\nimport type { ReactNode } from 'react';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, type ViewModifiers } from '../modifiers';\n\nexport interface HostElementProps extends ViewModifiers {\n /** The kind, as the host's `elements` names it: a prefix of the host's own keeps it apart from SwiftBrowser's kinds (`'noya:file'`). */\n kind: string;\n /** What the host's view takes: plain data (JSON). */\n props?: Readonly<Record<string, unknown>>;\n children?: ReactNode;\n}\n\nexport function HostElement(props: HostElementProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n return applyModifiers(sb(own.kind, own.props ? { ...own.props } : undefined, undefined, own.children), modifiers);\n}\n","/**\n * `measureText(text, font, width)`: the size a `Text` of `text` in `font`\n * takes wrapped to `width`, answered synchronously by whatever draws the\n * app: on the web the renderer's typography (the same wrapping and line\n * heights its layout engine uses, `mount` installs it), natively the host's\n * `NSAttributedString` bounding rect through the bridge (`run` installs it).\n * For an app that lays out from text sizes itself: pagination, say. SwiftUI\n * has no such call; this is the one `UIFont` and `NSAttributedString` give.\n */\n\nimport type { Font as ProtocolFont } from '@swiftbrowser/web/src/protocol';\nimport { font as fontOf, type FontValue } from './values';\n\nexport interface TextMeasurement {\n /** The widest line, in points. */\n width: number;\n /** The lines' height, as a `Text` is tall. */\n height: number;\n /** How many lines the text wraps to (one for an empty text). */\n lines: number;\n}\n\n/** What answers `measureText`: the renderer's or the host's measurer. */\nexport type TextMeasurerFunction = (text: string, font: ProtocolFont, width: number | null) => TextMeasurement;\n\nlet installed: TextMeasurerFunction | null = null;\n\n/** Points `measureText` at a measurer (`mount`, `run`); the same one again to remove it. */\nexport function installTextMeasurer(measurer: TextMeasurerFunction | null, remove = false): void {\n if (remove) {\n if (installed === measurer) installed = null;\n return;\n }\n installed = measurer;\n}\n\n/** Whether something answers `measureText` here (a mounted app, a native host). */\nexport function canMeasureText(): boolean {\n return installed !== null;\n}\n\n/**\n * The size of `text` in `font` (a text style name or `system(size, weight,\n * design)`; `body` by default) wrapped to `width` points, or on one line\n * when `width` is omitted. Throws before an app is mounted or run.\n */\nexport function measureText(text: string, font: FontValue = 'body', width?: number): TextMeasurement {\n if (!installed) throw new Error('measureText: nothing measures text here yet (mount the app, or run it in a SwiftBrowser Native host)');\n const constrained = typeof width === 'number' && Number.isFinite(width) && width > 0 ? width : null;\n return installed(text, fontOf(font), constrained);\n}\n","/**\n * `mount(screen, element)`: the renderer of @swiftbrowser/web in `screen`\n * (the root container, element id 0, inside the device frame or full screen)\n * drawing a SwiftUI root. The page keeps the device chrome (theme, text size)\n * and tells both sides through `setEnvironment`; the size class follows the\n * root's width, the scene phase the document's visibility and focus, and the\n * platform (docs/notes/macos.md) the browser, unless the page says.\n */\n\nimport { horizontalSizeClassFor, type ColorScheme, type DynamicTypeSize, type Platform } from '@swiftbrowser/web/src/protocol';\nimport type { AssetCatalog } from '@swiftbrowser/web/src/assets';\nimport { BrowserHistory } from '@swiftbrowser/web/src/browserHistory';\nimport { watchKeyboard } from '@swiftbrowser/web/src/deviceMode';\nimport { browserEnvironment } from '@swiftbrowser/web/src/hostRequests';\nimport { Renderer } from '@swiftbrowser/web/src/renderer';\nimport { currentScenePhase, watchScenePhase } from '@swiftbrowser/web/src/scenePhase';\nimport type { ReactNode } from 'react';\nimport { createSwiftUIRoot, type SwiftUIRoot } from './host/root';\nimport { installTextMeasurer, type TextMeasurerFunction } from './measureText';\n\nexport interface MountOptions {\n colorScheme?: ColorScheme;\n dynamicTypeSize?: DynamicTypeSize;\n /**\n * The platform the app is drawn as (docs/notes/macos.md): `ios` or\n * `macos`, or `auto` (the default), which is macOS in a browser with a\n * fine pointer that can hover (a desktop) showing the root at 700 CSS px\n * or more, and iOS otherwise. A preview page's device picker\n * (`installDeviceFrame`) sets it afterwards from the device chosen.\n */\n platform?: Platform | 'auto';\n /** Device mode: the real safe-area insets (frame mode has the iPhone's). */\n safeArea?: { top: number; leading: number; bottom: number; trailing: number } | null;\n /** The root is as tall as its content (an island in a page), not as the screen. */\n contentHeight?: boolean;\n /**\n * The asset catalog manifest `Image(name:)` and catalog colors resolve\n * against (the `/catalog/<App>.json` the SwiftBrowser build writes, or one\n * of your own: `{ images: { name: { src, width, height, scale, kind } }, colors: {} }`).\n */\n assets?: AssetCatalog;\n /**\n * The app's name: its files (`fileManager`) live in the IndexedDB database\n * `sb-files:<app>`, as a Swift app's of that name do. `app` by default.\n */\n app?: string;\n /**\n * Mirror navigation in the browser's history (the default): pushing a\n * screen, presenting a sheet or moving a split view's sidebar selection\n * adds an entry, and the browser's back and edge swipe pop, dismiss or\n * reselect it (the renderer's own swipe back is then off).\n * The URL is left alone; map screens to paths yourself with\n * `history.replaceState` (not `pushState`, which would add a second entry).\n * `false` leaves the history untouched, for an island in a page whose own\n * router owns it.\n */\n history?: boolean;\n /**\n * Follow the on-screen keyboard (a phone's): its height becomes a bottom\n * inset, so a field, a bottom search field or a chat's composer rises\n * above it and a list stops above it, as on iOS, instead of the browser\n * panning the page to the field. For a root that fills the layout\n * viewport (a full-screen app); off by default.\n */\n keyboard?: boolean;\n /**\n * The Mac's sidebar panel paints its top 44 points in the window's color,\n * where macOS draws the title bar behind the window's buttons (`true`, the\n * default). `false` keeps the panel's sidebar fill to its top: a page has\n * no window buttons there. Web only (a native app is in a real window).\n */\n sidebarTitleBar?: boolean;\n}\n\nexport interface Mounted {\n root: SwiftUIRoot;\n renderer: Renderer;\n /** The device environment, for the renderer and the tree both (the page's theme toggle, a device picker's platform). */\n setEnvironment(environment: { colorScheme?: ColorScheme; dynamicTypeSize?: DynamicTypeSize; platform?: Platform }): void;\n /** The renderer's (`installDeviceFrame` drives these). */\n setSafeArea(insets: { top: number; leading: number; bottom: number; trailing: number } | null): void;\n viewportChanged(): void;\n unmount(): void;\n}\n\n/**\n * The platform `auto` decides for a root `width` CSS px wide: macOS with a\n * fine pointer that hovers (a desktop browser) at the regular width, iOS\n * otherwise. Width alone is no signal: a narrow desktop window is not a phone.\n */\nexport function decidePlatform(width: number, media: (query: string) => boolean = matchesMedia): Platform {\n return horizontalSizeClassFor(width) === 'regular' && media('(hover: hover) and (pointer: fine)') ? 'macos' : 'ios';\n}\n\nfunction matchesMedia(query: string): boolean {\n return typeof matchMedia === 'function' && matchMedia(query).matches;\n}\n\nexport function mount(screen: HTMLElement, element: ReactNode, options: MountOptions = {}): Mounted {\n let renderer: Renderer | null = null;\n const root = createSwiftUIRoot((ops) => renderer?.applyOps(ops));\n renderer = new Renderer(screen, (event) => root.dispatch(event));\n // A React app is in the page: a dropped file comes as the `File` itself, a dropped folder as its files by path (src/dragDrop.ts).\n renderer.fileDrops = 'reference';\n // `measureText` answers from this renderer's typography while it is mounted.\n const measurer: TextMeasurerFunction = (text, font, width) => renderer!.measureText(text, font, width);\n installTextMeasurer(measurer);\n // The page's appearance; `.preferredColorScheme` overrides it while set.\n let pageScheme: ColorScheme = options.colorScheme ?? 'light';\n let preferred: ColorScheme | null = null;\n const width = screen.clientWidth || 393;\n const environment = {\n colorScheme: pageScheme,\n dynamicTypeSize: options.dynamicTypeSize ?? 'large',\n horizontalSizeClass: horizontalSizeClassFor(width),\n scenePhase: typeof document !== 'undefined' ? currentScenePhase() : ('active' as const),\n platform: options.platform === undefined || options.platform === 'auto' ? decidePlatform(width) : options.platform,\n };\n renderer.contentHeight = options.contentHeight ?? false;\n if (options.sidebarTitleBar === false) renderer.sidebarTitleBar = false;\n if (options.assets) renderer.setAssetCatalog(options.assets);\n if (options.app) (browserEnvironment.files as { setApp?: (app: string) => void } | undefined)?.setApp?.(options.app);\n renderer.setEnvironment({ colorScheme: environment.colorScheme, dynamicTypeSize: environment.dynamicTypeSize, platform: environment.platform });\n if (options.safeArea !== undefined) renderer.setSafeArea(options.safeArea);\n root.setEnvironment(environment);\n const browserHistory = (options.history ?? true) && typeof window !== 'undefined' ? new BrowserHistory(renderer, screen) : null;\n browserHistory?.enable();\n const stopKeyboard = options.keyboard && typeof window !== 'undefined' ? watchKeyboard((height) => renderer?.setKeyboard(height), { root: screen }) : null;\n\n const applyScheme = (): void => {\n const scheme = preferred ?? pageScheme;\n const device = screen.closest<HTMLElement>('.device');\n if (device) device.dataset['theme'] = scheme;\n renderer?.setEnvironment({ colorScheme: scheme });\n root.setEnvironment({ colorScheme: scheme });\n };\n const onPreferredScheme = (event: Event): void => {\n const scheme = (event as CustomEvent<{ colorScheme: ColorScheme | null }>).detail.colorScheme;\n preferred = scheme;\n // Outside the commit that asked for it.\n queueMicrotask(applyScheme);\n };\n screen.addEventListener('sb:color-scheme', onPreferredScheme);\n\n // The size class follows the root's width (700 points and up is regular).\n let sizeClass = environment.horizontalSizeClass;\n const observer =\n typeof ResizeObserver !== 'undefined'\n ? new ResizeObserver(() => {\n const next = horizontalSizeClassFor(screen.clientWidth);\n if (next === sizeClass) return;\n sizeClass = next;\n root.setEnvironment({ horizontalSizeClass: next });\n })\n : null;\n observer?.observe(screen);\n // The scene phase follows the document (hidden: background) and the window's focus.\n const stopScenePhase = typeof document !== 'undefined' ? watchScenePhase((scenePhase) => root.setEnvironment({ scenePhase })) : null;\n\n root.render(element);\n const mounted: Mounted = {\n root,\n renderer,\n setEnvironment(next) {\n if (next.colorScheme !== undefined) pageScheme = next.colorScheme;\n const scheme = preferred ?? pageScheme;\n renderer?.setEnvironment({ ...next, colorScheme: scheme });\n root.setEnvironment({ ...next, colorScheme: scheme });\n },\n setSafeArea(insets) {\n renderer?.setSafeArea(insets);\n },\n viewportChanged() {\n renderer?.viewportChanged();\n },\n unmount() {\n observer?.disconnect();\n stopScenePhase?.();\n stopKeyboard?.();\n browserHistory?.dispose();\n screen.removeEventListener('sb:color-scheme', onPreferredScheme);\n installTextMeasurer(measurer, true);\n root.unmount();\n renderer?.dispose();\n },\n };\n return mounted;\n}\n","/**\n * `useUndoManager()`: SwiftUI's `@Environment(\\.undoManager)`. The manager\n * keeps a stack of named undo closures with `NSUndoManager`'s rules: a\n * closure registered while undoing goes on the redo stack (so an undo's\n * inverse re-registers as its redo), a new registration drops what could be\n * redone, registrations in one event form one group, and\n * `beginGrouping`/`endGrouping` (or `group`) make one of several events. A\n * registration with a `key` joins the group on top when it has the same key,\n * so a run of keystrokes undoes at once.\n *\n * The stack is the truth: the closures are JavaScript, and `canUndo` must\n * change in the pass that registered them. The system is told what the\n * stack can do and sends its undo and redo here, through the renderer\n * environment's `undoManager` host (Web/src/undo.ts): the keyboard on a\n * page, the window's `UndoManager` natively (its shake, three-finger swipe,\n * keyboard and Edit menu), which mirrors this one.\n */\n\nimport { browserEnvironment } from '@swiftbrowser/web/src/hostRequests';\nimport type { UndoHost, UndoState } from '@swiftbrowser/web/src/undo';\nimport { createContext, useContext, useSyncExternalStore } from 'react';\n\nexport type { UndoHost, UndoState };\n\nexport interface UndoOptions {\n /** Who registered it (`removeAllActions(target)` drops its actions, as `removeAllActions(withTarget:)` does): a document, a view. */\n target?: object;\n /**\n * A registration with the same key as the one before joins its group, so a\n * run of typing in one field (`text:<field>`) undoes at once; an undo, a\n * redo or a registration with another key (or none) ends the run.\n */\n key?: string;\n}\n\nexport interface UndoManagerOptions {\n /** Where the system's undo comes from; the renderer environment's host by default, none for a manager of its own. */\n host?: UndoHost | null;\n /** Closes the group an event opened; the microtask queue by default (the event has ended by then). */\n schedule?: (close: () => void) => void;\n}\n\ninterface Action {\n name: string;\n undo: () => void;\n target: object | undefined;\n}\n\ninterface Group {\n /** The name of what the group undoes, '' when its registrations had none. */\n name: string;\n /** Fixed by `beginGrouping(name)`; otherwise the last registration's. */\n named: boolean;\n actions: Action[];\n key: string | undefined;\n}\n\nconst EMPTY: UndoState = { canUndo: false, canRedo: false, undoActionName: '', redoActionName: '' };\n\nconst defaultSchedule = (close: () => void): void => {\n if (typeof queueMicrotask === 'function') queueMicrotask(close);\n else void Promise.resolve().then(close);\n};\n\nexport class UndoManager {\n /** Whether registrations in one event (one task of the event loop) form one group; true, as `groupsByEvent`. */\n groupsByEvent = true;\n /** How many groups the undo stack keeps; 0 for no limit, as `levelsOfUndo`. */\n levelsOfUndo = 0;\n\n private undoStack: Group[] = [];\n private redoStack: Group[] = [];\n /** The group registrations go in: an explicit group, the event's group, or the inverse of what is being undone or redone. */\n private open: Group | null = null;\n /** How deep `beginGrouping` is; 0 when `open` is the event's group or an inverse. */\n private depth = 0;\n /** Whether `open` is the event's group, which `schedule` closes. */\n private byEvent = false;\n /** The last keyed group closed onto the undo stack, which a registration with its key joins. */\n private coalescing: Group | null = null;\n private undoing = false;\n private redoing = false;\n private snapshot: UndoState = EMPTY;\n private readonly listeners = new Set<() => void>();\n private readonly schedule: (close: () => void) => void;\n private readonly host: UndoHost | null;\n private stopListening: (() => void) | null = null;\n\n constructor(options: UndoManagerOptions = {}) {\n this.schedule = options.schedule ?? defaultSchedule;\n this.host = options.host === undefined ? (browserEnvironment.undoManager ?? null) : options.host;\n if (this.host) {\n this.stopListening = this.host.listen({ undo: () => this.undo(), redo: () => this.redo() });\n this.host.update(this.snapshot);\n }\n }\n\n get canUndo(): boolean {\n return this.undoStack.length > 0;\n }\n\n get canRedo(): boolean {\n return this.redoStack.length > 0;\n }\n\n /** The name of what `undo` takes back ('' for none): \"Move\" for an Edit menu's \"Undo Move\". */\n get undoActionName(): string {\n return this.undoStack[this.undoStack.length - 1]?.name ?? '';\n }\n\n get redoActionName(): string {\n return this.redoStack[this.redoStack.length - 1]?.name ?? '';\n }\n\n get isUndoing(): boolean {\n return this.undoing;\n }\n\n get isRedoing(): boolean {\n return this.redoing;\n }\n\n /** What the stacks can do, one object per change (for `useSyncExternalStore`). */\n get state(): UndoState {\n return this.snapshot;\n }\n\n /**\n * Registers what undoes the change just made, under `name`. Run by `undo`,\n * the closure registers its own inverse the same way, which lands on the\n * redo stack because the manager is undoing.\n */\n registerUndo(name: string, undo: () => void, options: UndoOptions = {}): void {\n const action: Action = { name, undo, target: options.target };\n if (this.undoing || this.redoing) {\n // The inverse of the group being run (`undo` or `redo` opened it), named after that group.\n this.open!.actions.push(action);\n this.changed();\n return;\n }\n this.redoStack = [];\n this.coalescing = this.coalescing && this.undoStack[this.undoStack.length - 1] === this.coalescing ? this.coalescing : null;\n if (this.open) {\n // An explicit group goes on the stack with its first registration (an empty one never does).\n if (!this.undoStack.includes(this.open)) this.push(this.open);\n this.open.actions.push(action);\n if (!this.open.named) this.open.name = name;\n } else if (this.coalescing && options.key !== undefined && this.coalescing.key === options.key) {\n this.coalescing.actions.push(action);\n this.coalescing.name = name;\n } else {\n const group: Group = { name, named: false, actions: [action], key: options.key };\n this.push(group);\n this.coalescing = null;\n if (this.groupsByEvent) {\n this.open = group;\n this.byEvent = true;\n this.schedule(() => {\n if (this.open === group && this.byEvent) this.close();\n });\n } else {\n this.coalescing = group.key !== undefined ? group : null;\n }\n }\n this.changed();\n }\n\n /** Takes back the top group of changes; its inverses become the top of the redo stack. */\n undo(): void {\n this.endOpenGroups();\n const group = this.undoStack.pop();\n if (!group) return;\n this.coalescing = null;\n this.run(group, 'undo');\n }\n\n redo(): void {\n this.endOpenGroups();\n const group = this.redoStack.pop();\n if (!group) return;\n this.run(group, 'redo');\n }\n\n /**\n * Starts a group: every registration until `endGrouping` undoes as one\n * (`beginUndoGrouping`). Nested calls join the outer group. The group is\n * named `name`, else after its last registration.\n */\n beginGrouping(name?: string): void {\n if (this.undoing || this.redoing) return;\n this.depth += 1;\n if (this.depth > 1) return;\n if (this.open) this.close();\n this.open = { name: name ?? '', named: name !== undefined, actions: [], key: undefined };\n this.byEvent = false;\n this.coalescing = null;\n }\n\n /** Ends the group `beginGrouping` started; one that registered nothing is dropped. */\n endGrouping(): void {\n if (this.depth === 0) return;\n this.depth -= 1;\n if (this.depth === 0) this.close();\n }\n\n /** `body` as one group named `name`. */\n group<T>(name: string, body: () => T): T {\n this.beginGrouping(name);\n try {\n return body();\n } finally {\n this.endGrouping();\n }\n }\n\n /** Forgets every registration, or those `target` made (`removeAllActions(withTarget:)`), on both stacks and in the open group. */\n removeAllActions(target?: object): void {\n const mine = (action: Action): boolean => target === undefined || action.target === target;\n const strip = (groups: Group[]): Group[] =>\n groups.filter((group) => {\n group.actions = group.actions.filter((action) => !mine(action));\n return group.actions.length > 0;\n });\n this.undoStack = strip(this.undoStack);\n this.redoStack = strip(this.redoStack);\n if (this.open) this.open.actions = this.open.actions.filter((action) => !mine(action));\n if (this.coalescing && !this.undoStack.includes(this.coalescing)) this.coalescing = null;\n this.changed();\n }\n\n /** Calls `listener` after each change to `state`; returns what stops it. */\n readonly subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n };\n\n /** Stops listening to the host, for a manager made in a test. */\n dispose(): void {\n this.stopListening?.();\n this.stopListening = null;\n }\n\n private push(group: Group): void {\n this.undoStack.push(group);\n if (this.levelsOfUndo > 0 && this.undoStack.length > this.levelsOfUndo) this.undoStack.splice(0, this.undoStack.length - this.levelsOfUndo);\n }\n\n /** Closes `open`; a keyed group on top stays open to its key. */\n private close(): void {\n const group = this.open;\n this.open = null;\n this.byEvent = false;\n if (group && group.key !== undefined && this.undoStack[this.undoStack.length - 1] === group) this.coalescing = group;\n }\n\n private endOpenGroups(): void {\n this.depth = 0;\n if (this.open) this.close();\n }\n\n private run(group: Group, direction: 'undo' | 'redo'): void {\n const inverse: Group = { name: group.name, named: true, actions: [], key: undefined };\n this.open = inverse;\n this.byEvent = false;\n if (direction === 'undo') this.undoing = true;\n else this.redoing = true;\n try {\n for (let i = group.actions.length - 1; i >= 0; i -= 1) group.actions[i]!.undo();\n } finally {\n this.undoing = false;\n this.redoing = false;\n this.open = null;\n if (inverse.actions.length > 0) {\n if (direction === 'undo') this.redoStack.push(inverse);\n else this.push(inverse);\n }\n this.changed();\n }\n }\n\n private changed(): void {\n const next: UndoState = { canUndo: this.canUndo, canRedo: this.canRedo, undoActionName: this.undoActionName, redoActionName: this.redoActionName };\n const last = this.snapshot;\n if (next.canUndo === last.canUndo && next.canRedo === last.canRedo && next.undoActionName === last.undoActionName && next.redoActionName === last.redoActionName) return;\n this.snapshot = next;\n this.host?.update(next);\n for (const listener of [...this.listeners]) listener();\n }\n}\n\n/** A manager for the views below, in place of the page's (an island with a stack of its own, a test). */\nexport const UndoManagerContext = createContext<UndoManager | null>(null);\n\nlet shared: UndoManager | null = null;\n\n/** The page's manager, made on first use and connected to the environment's host. */\nfunction sharedUndoManager(): UndoManager {\n shared ??= new UndoManager();\n return shared;\n}\n\n/**\n * The window's undo manager: `registerUndo(name, undo)` after a change,\n * `undo()`, `redo()`, and `canUndo`, `canRedo`, `undoActionName` and\n * `redoActionName`, which re-render the view as they change.\n */\nexport function useUndoManager(): UndoManager {\n const manager = useContext(UndoManagerContext) ?? sharedUndoManager();\n useSyncExternalStore(\n manager.subscribe,\n () => manager.state,\n () => manager.state,\n );\n return manager;\n}\n","/**\n * React context does not cross a root boundary, and a `Host` (a react-dom\n * root inside the SwiftUI tree) or a `SwiftUIView` (a SwiftUI root inside a\n * react-dom tree) is one. The bridge reads the contexts on the outer side and\n * provides them again on the inner side. This package's own contexts always\n * travel; a component names any others it needs.\n */\n\nimport { createElement, useContext, type Context, type ReactNode } from 'react';\nimport { DismissContext, EnvironmentContext, ViewEnvironmentContext } from './environment';\nimport { NavigationContext } from './navigation-context';\nimport { UndoManagerContext } from './undo';\n\nconst OWN: readonly Context<unknown>[] = [\n EnvironmentContext as Context<unknown>,\n ViewEnvironmentContext as Context<unknown>,\n NavigationContext as Context<unknown>,\n DismissContext as Context<unknown>,\n UndoManagerContext as Context<unknown>,\n];\n\n/**\n * Returns a function that wraps `children` in providers of the current\n * values of this package's contexts and of `contexts`. The list of contexts\n * must not change between renders (each is read with a hook).\n */\nexport function useContextBridge(\n contexts: readonly Context<unknown>[] = [],\n options: { environment?: boolean } = {},\n): (children: ReactNode) => ReactNode {\n // An island is the source of its own device environment (its root\n // provides it), so it bridges everything but that.\n const own = options.environment === false ? OWN.filter((context) => context !== (EnvironmentContext as Context<unknown>)) : OWN;\n const all = [...own, ...contexts];\n // One hook per context, in a stable order: the list is fixed per call site.\n const values = all.map((context) => useContext(context));\n return (children) =>\n all.reduceRight<ReactNode>((inner, context, index) => createElement(context.Provider, { value: values[index] }, inner), children);\n}\n","/**\n * `SwiftUIView`: a SwiftUI tree inside a react-dom app. The element carries\n * the device's design tokens (the `device` class, without its frame) and the\n * renderer draws the tree in it. `fit=\"fill\"` draws in the box the page\n * gives it (give it a height); `fit=\"content\"` makes the island as tall as\n * its content. Navigation stacks and tab views fill the box, so they want\n * `fill`.\n */\n\nimport type { AssetCatalog } from '@swiftbrowser/web/src/assets';\nimport type { ColorScheme, DynamicTypeSize } from '@swiftbrowser/web/src/protocol';\nimport { applyTypeSizeVariables } from '@swiftbrowser/web/src/typography';\nimport { useLayoutEffect, useRef, type CSSProperties, type Context, type ReactNode } from 'react';\nimport { useContextBridge } from './bridge';\nimport { mount, type Mounted } from './mount';\n\nexport interface SwiftUIViewProps {\n children?: ReactNode;\n fit?: 'fill' | 'content';\n colorScheme?: ColorScheme;\n dynamicTypeSize?: DynamicTypeSize;\n /** Contexts of the page the SwiftUI tree reads (this package's own are not needed). */\n contexts?: readonly Context<unknown>[];\n /** The asset catalog manifest for `Image(name:)` and catalog colors (see `mount`). */\n assets?: AssetCatalog;\n /**\n * Insets the views keep clear of, as a device's status bar and home\n * indicator: a navigation bar sits below `top` (its background reaching\n * into it), a list starts below it. A number is the top inset. By default\n * a `fill` island keeps `WINDOW_TOP_INSET` at the top, as SwiftUI keeps its\n * bars off a window's edge where there is no status bar; `content` has none.\n */\n safeArea?: number | Partial<SafeAreaInsets>;\n /**\n * Mirror navigation in the browser's history (the default): a pushed\n * screen, a presented sheet or a moved split-view sidebar selection adds\n * an entry, and the browser's back and edge swipe pop, dismiss or\n * reselect it. The URL is left alone; set paths with\n * `history.replaceState`. `false` for an island in a page whose own router\n * owns the history.\n */\n history?: boolean;\n /**\n * Follow the on-screen keyboard: its height becomes a bottom inset, so a\n * field, a bottom search field or a chat's composer rises above it and a\n * list stops above it, as on iOS, instead of the browser panning the page\n * to the field. On by default for a `fill` island, which fills the layout\n * viewport as a full-screen app; a `content` island in a page leaves the\n * page to the browser.\n */\n keyboard?: boolean;\n /**\n * The Mac's sidebar panel paints its top 44 points in the window's color,\n * behind where macOS draws the window's buttons (`true`, the default);\n * `false` keeps the panel's sidebar fill to its top, as a page has no\n * window buttons there (see `mount`).\n */\n sidebarTitleBar?: boolean;\n className?: string;\n style?: CSSProperties;\n}\n\ninterface SafeAreaInsets {\n top: number;\n leading: number;\n bottom: number;\n trailing: number;\n}\n\n/** The top inset of a `fill` island: a window's bar row clear of its edge. */\nconst WINDOW_TOP_INSET = 10;\n\nexport function insetsOf(safeArea: SwiftUIViewProps['safeArea'], fit: 'fill' | 'content'): SafeAreaInsets {\n const given = typeof safeArea === 'number' ? { top: safeArea } : (safeArea ?? { top: fit === 'fill' ? WINDOW_TOP_INSET : 0 });\n return { top: given.top ?? 0, leading: given.leading ?? 0, bottom: given.bottom ?? 0, trailing: given.trailing ?? 0 };\n}\n\nexport function SwiftUIView({\n children,\n fit = 'fill',\n colorScheme = 'light',\n dynamicTypeSize = 'large',\n contexts,\n assets,\n safeArea,\n history = true,\n keyboard = fit === 'fill',\n sidebarTitleBar = true,\n className,\n style,\n}: SwiftUIViewProps): ReactNode {\n const device = useRef<HTMLDivElement>(null);\n const screen = useRef<HTMLDivElement>(null);\n const mounted = useRef<Mounted | null>(null);\n const bridge = useContextBridge(contexts, { environment: false });\n const tree = bridge(children);\n const latest = useRef(tree);\n latest.current = tree;\n\n useLayoutEffect(() => {\n if (!screen.current) return;\n const instance = mount(screen.current, latest.current, {\n colorScheme,\n dynamicTypeSize,\n safeArea: insetsOf(safeArea, fit),\n contentHeight: fit === 'content',\n history,\n keyboard,\n ...(assets ? { assets } : {}),\n });\n mounted.current = instance;\n return () => {\n mounted.current = null;\n instance.unmount();\n };\n // The environment is updated below; a change of fit, history or keyboard re-mounts.\n }, [fit, history, keyboard]);\n\n // After the mount above, so a new renderer takes it too; a change applies in place.\n useLayoutEffect(() => {\n if (mounted.current) mounted.current.renderer.sidebarTitleBar = sidebarTitleBar;\n }, [sidebarTitleBar, fit, history, keyboard]);\n\n useLayoutEffect(() => {\n mounted.current?.root.render(tree);\n });\n\n const insets = insetsOf(safeArea, fit);\n const insetsKey = `${insets.top},${insets.leading},${insets.bottom},${insets.trailing}`;\n useLayoutEffect(() => {\n mounted.current?.renderer.setSafeArea(insets);\n // Keyed by value: a new object each render is the same insets.\n }, [insetsKey]);\n\n useLayoutEffect(() => {\n if (device.current) applyTypeSizeVariables(device.current, dynamicTypeSize, mounted.current?.renderer.platform);\n mounted.current?.setEnvironment({ colorScheme, dynamicTypeSize });\n }, [colorScheme, dynamicTypeSize]);\n\n const classes = ['device', 'sb-island', className].filter(Boolean).join(' ');\n return (\n <div ref={device} className={classes} data-theme={colorScheme} data-type-size={dynamicTypeSize} data-state=\"ready\" data-sb-fit={fit} style={style}>\n <div className=\"device-screen\">\n <div ref={screen} className=\"screen\" />\n </div>\n </div>\n );\n}\n","/**\n * `Path`: a builder for SVG path data, in SwiftUI's vocabulary. Custom\n * shapes (`Shape` with a `path` function) and `Canvas` drawing take one.\n * Points are rounded to hundredths, as the Swift shim rounds them.\n */\n\nexport interface Point {\n x: number;\n y: number;\n}\n\nexport interface CGRect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\nconst r = (n: number): string => {\n const v = Math.round(n * 100) / 100;\n return Object.is(v, -0) ? '0' : String(v);\n};\n\nexport class Path {\n private readonly parts: string[] = [];\n private current: Point | null = null;\n private start: Point | null = null;\n\n constructor(build?: (path: Path) => void) {\n build?.(this);\n }\n\n /** `Path(rect)` */\n static rect(rect: CGRect): Path {\n return new Path().addRect(rect);\n }\n /** `Path(roundedRect:cornerRadius:)` */\n static roundedRect(rect: CGRect, cornerRadius: number): Path {\n return new Path().addRoundedRect(rect, cornerRadius);\n }\n /** `Path(ellipseIn:)` */\n static ellipse(rect: CGRect): Path {\n return new Path().addEllipse(rect);\n }\n\n move(to: Point): this {\n this.parts.push(`M${r(to.x)} ${r(to.y)}`);\n this.current = to;\n this.start = to;\n return this;\n }\n\n addLine(to: Point): this {\n if (!this.current) return this.move(to);\n this.parts.push(`L${r(to.x)} ${r(to.y)}`);\n this.current = to;\n return this;\n }\n\n addLines(points: readonly Point[]): this {\n points.forEach((point, index) => (index === 0 ? this.move(point) : this.addLine(point)));\n return this;\n }\n\n addQuadCurve(to: Point, control: Point): this {\n if (!this.current) this.move(control);\n this.parts.push(`Q${r(control.x)} ${r(control.y)} ${r(to.x)} ${r(to.y)}`);\n this.current = to;\n return this;\n }\n\n addCurve(to: Point, control1: Point, control2: Point): this {\n if (!this.current) this.move(control1);\n this.parts.push(`C${r(control1.x)} ${r(control1.y)} ${r(control2.x)} ${r(control2.y)} ${r(to.x)} ${r(to.y)}`);\n this.current = to;\n return this;\n }\n\n /**\n * `addArc(center:radius:startAngle:endAngle:clockwise:)`, angles in\n * degrees. As in SwiftUI's flipped coordinates, `clockwise: false` draws\n * clockwise on screen.\n */\n addArc(center: Point, radius: number, startAngle: number, endAngle: number, clockwise: boolean): this {\n const rad = (deg: number): number => (deg * Math.PI) / 180;\n const point = (deg: number): Point => ({ x: center.x + radius * Math.cos(rad(deg)), y: center.y + radius * Math.sin(rad(deg)) });\n const from = point(startAngle);\n if (this.current) this.addLine(from);\n else this.move(from);\n // On screen (y down), SwiftUI's `clockwise: false` sweeps with increasing angles.\n const sweepPositive = !clockwise;\n let delta = endAngle - startAngle;\n if (sweepPositive) while (delta < 0) delta += 360;\n else while (delta > 0) delta -= 360;\n if (Math.abs(delta) >= 360) {\n // A full circle: two half arcs.\n const half = point(startAngle + (sweepPositive ? 180 : -180));\n const flag = sweepPositive ? 1 : 0;\n this.parts.push(`A${r(radius)} ${r(radius)} 0 0 ${flag} ${r(half.x)} ${r(half.y)}`);\n this.parts.push(`A${r(radius)} ${r(radius)} 0 0 ${flag} ${r(from.x)} ${r(from.y)}`);\n this.current = from;\n return this;\n }\n const to = point(startAngle + delta);\n const large = Math.abs(delta) > 180 ? 1 : 0;\n this.parts.push(`A${r(radius)} ${r(radius)} 0 ${large} ${sweepPositive ? 1 : 0} ${r(to.x)} ${r(to.y)}`);\n this.current = to;\n return this;\n }\n\n addRect(rect: CGRect): this {\n this.move({ x: rect.x, y: rect.y });\n this.addLine({ x: rect.x + rect.width, y: rect.y });\n this.addLine({ x: rect.x + rect.width, y: rect.y + rect.height });\n this.addLine({ x: rect.x, y: rect.y + rect.height });\n return this.closeSubpath();\n }\n\n addRoundedRect(rect: CGRect, cornerRadius: number): this {\n const c = Math.max(0, Math.min(cornerRadius, rect.width / 2, rect.height / 2));\n if (c === 0) return this.addRect(rect);\n const { x, y, width: w, height: h } = rect;\n this.move({ x: x + c, y });\n this.addLine({ x: x + w - c, y });\n this.parts.push(`A${r(c)} ${r(c)} 0 0 1 ${r(x + w)} ${r(y + c)}`);\n this.current = { x: x + w, y: y + c };\n this.addLine({ x: x + w, y: y + h - c });\n this.parts.push(`A${r(c)} ${r(c)} 0 0 1 ${r(x + w - c)} ${r(y + h)}`);\n this.current = { x: x + w - c, y: y + h };\n this.addLine({ x: x + c, y: y + h });\n this.parts.push(`A${r(c)} ${r(c)} 0 0 1 ${r(x)} ${r(y + h - c)}`);\n this.current = { x, y: y + h - c };\n this.addLine({ x, y: y + c });\n this.parts.push(`A${r(c)} ${r(c)} 0 0 1 ${r(x + c)} ${r(y)}`);\n this.current = { x: x + c, y };\n return this.closeSubpath();\n }\n\n addEllipse(rect: CGRect): this {\n const rx = rect.width / 2;\n const ry = rect.height / 2;\n const cx = rect.x + rx;\n const cy = rect.y + ry;\n this.move({ x: cx + rx, y: cy });\n this.parts.push(`A${r(rx)} ${r(ry)} 0 0 1 ${r(cx - rx)} ${r(cy)}`);\n this.parts.push(`A${r(rx)} ${r(ry)} 0 0 1 ${r(cx + rx)} ${r(cy)}`);\n this.current = { x: cx + rx, y: cy };\n return this.closeSubpath();\n }\n\n addPath(path: Path): this {\n this.parts.push(path.svg());\n return this;\n }\n\n closeSubpath(): this {\n this.parts.push('Z');\n this.current = this.start;\n return this;\n }\n\n get isEmpty(): boolean {\n return this.parts.length === 0;\n }\n\n /** The SVG path data. */\n svg(): string {\n return this.parts.join('');\n }\n\n toString(): string {\n return this.svg();\n }\n}\n","/**\n * Attributed text, SwiftUI's `AttributedString` as the rich `TextEditor`\n * edits it (`TextEditor(text: $attributed, selection: $selection)`, iOS 26):\n * runs of text, each with its own weight, slant, lines and color. Plain\n * objects, so the text saves as JSON; the functions here are what an edit\n * in the editor does to it.\n */\n\nimport type { FontDesign, FontWeight, TextRun } from '@swiftbrowser/web/src/protocol';\nimport { color, type ColorValue } from './values';\n\n/** A run's own font over the editor's (`AttributedString`'s `font`): `Font.system(size:weight:design:)`'s parts, each optional. */\nexport interface RunFont {\n size?: number;\n weight?: FontWeight;\n design?: FontDesign;\n}\n\nexport interface AttributedRun {\n text: string;\n bold?: boolean;\n italic?: boolean;\n underline?: boolean;\n strikethrough?: boolean;\n /** The run's color, over the editor's foreground. */\n foregroundColor?: ColorValue;\n /** A color behind the run's glyphs (`backgroundColor`): a find highlight, say. */\n backgroundColor?: ColorValue;\n /** The run's size, weight or design over the editor's font (`bold` is the weight `bold` when the font names none). */\n font?: RunFont;\n}\n\nexport type AttributedText = readonly AttributedRun[];\n\n/** A range of an editor's text in UTF-16 offsets (JavaScript's string indices); `start === end` is the caret. */\nexport interface TextSelection {\n start: number;\n end: number;\n}\n\n/** A run's attributes without its text. */\nexport type TextAttributes = Omit<AttributedRun, 'text'>;\n\nconst plain = (text: AttributedText): string => text.map((run) => run.text).join('');\n\nfunction attributesOf(run: AttributedRun | undefined): TextAttributes {\n if (!run) return {};\n const { text: _text, ...attributes } = run;\n return attributes;\n}\n\n/** Whether two runs look the same (an absent flag is false). */\nfunction alike(a: TextAttributes, b: TextAttributes): boolean {\n return (\n !a.bold === !b.bold &&\n !a.italic === !b.italic &&\n !a.underline === !b.underline &&\n !a.strikethrough === !b.strikethrough &&\n JSON.stringify(a.foregroundColor ?? null) === JSON.stringify(b.foregroundColor ?? null) &&\n JSON.stringify(a.backgroundColor ?? null) === JSON.stringify(b.backgroundColor ?? null) &&\n JSON.stringify(runFont(a.font) ?? null) === JSON.stringify(runFont(b.font) ?? null)\n );\n}\n\n/** A run font with its fields in one order and none unset, or undefined when it says nothing. */\nfunction runFont(font: RunFont | undefined): RunFont | undefined {\n if (!font) return undefined;\n const out: RunFont = {};\n if (typeof font.size === 'number' && Number.isFinite(font.size) && font.size > 0) out.size = font.size;\n if (font.weight) out.weight = font.weight;\n if (font.design) out.design = font.design;\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/** The same text with no empty runs and no two alike side by side. */\nfunction normalized(text: AttributedText): AttributedText {\n const runs: AttributedRun[] = [];\n for (const run of text) {\n if (!run.text) continue;\n const last = runs[runs.length - 1];\n if (last && alike(last, run)) runs[runs.length - 1] = { ...last, text: last.text + run.text };\n else runs.push(run);\n }\n return runs;\n}\n\n/** The runs between two offsets, cut where they fall. */\nfunction slice(text: AttributedText, start: number, end = Infinity): AttributedText {\n const runs: AttributedRun[] = [];\n let at = 0;\n for (const run of text) {\n const from = Math.max(start, at);\n const to = Math.min(end, at + run.text.length);\n if (from < to) runs.push({ ...run, text: run.text.slice(from - at, to - at) });\n at += run.text.length;\n }\n return runs;\n}\n\n/** The attributes of the character at `offset` (the last one's past the end; none in an empty text). */\nfunction attributesAt(text: AttributedText, offset: number): TextAttributes {\n let at = 0;\n for (const run of text) {\n if (offset < at + run.text.length) return attributesOf(run);\n at += run.text.length;\n }\n return attributesOf([...text].reverse().find((run) => run.text.length > 0));\n}\n\n/**\n * `text` changed to read `next`, as a keystroke, a paste or a deletion in\n * the editor changes it: the start and end that did not change keep their\n * runs, and what was typed takes the attributes of what it replaced, else\n * of the character before it (the first character's, typed at the start).\n */\nfunction replacingCharacters(text: AttributedText, next: string): AttributedText {\n const old = plain(text);\n if (old === next) return text;\n let head = 0;\n const shorter = Math.min(old.length, next.length);\n while (head < shorter && old[head] === next[head]) head++;\n let tail = 0;\n while (tail < shorter - head && old[old.length - 1 - tail] === next[next.length - 1 - tail]) tail++;\n const removedEnd = old.length - tail;\n const typed = next.slice(head, next.length - tail);\n const attributes = attributesAt(text, removedEnd > head || head === 0 ? head : head - 1);\n return normalized([...slice(text, 0, head), { ...attributes, text: typed }, ...slice(text, removedEnd)]);\n}\n\n/** `text` with `change` over the characters between `start` and `end`. */\nfunction settingAttributes(text: AttributedText, start: number, end: number, change: TextAttributes): AttributedText {\n const inside = slice(text, start, end).map((run) => ({ ...run, ...change }));\n return normalized([...slice(text, 0, start), ...inside, ...slice(text, end)]);\n}\n\n/** Whether every character between `start` and `end` has `key` on (false for an empty range). */\nfunction every(text: AttributedText, start: number, end: number, key: 'bold' | 'italic' | 'underline' | 'strikethrough'): boolean {\n const inside = slice(text, start, end);\n return inside.length > 0 && inside.every((run) => run[key] === true);\n}\n\n/** The functions over attributed text, as `AttributedString`'s methods. */\nexport const AttributedText = {\n plain,\n normalized,\n slice,\n attributesAt,\n replacingCharacters,\n settingAttributes,\n every,\n /** A text of one run. */\n of: (text: string, attributes: TextAttributes = {}): AttributedText => normalized([{ ...attributes, text }]),\n};\n\n/** The weights `fromProtocolRuns` reads as bold (the native editor names the system's Bold `bold`; an app may have sent a heavier one). */\nconst BOLD_WEIGHTS = new Set(['semibold', 'bold', 'heavy', 'black']);\n\n/**\n * The text the protocol's runs stand for (a `runs` event: the native\n * editor's own Bold, Italic or Underline over the text), `protocolRuns`\n * read back: a bold weight is `bold`, a line is on, a color is the run's,\n * and a run's size, design and other weight are its `font`.\n */\nexport function fromProtocolRuns(runs: readonly TextRun[]): AttributedText {\n return normalized(\n runs.map((run) => {\n const out: AttributedRun = { text: run.text ?? '' };\n const font = (run.font ?? {}) as { weight?: unknown; size?: unknown; design?: unknown };\n const bold = typeof font.weight === 'string' && BOLD_WEIGHTS.has(font.weight);\n if (bold) out.bold = true;\n const own = runFont({\n ...(typeof font.size === 'number' ? { size: font.size } : {}),\n ...(typeof font.weight === 'string' && !bold ? { weight: font.weight as FontWeight } : {}),\n ...(typeof font.design === 'string' ? { design: font.design as FontDesign } : {}),\n });\n if (own) out.font = own;\n if (run.italic) out.italic = true;\n if (run.underline) out.underline = true;\n if (run.strikethrough) out.strikethrough = true;\n if (run.foreground !== undefined) out.foregroundColor = run.foreground as ColorValue;\n if (run.background !== undefined) out.backgroundColor = run.background as ColorValue;\n return out;\n }),\n );\n}\n\n/** The protocol's runs for a text: a run's font over the editor's (bold is the weight `bold`), its lines and colors. */\nexport function protocolRuns(text: AttributedText): TextRun[] {\n return text.map((run) => {\n const out: TextRun = { text: run.text };\n const font = { ...(runFont(run.font) ?? {}) };\n if (run.bold && !font.weight) font.weight = 'bold';\n if (Object.keys(font).length > 0) out.font = font;\n if (run.italic) out.italic = true;\n if (run.underline) out.underline = {};\n if (run.strikethrough) out.strikethrough = {};\n if (run.foregroundColor !== undefined) out.foreground = color(run.foregroundColor);\n if (run.backgroundColor !== undefined) out.background = color(run.backgroundColor);\n return out;\n });\n}\n","/**\n * `useAudioRecorder()`: the microphone, as an iOS app records with\n * `AVAudioRecorder`. `record()` asks for the microphone and starts; while it\n * records the hook meters the input (`levels`, one 0…1 level per tick, for a\n * waveform) and counts `time`; `stop()` resolves with the recording's URL\n * (a `data:` URL on a page, a file natively) to play with `useAVPlayer`;\n * `trim()` makes a new recording out of parts of one. The page records with\n * `MediaRecorder` and cuts with the Web Audio API (Web/src/audioRecorder.ts);\n * the native app answers with `AVAudioRecorder` and `AVAssetExportSession`\n * (AudioRecorderBridge.swift).\n */\n\nimport type { AudioRange, AudioRecording } from '@swiftbrowser/web/src/audioRecorder';\nimport { browserEnvironment } from '@swiftbrowser/web/src/hostRequests';\nimport { useCallback, useEffect, useRef, useState } from 'react';\n\nexport type { AudioRange, AudioRecording };\n\nexport type AudioRecorderStatus = 'idle' | 'starting' | 'recording' | 'paused' | 'stopping';\n\nexport interface AudioRecorder {\n /** Whether this page or app can record at all. */\n available: boolean;\n status: AudioRecorderStatus;\n /** Seconds recorded so far (it holds while paused). */\n time: number;\n /** The input's level at each tick of this recording (0 silent … 1 loud), oldest first. */\n levels: readonly number[];\n /** Why the last call failed (`permission: …` when the microphone was refused), or null. */\n error: string | null;\n record(): Promise<void>;\n pause(): Promise<void>;\n resume(): Promise<void>;\n /** Ends the recording and resolves with it, or null when there was none. */\n stop(): Promise<AudioRecording | null>;\n /** Ends the recording and keeps nothing. */\n cancel(): Promise<void>;\n /** Deletes a recording `stop` made before (its file, natively), when the app deletes it. */\n discard(url: string): Promise<void>;\n /**\n * A new recording made of the parts of `url` in `keep` (seconds, in\n * order, concatenated): `[{ start, end }]` trims to that range, two parts\n * around a range delete it. Resolves with the new recording (a `data:` URL\n * on a page, a new file natively); the original is left as it was (the app\n * discards it when it no longer wants it). Rejects with `unsupported: …`\n * where the host cannot cut audio.\n */\n trim(url: string, keep: readonly { start: number; end: number }[]): Promise<AudioRecording>;\n}\n\nexport interface AudioRecorderOptions {\n /** Milliseconds between meter readings (50: twenty a second). */\n meterInterval?: number;\n}\n\nexport function useAudioRecorder(options: AudioRecorderOptions = {}): AudioRecorder {\n const interval = options.meterInterval ?? 50;\n const host = browserEnvironment.audioRecorder;\n const [status, setStatus] = useState<AudioRecorderStatus>('idle');\n const [time, setTime] = useState(0);\n const [levels, setLevels] = useState<readonly number[]>([]);\n const [error, setError] = useState<string | null>(null);\n const statusRef = useRef(status);\n statusRef.current = status;\n\n const fail = (reason: unknown): void => setError(reason instanceof Error ? reason.message : String(reason));\n\n // Meter while recording; one reading at a time, so a slow host never queues them.\n useEffect(() => {\n if (status !== 'recording' || !host) return;\n let reading = false;\n let live = true;\n const timer = setInterval(() => {\n if (reading) return;\n reading = true;\n host\n .meter()\n .then((meter) => {\n if (!live) return;\n setTime(meter.time);\n setLevels((previous) => [...previous, meter.level]);\n })\n .catch(() => undefined)\n .finally(() => {\n reading = false;\n });\n }, interval);\n return () => {\n live = false;\n clearInterval(timer);\n };\n }, [status, host, interval]);\n\n // A recording still going when the view goes is cancelled.\n useEffect(\n () => () => {\n if (statusRef.current !== 'idle') void host?.cancel().catch(() => undefined);\n },\n [host],\n );\n\n const record = useCallback(async (): Promise<void> => {\n if (!host) {\n setError('unsupported: this page cannot record');\n return;\n }\n if (statusRef.current !== 'idle') return;\n setError(null);\n setTime(0);\n setLevels([]);\n setStatus('starting');\n try {\n await host.start();\n setStatus('recording');\n } catch (reason) {\n fail(reason);\n setStatus('idle');\n }\n }, [host]);\n\n const pause = useCallback(async (): Promise<void> => {\n if (!host || statusRef.current !== 'recording') return;\n await host.pause().catch(fail);\n setStatus('paused');\n }, [host]);\n\n const resume = useCallback(async (): Promise<void> => {\n if (!host || statusRef.current !== 'paused') return;\n await host.resume().catch(fail);\n setStatus('recording');\n }, [host]);\n\n const stop = useCallback(async (): Promise<AudioRecording | null> => {\n if (!host || (statusRef.current !== 'recording' && statusRef.current !== 'paused')) return null;\n setStatus('stopping');\n try {\n const recording = await host.stop();\n setTime(recording.duration);\n return recording;\n } catch (reason) {\n fail(reason);\n return null;\n } finally {\n setStatus('idle');\n }\n }, [host]);\n\n const cancel = useCallback(async (): Promise<void> => {\n if (!host || statusRef.current === 'idle') return;\n await host.cancel().catch(fail);\n setStatus('idle');\n setTime(0);\n setLevels([]);\n }, [host]);\n\n const discard = useCallback(async (url: string): Promise<void> => {\n await host?.discard(url).catch(fail);\n }, [host]);\n\n // The cut needs no status: it reads one recording and writes another while the recorder does as it was.\n const trim = useCallback(\n async (url: string, keep: readonly AudioRange[]): Promise<AudioRecording> => {\n if (!host) throw new Error('unsupported: this page cannot cut audio');\n try {\n return await host.trim(url, keep);\n } catch (reason) {\n fail(reason);\n throw reason;\n }\n },\n [host],\n );\n\n return { available: host !== undefined, status, time, levels, error, record, pause, resume, stop, cancel, discard, trim };\n}\n","/**\n * AVFoundation's assets, as an iOS app edits video: `CMTime` and\n * `CMTimeRange`; `AVURLAsset` (`load('duration')`, `load('tracks')`,\n * `loadTracks(withMediaType)`); `AVAssetImageGenerator` (a still at a time,\n * for thumbnails and filmstrips); `AVMutableComposition` (parts of assets\n * placed in order: trims, cuts, joins); and `AVAssetExportSession` (an\n * asset or a composition written as a file, with a preset and a\n * `timeRange`). The host does the work (`browserEnvironment.avAsset`): the\n * page with WebCodecs (Web/src/avAsset.ts), the native app with\n * AVFoundation itself (AVAssetBridge.swift). A still or an export is a URL\n * an `Image`, `AsyncImage` or `VideoPlayer` shows (a `blob:` URL on a page, a\n * file natively), or the app's own `outputURL`.\n */\n\nimport { browserEnvironment } from '@swiftbrowser/web/src/hostRequests';\nimport type { AssetExportResult, AssetFileType, AssetInfo, AssetSegment, AVAssetHost } from '@swiftbrowser/web/src/avAsset';\n\nfunction host(): AVAssetHost {\n const found = browserEnvironment.avAsset;\n if (!found) throw new Error('unsupported: this page cannot read or write video');\n return found;\n}\n\n// ---------------------------------------------------------------------------\n// CMTime, CMTimeRange\n// ---------------------------------------------------------------------------\n\n/** `CMTime`: a time as `value / timescale` seconds (600 is the usual video timescale). */\nexport class CMTime {\n static readonly zero = new CMTime(0, 1);\n static readonly invalid = new CMTime(0, 0);\n static readonly positiveInfinity = new CMTime(Infinity, 1);\n\n constructor(\n readonly value: number,\n readonly timescale: number,\n ) {}\n\n /** `CMTime(value:timescale:)`. */\n static make(value: number, timescale: number): CMTime {\n return new CMTime(value, timescale);\n }\n\n /** `CMTime(seconds:preferredTimescale:)`: rounded to the timescale. */\n static seconds(seconds: number, preferredTimescale = 600): CMTime {\n if (!Number.isFinite(seconds)) return seconds > 0 ? CMTime.positiveInfinity : CMTime.invalid;\n return new CMTime(Math.round(seconds * preferredTimescale), preferredTimescale);\n }\n\n get isValid(): boolean {\n return this.timescale > 0;\n }\n\n /** `CMTimeGetSeconds`. */\n get seconds(): number {\n return this.timescale > 0 ? this.value / this.timescale : Number.NaN;\n }\n\n add(other: CMTime): CMTime {\n return CMTime.seconds(this.seconds + other.seconds, Math.max(this.timescale, other.timescale, 1));\n }\n\n subtract(other: CMTime): CMTime {\n return CMTime.seconds(this.seconds - other.seconds, Math.max(this.timescale, other.timescale, 1));\n }\n\n /** `CMTimeCompare`: -1, 0 or 1. */\n compare(other: CMTime): -1 | 0 | 1 {\n const a = this.seconds;\n const b = other.seconds;\n return a < b ? -1 : a > b ? 1 : 0;\n }\n\n static minimum(a: CMTime, b: CMTime): CMTime {\n return a.compare(b) <= 0 ? a : b;\n }\n\n static maximum(a: CMTime, b: CMTime): CMTime {\n return a.compare(b) >= 0 ? a : b;\n }\n}\n\n/** `CMTimeRange`: from `start`, `duration` long. */\nexport class CMTimeRange {\n static readonly zero = new CMTimeRange(CMTime.zero, CMTime.zero);\n\n constructor(\n readonly start: CMTime,\n readonly duration: CMTime,\n ) {}\n\n /** `CMTimeRange(start:end:)`. */\n static fromTo(start: CMTime, end: CMTime): CMTimeRange {\n return new CMTimeRange(start, CMTime.maximum(end.subtract(start), CMTime.zero));\n }\n\n /** `CMTimeRange(start:duration:)` in seconds. */\n static seconds(start: number, duration: number, preferredTimescale = 600): CMTimeRange {\n return new CMTimeRange(CMTime.seconds(start, preferredTimescale), CMTime.seconds(duration, preferredTimescale));\n }\n\n get end(): CMTime {\n return this.start.add(this.duration);\n }\n\n get isEmpty(): boolean {\n return this.duration.seconds <= 0;\n }\n\n containsTime(time: CMTime): boolean {\n return time.compare(this.start) >= 0 && time.compare(this.end) < 0;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Assets\n// ---------------------------------------------------------------------------\n\n/** `AVMediaType`. */\nexport const AVMediaType = { video: 'vide', audio: 'soun' } as const;\nexport type AVMediaType = (typeof AVMediaType)[keyof typeof AVMediaType];\n\n/** `AVAssetTrack`: one of an asset's tracks. */\nexport class AVAssetTrack {\n constructor(\n readonly trackID: number,\n readonly mediaType: AVMediaType,\n /** The display size (its rotation applied), 0 × 0 for audio. */\n readonly naturalSize: { width: number; height: number },\n readonly nominalFrameRate: number,\n readonly timeRange: CMTimeRange,\n /** The codec (`avc`, `hevc`, `vp9`, `aac`, `opus` …), or null when unknown. */\n readonly codec: string | null,\n ) {}\n}\n\n/** What `load` answers for each key, as `try await asset.load(.duration)` does. */\nexport interface AVAssetProperties {\n duration: CMTime;\n tracks: AVAssetTrack[];\n naturalSize: { width: number; height: number };\n isPlayable: boolean;\n isExportable: boolean;\n}\n\n/** `AVAsset`: media to read, play and write; an `AVURLAsset` or an `AVMutableComposition`. */\nexport abstract class AVAsset {\n /** The parts of files this asset is made of, in order (an `AVURLAsset` is one whole file). */\n protected abstract segments(): Promise<AssetSegment[]>;\n /** @internal */\n segmentsForExport(): Promise<AssetSegment[]> {\n return this.segments();\n }\n abstract load<K extends keyof AVAssetProperties>(key: K): Promise<AVAssetProperties[K]>;\n\n /** `loadTracks(withMediaType:)`. */\n async loadTracks(mediaType: AVMediaType): Promise<AVAssetTrack[]> {\n return (await this.load('tracks')).filter((track) => track.mediaType === mediaType);\n }\n}\n\nconst tracksOf = (info: AssetInfo): AVAssetTrack[] =>\n info.tracks.map(\n (t) =>\n new AVAssetTrack(\n t.trackID,\n t.mediaType === 'video' ? AVMediaType.video : AVMediaType.audio,\n t.naturalSize,\n t.nominalFrameRate,\n CMTimeRange.seconds(t.timeRange.start, t.timeRange.duration),\n t.codec,\n ),\n );\n\n/** `AVURLAsset(url:)`: the media at a URL (a file of the app's, a `blob:`, `data:` or `http(s):` URL). */\nexport class AVURLAsset extends AVAsset {\n private info: Promise<AssetInfo> | null = null;\n\n constructor(readonly url: string) {\n super();\n }\n\n private loaded(): Promise<AssetInfo> {\n if (!this.info) {\n this.info = host().load(this.url);\n // A failed load is tried again on the next `load`.\n this.info.catch(() => {\n this.info = null;\n });\n }\n return this.info;\n }\n\n protected async segments(): Promise<AssetSegment[]> {\n return [{ url: this.url, start: 0, end: (await this.loaded()).duration }];\n }\n\n async load<K extends keyof AVAssetProperties>(key: K): Promise<AVAssetProperties[K]> {\n const info = await this.loaded();\n const values: AVAssetProperties = {\n duration: CMTime.seconds(info.duration),\n tracks: tracksOf(info),\n naturalSize: info.naturalSize,\n isPlayable: info.tracks.length > 0,\n isExportable: info.tracks.length > 0,\n };\n return values[key];\n }\n}\n\n/** One part of a composition: `asset`'s media in `range`, placed at `at`. */\ninterface CompositionPart {\n asset: AVURLAsset;\n range: CMTimeRange;\n}\n\n/**\n * `AVMutableComposition`: parts of assets placed one after another, as a\n * timeline editor cuts and joins them. `insertTimeRange(_:of:at:)` places a\n * part at a time (splitting the part already there), `removeTimeRange(_:)`\n * cuts a range out (the rest closes up), and the composition plays nowhere\n * itself: export it (`AVAssetExportSession`) to watch or keep it.\n */\nexport class AVMutableComposition extends AVAsset {\n private parts: CompositionPart[] = [];\n\n /** The composition's length. */\n get duration(): CMTime {\n return CMTime.seconds(this.parts.reduce((sum, part) => sum + part.range.duration.seconds, 0));\n }\n\n /** `insertTimeRange(_:of:at:)`: `range` of `asset` (an `AVURLAsset`, or another composition's parts) placed at `at`. */\n async insertTimeRange(range: CMTimeRange, asset: AVAsset, at: CMTime): Promise<void> {\n const inserted: CompositionPart[] = [];\n if (asset instanceof AVURLAsset) {\n const length = (await asset.load('duration')).seconds;\n const start = Math.max(0, range.start.seconds);\n const end = Math.min(length, range.end.seconds);\n if (end - start > 1e-3) inserted.push({ asset, range: CMTimeRange.seconds(start, end - start) });\n } else if (asset instanceof AVMutableComposition) {\n inserted.push(...asset.partsIn(range.start.seconds, range.end.seconds));\n } else {\n throw new Error('unsupported: only an AVURLAsset or an AVMutableComposition can be inserted');\n }\n const time = Math.max(0, Math.min(at.seconds, this.duration.seconds));\n const [before, after] = this.splitAt(time);\n this.parts = [...before, ...inserted, ...after];\n }\n\n /** `removeTimeRange(_:)`: the media in `range` cut out, the rest closing up. */\n removeTimeRange(range: CMTimeRange): void {\n const [before] = this.splitAt(range.start.seconds);\n const [, after] = this.splitAt(range.end.seconds);\n this.parts = [...before, ...after];\n }\n\n /** The parts' media from `start` to `end` of the composition's timeline. */\n private partsIn(start: number, end: number): CompositionPart[] {\n const [, from] = this.splitAt(start);\n const out: CompositionPart[] = [];\n let cursor = start;\n for (const part of from) {\n if (cursor >= end) break;\n const take = Math.min(part.range.duration.seconds, end - cursor);\n if (take > 1e-3) out.push({ asset: part.asset, range: CMTimeRange.seconds(part.range.start.seconds, take) });\n cursor += take;\n }\n return out;\n }\n\n /** The parts before `time` and from it, a part across it split in two. */\n private splitAt(time: number): [CompositionPart[], CompositionPart[]] {\n const before: CompositionPart[] = [];\n const after: CompositionPart[] = [];\n let cursor = 0;\n for (const part of this.parts) {\n const length = part.range.duration.seconds;\n const start = part.range.start.seconds;\n if (cursor + length <= time + 1e-9) before.push(part);\n else if (cursor >= time - 1e-9) after.push(part);\n else {\n const head = time - cursor;\n before.push({ asset: part.asset, range: CMTimeRange.seconds(start, head) });\n after.push({ asset: part.asset, range: CMTimeRange.seconds(start + head, length - head) });\n }\n cursor += length;\n }\n return [before, after];\n }\n\n protected async segments(): Promise<AssetSegment[]> {\n return this.parts.map((part) => ({ url: part.asset.url, start: part.range.start.seconds, end: part.range.end.seconds }));\n }\n\n async load<K extends keyof AVAssetProperties>(key: K): Promise<AVAssetProperties[K]> {\n const first = this.parts[0]?.asset;\n const tracks = first ? await first.load('tracks') : [];\n const values: AVAssetProperties = {\n duration: this.duration,\n tracks: tracks.map((t) => new AVAssetTrack(t.trackID, t.mediaType, t.naturalSize, t.nominalFrameRate, new CMTimeRange(CMTime.zero, this.duration), t.codec)),\n naturalSize: first ? await first.load('naturalSize') : { width: 0, height: 0 },\n isPlayable: this.parts.length > 0,\n isExportable: this.parts.length > 0,\n };\n return values[key];\n }\n}\n\n// ---------------------------------------------------------------------------\n// Image generation\n// ---------------------------------------------------------------------------\n\n/** A still `AVAssetImageGenerator` made: a URL an `Image` or `AsyncImage` shows, the time of the frame drawn, and its size. */\nexport interface AVAssetImage {\n image: string;\n actualTime: CMTime;\n width: number;\n height: number;\n}\n\n/**\n * `AVAssetImageGenerator(asset:)`: stills of a video, for a thumbnail or a\n * trim editor's filmstrip. `maximumSize` bounds them (aspect kept; 0 on an\n * axis leaves it open); `image(at:)` answers the frame at (or nearest\n * before) a time; `images(for:)` one after another.\n */\nexport class AVAssetImageGenerator {\n maximumSize: { width: number; height: number } = { width: 0, height: 0 };\n /** Stills come upright (the track's rotation applied), as with `appliesPreferredTrackTransform = true`. */\n appliesPreferredTrackTransform = true;\n private readonly made: string[] = [];\n\n constructor(readonly asset: AVAsset) {}\n\n /** The file and the time in it that `time` on the asset's timeline falls on (a composition's part). */\n private async source(time: number): Promise<{ url: string; time: number }> {\n let cursor = 0;\n const segments = await this.asset.segmentsForExport();\n for (const segment of segments) {\n const length = segment.end - segment.start;\n if (time < cursor + length || segment === segments[segments.length - 1]) return { url: segment.url, time: segment.start + Math.max(0, Math.min(length, time - cursor)) };\n cursor += length;\n }\n throw new Error('empty: the asset has no media');\n }\n\n /** `image(at:)`: the still at `time`. */\n async image(at: CMTime): Promise<AVAssetImage> {\n const { url, time } = await this.source(Math.max(0, at.seconds));\n const options = {\n ...(this.maximumSize.width > 0 ? { maxWidth: this.maximumSize.width } : {}),\n ...(this.maximumSize.height > 0 ? { maxHeight: this.maximumSize.height } : {}),\n };\n const still = await host().image(url, time, options);\n this.made.push(still.url);\n return { image: still.url, actualTime: CMTime.seconds(at.seconds + (still.actualTime - time)), width: still.width, height: still.height };\n }\n\n /** `images(for:)`: a still for each time, in turn. */\n async *images(times: readonly CMTime[]): AsyncGenerator<AVAssetImage & { requestedTime: CMTime }> {\n for (const time of times) yield { ...(await this.image(time)), requestedTime: time };\n }\n\n /** Lets go of the stills this generator made (their `blob:` URLs on a page). */\n async release(): Promise<void> {\n const urls = this.made.splice(0);\n await Promise.all(urls.map((url) => host().release(url)));\n }\n}\n\n// ---------------------------------------------------------------------------\n// Export\n// ---------------------------------------------------------------------------\n\n/** `AVFileType` (and WebM, which a page writes and AVFoundation does not). */\nexport const AVFileType = { mp4: 'public.mpeg-4', mov: 'com.apple.quicktime-movie', m4v: 'com.apple.m4v-video', webm: 'org.webmproject.webm' } as const;\nexport type AVFileType = (typeof AVFileType)[keyof typeof AVFileType];\n\nconst FILE_TYPES: Record<AVFileType, AssetFileType> = {\n 'public.mpeg-4': 'mp4',\n 'com.apple.m4v-video': 'mp4',\n 'com.apple.quicktime-movie': 'mov',\n 'org.webmproject.webm': 'webm',\n};\n\nexport const AVAssetExportPresetPassthrough = 'AVAssetExportPresetPassthrough';\nexport const AVAssetExportPresetHighestQuality = 'AVAssetExportPresetHighestQuality';\nexport const AVAssetExportPresetMediumQuality = 'AVAssetExportPresetMediumQuality';\nexport const AVAssetExportPresetLowQuality = 'AVAssetExportPresetLowQuality';\nexport const AVAssetExportPreset640x480 = 'AVAssetExportPreset640x480';\nexport const AVAssetExportPreset960x540 = 'AVAssetExportPreset960x540';\nexport const AVAssetExportPreset1280x720 = 'AVAssetExportPreset1280x720';\nexport const AVAssetExportPreset1920x1080 = 'AVAssetExportPreset1920x1080';\nexport const AVAssetExportPreset3840x2160 = 'AVAssetExportPreset3840x2160';\n\n/** `AVAssetExportSession.Status`. */\nexport type AVAssetExportSessionStatus = 'unknown' | 'waiting' | 'exporting' | 'completed' | 'failed' | 'cancelled';\n\nlet exports = 0;\n\n/**\n * `AVAssetExportSession(asset:presetName:)`: an asset (or a composition)\n * written as one file. `AVAssetExportPresetPassthrough` copies the media,\n * its cuts on key frames; the other presets re-encode it, cutting exactly,\n * fitted to the preset's size. `timeRange` keeps only that part (a trim);\n * `outputURL` is the app's file to write (else the host makes one, which\n * `export()` answers); `outputFileType` the container. While it runs,\n * `progress` goes 0 to 1 (`onProgress` hears it); `cancelExport()` stops it.\n */\nexport class AVAssetExportSession {\n outputURL: string | null = null;\n outputFileType: AVFileType = AVFileType.mp4;\n timeRange: CMTimeRange | null = null;\n status: AVAssetExportSessionStatus = 'unknown';\n progress = 0;\n error: Error | null = null;\n /** Heard as `progress` changes (a few times a second). */\n onProgress: ((progress: number) => void) | null = null;\n /** The written file's length and MIME type, once completed. */\n result: Omit<AssetExportResult, 'url'> | null = null;\n private readonly id = `export-${++exports}`;\n\n constructor(\n readonly asset: AVAsset,\n readonly presetName: string,\n ) {}\n\n /** `AVAssetExportSession.allExportPresets()`. */\n static allExportPresets(): string[] {\n return [\n AVAssetExportPresetPassthrough,\n AVAssetExportPresetHighestQuality,\n AVAssetExportPresetMediumQuality,\n AVAssetExportPresetLowQuality,\n AVAssetExportPreset640x480,\n AVAssetExportPreset960x540,\n AVAssetExportPreset1280x720,\n AVAssetExportPreset1920x1080,\n AVAssetExportPreset3840x2160,\n ];\n }\n\n /** The asset's parts, cut to `timeRange` when it is set. */\n private async parts(): Promise<AssetSegment[]> {\n const all = await this.asset.segmentsForExport();\n if (!this.timeRange) return all;\n const from = this.timeRange.start.seconds;\n const to = this.timeRange.end.seconds;\n const out: AssetSegment[] = [];\n let cursor = 0;\n for (const segment of all) {\n const length = segment.end - segment.start;\n const start = Math.max(from, cursor);\n const end = Math.min(to, cursor + length);\n if (end - start > 1e-3) out.push({ url: segment.url, start: segment.start + (start - cursor), end: segment.start + (end - cursor) });\n cursor += length;\n }\n return out;\n }\n\n /** `export()`: writes the file and answers its URL (also `outputURL`); rejects with why it could not. */\n async export(): Promise<string> {\n if (this.status === 'exporting') throw new Error('busy: already exporting');\n this.status = 'exporting';\n this.error = null;\n this.setProgress(0);\n const assets = host();\n const ticker = setInterval(() => {\n void assets.progress(this.id).then((p) => this.status === 'exporting' && this.setProgress(p));\n }, 200);\n try {\n const result = await assets.export(this.id, {\n segments: await this.parts(),\n preset: this.presetName,\n fileType: FILE_TYPES[this.outputFileType] ?? 'mp4',\n ...(this.outputURL ? { outputURL: this.outputURL } : {}),\n });\n this.outputURL = result.url;\n this.result = { duration: result.duration, type: result.type };\n this.status = 'completed';\n this.setProgress(1);\n return result.url;\n } catch (reason) {\n const error = reason instanceof Error ? reason : new Error(String(reason));\n this.error = error;\n this.status = error.message.startsWith('cancelled') ? 'cancelled' : 'failed';\n throw error;\n } finally {\n clearInterval(ticker);\n }\n }\n\n /** `cancelExport()`. */\n cancelExport(): void {\n if (this.status !== 'exporting') return;\n void host().cancel(this.id);\n }\n\n private setProgress(progress: number): void {\n if (progress === this.progress) return;\n this.progress = progress;\n this.onProgress?.(progress);\n }\n}\n","/**\n * `useVideoRecorder()`: the camera, as an iOS app records video with an\n * `AVCaptureSession` and a movie file output. `open()` asks for the camera\n * and the microphone and starts the live picture, which `CameraPreview`\n * shows; `record()` records it and `time` counts; `stop()` resolves with\n * the recording (a URL to play with `useAVPlayer`, its length, type and\n * size) and leaves the camera open for the next; `close()` lets the camera\n * go (as leaving the view does). The page records with `getUserMedia` and\n * `MediaRecorder` (Web/src/videoRecorder.ts) into a `blob:` URL; the native\n * app with an `AVCaptureSession` (VideoRecorderBridge.swift) into a\n * QuickTime file in Documents/Recordings.\n */\n\nimport type { CameraFacing, VideoRecording } from '@swiftbrowser/web/src/videoRecorder';\nimport { browserEnvironment } from '@swiftbrowser/web/src/hostRequests';\nimport { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';\nimport { sb } from './host/sb';\nimport { applyModifiers, splitProps, type ViewModifiers } from './modifiers';\n\nexport type { CameraFacing, VideoRecording };\n\n/** `closed` (no camera), `opening` (asking for it), `ready` (its picture shows), `recording`, `paused`, `stopping`. */\nexport type VideoRecorderStatus = 'closed' | 'opening' | 'ready' | 'recording' | 'paused' | 'stopping';\n\nexport interface VideoRecorder {\n /** Whether this page or app can record video at all. */\n available: boolean;\n status: VideoRecorderStatus;\n /** The live picture's stream while the camera is open, for `CameraPreview`. */\n stream: string | null;\n /** The camera in use. */\n facing: CameraFacing;\n /** Seconds recorded so far (it holds while paused). */\n time: number;\n /** Why the last call failed (`permission: …` when the camera was refused), or null. */\n error: string | null;\n /** Opens the camera (`facing`, else the one used last, else the front); the picture shows once `status` is `ready`. */\n open(facing?: CameraFacing): Promise<void>;\n /** Lets the camera go (a recording under way is cancelled). */\n close(): Promise<void>;\n /** The other camera, front or back. */\n flip(): Promise<void>;\n record(): Promise<void>;\n pause(): Promise<void>;\n resume(): Promise<void>;\n /** Ends the recording and resolves with it, or null when there was none. The camera stays open. */\n stop(): Promise<VideoRecording | null>;\n /** Ends the recording and keeps nothing. */\n cancel(): Promise<void>;\n /** Lets go of a recording `stop` made, when the app is done with it (saved it, or deleted it). */\n discard(url: string): Promise<void>;\n}\n\nexport interface VideoRecorderOptions {\n /** Milliseconds between readings of the recorded time (100: ten a second). */\n timeInterval?: number;\n}\n\nexport function useVideoRecorder(options: VideoRecorderOptions = {}): VideoRecorder {\n const interval = options.timeInterval ?? 100;\n const host = browserEnvironment.videoRecorder;\n const [status, setStatus] = useState<VideoRecorderStatus>('closed');\n const [stream, setStream] = useState<string | null>(null);\n const [facing, setFacing] = useState<CameraFacing>('user');\n const [time, setTime] = useState(0);\n const [error, setError] = useState<string | null>(null);\n const statusRef = useRef(status);\n statusRef.current = status;\n const facingRef = useRef(facing);\n facingRef.current = facing;\n const fail = (reason: unknown): void => setError(reason instanceof Error ? reason.message : String(reason));\n\n // The time while recording; one reading at a time, so a slow host never queues them.\n useEffect(() => {\n if (status !== 'recording' || !host) return;\n let reading = false;\n let live = true;\n const timer = setInterval(() => {\n if (reading) return;\n reading = true;\n host\n .time()\n .then((seconds) => live && setTime(seconds))\n .catch(() => undefined)\n .finally(() => {\n reading = false;\n });\n }, interval);\n return () => {\n live = false;\n clearInterval(timer);\n };\n }, [status, host, interval]);\n\n // The camera goes with the view (a recording under way is cancelled).\n useEffect(\n () => () => {\n if (statusRef.current !== 'closed') void host?.close().catch(() => undefined);\n },\n [host],\n );\n\n const open = useCallback(\n async (wanted?: CameraFacing): Promise<void> => {\n if (!host) {\n setError('unsupported: this page cannot record video');\n return;\n }\n if (statusRef.current === 'recording' || statusRef.current === 'paused' || statusRef.current === 'stopping') return;\n setError(null);\n setStatus('opening');\n try {\n const opened = await host.open({ facing: wanted ?? facingRef.current });\n setStream(opened.stream);\n setFacing(opened.facing);\n setStatus('ready');\n } catch (reason) {\n fail(reason);\n setStream(null);\n setStatus('closed');\n }\n },\n [host],\n );\n\n const close = useCallback(async (): Promise<void> => {\n if (!host) return;\n await host.close().catch(fail);\n setStream(null);\n setStatus('closed');\n setTime(0);\n }, [host]);\n\n const flip = useCallback(async (): Promise<void> => {\n if (statusRef.current !== 'ready') return;\n await open(facingRef.current === 'user' ? 'environment' : 'user');\n }, [open]);\n\n const record = useCallback(async (): Promise<void> => {\n if (!host || statusRef.current !== 'ready') return;\n setError(null);\n setTime(0);\n try {\n await host.start();\n setStatus('recording');\n } catch (reason) {\n fail(reason);\n }\n }, [host]);\n\n const pause = useCallback(async (): Promise<void> => {\n if (!host || statusRef.current !== 'recording') return;\n await host.pause().catch(fail);\n setStatus('paused');\n }, [host]);\n\n const resume = useCallback(async (): Promise<void> => {\n if (!host || statusRef.current !== 'paused') return;\n await host.resume().catch(fail);\n setStatus('recording');\n }, [host]);\n\n const stop = useCallback(async (): Promise<VideoRecording | null> => {\n if (!host || (statusRef.current !== 'recording' && statusRef.current !== 'paused')) return null;\n setStatus('stopping');\n try {\n const recording = await host.stop();\n setTime(recording.duration);\n return recording;\n } catch (reason) {\n fail(reason);\n return null;\n } finally {\n setStatus('ready');\n }\n }, [host]);\n\n const cancel = useCallback(async (): Promise<void> => {\n if (!host || (statusRef.current !== 'recording' && statusRef.current !== 'paused')) return;\n await host.cancel().catch(fail);\n setStatus('ready');\n setTime(0);\n }, [host]);\n\n const discard = useCallback(\n async (url: string): Promise<void> => {\n await host?.discard(url).catch(fail);\n },\n [host],\n );\n\n return { available: host !== undefined, status, stream, facing, time, error, open, close, flip, record, pause, resume, stop, cancel, discard };\n}\n\nexport interface CameraPreviewProps extends ViewModifiers {\n /** The recorder whose camera to show (its `stream`); nothing shows while it is closed. */\n recorder: Pick<VideoRecorder, 'stream' | 'facing'>;\n /** `videoGravity`: fill the view (the default, as the Camera app does) or fit in it. */\n gravity?: 'resizeAspect' | 'resizeAspectFill' | 'resize';\n /** Flipped left to right; by default the front camera is, as a mirror. */\n mirrored?: boolean;\n}\n\n/**\n * The camera's live picture (an `AVCaptureVideoPreviewLayer`), black while\n * the recorder's camera is closed. It fills its frame, cropping as needed.\n */\nexport function CameraPreview(props: CameraPreviewProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const stream = own.recorder.stream;\n if (!stream) return applyModifiers(sb('color', { color: { r: 0, g: 0, b: 0, a: 1 } }), modifiers);\n return applyModifiers(\n sb('video', {\n url: null,\n playing: false,\n muted: true,\n volume: 0,\n rate: 1,\n loop: false,\n gravity: own.gravity ?? 'resizeAspectFill',\n controls: false,\n seek: { time: 0, serial: 0 },\n stream,\n mirrored: own.mirrored ?? own.recorder.facing === 'user',\n }),\n modifiers,\n );\n}\n","/**\n * `AVAudioEngine` for a JavaScript app: the engine, its nodes and their\n * files and buffers, shaped as AVFoundation's, so an app builds a graph as\n * an iOS app does. Attach a player, a sampler, a mixer or an effect,\n * connect them toward `mainMixerNode`, `start()`, then schedule files and\n * buffers on a player (`AVAudioPlayerNode`) or play notes on a sampler\n * (`AVAudioUnitSampler`); reverb, delay, distortion, EQ and time-pitch\n * effects shape what passes through them, and `inputNode` is the\n * microphone. Each object is a number the app chooses and each call one\n * command to the host, in order: natively `AVAudioEngine` itself answers\n * (packages/native, AudioEngineBridge.swift), on a page the Web Audio API\n * (Web/src/audioEngine.ts). Per-sample work never runs in JavaScript.\n *\n * What differs from Swift: `start()`, opening a file and loading a sampler\n * are asynchronous (await them before playing); a scheduled file or\n * buffer's completion is also the promise its `schedule…` call returns; a\n * sampler's `loadAudioFiles` places each file on the keyboard by the note in\n * its name (`Piano C4.wav`, `F#2`, `60`; C4 is middle C, MIDI 60) or the\n * `rootNotes` given, each covering the keys up to halfway to the next; and\n * `meter()` reads a node's output level, as a tap would. A page cannot load\n * sound banks (`loadInstrument`) or change pitch apart from speed\n * (`AVAudioUnitTimePitch` passes its input through there).\n */\n\nimport type {\n AudioBufferInfo,\n AudioEngineCommand,\n AudioEngineHost,\n AudioFileInfo,\n AudioNodeKind,\n AudioTimeSpec,\n AudioValue,\n CustomAudioNodeKind,\n SamplerZone,\n} from '@swiftbrowser/web/src/audioEngine';\nimport { browserEnvironment } from '@swiftbrowser/web/src/hostRequests';\nimport { useEffect, useState } from 'react';\n\nexport type { AudioEngineHost, SamplerZone };\n\n/** One id space for every engine, node, file and buffer on the page or in the app. */\nlet nextId = 1;\nconst newId = (): number => nextId++;\n\nconst hostNow = (): AudioEngineHost | undefined => browserEnvironment.audioEngine;\n\nfunction unsupported(): Error {\n return new Error('unsupported: this page or app has no audio engine');\n}\n\nfunction perform<T = unknown>(command: AudioEngineCommand): Promise<T> {\n const host = hostNow();\n if (!host) return Promise.reject(unsupported());\n return host.perform(command) as Promise<T>;\n}\n\n/** A format as an app reads it: the sample rate and the channels. */\nexport interface AVAudioFormat {\n sampleRate: number;\n channelCount: number;\n}\n\n/**\n * When something starts. `new AVAudioTime(sampleTime, rate)` is a sample\n * time on a player's own timeline (frames at `rate` from when it started\n * playing): what a sequencer schedules on, sample-accurately.\n * `AVAudioTime.secondsFromNow(s)` is a delay from when the call arrives.\n */\nexport class AVAudioTime {\n readonly spec: AudioTimeSpec;\n\n constructor(sampleTime: number, atRate: number) {\n this.spec = { sampleTime: Math.round(sampleTime), sampleRate: atRate };\n }\n\n static secondsFromNow(seconds: number): AVAudioTime {\n const time = Object.create(AVAudioTime.prototype) as { spec: AudioTimeSpec };\n time.spec = { delay: Math.max(0, seconds) };\n return time as AVAudioTime;\n }\n\n get isSampleTimeValid(): boolean {\n return 'sampleTime' in this.spec;\n }\n\n get sampleTime(): number {\n return 'sampleTime' in this.spec ? this.spec.sampleTime : 0;\n }\n\n get sampleRate(): number {\n return 'sampleTime' in this.spec ? this.spec.sampleRate : 0;\n }\n\n /** The time in seconds: a sample time's place on its timeline, or the delay. */\n get seconds(): number {\n return 'sampleTime' in this.spec ? this.spec.sampleTime / this.spec.sampleRate : this.spec.delay;\n }\n}\n\n/** Frees a file or buffer's audio on the host once the app's object is gone, if the app did not `close()` it. */\nconst released =\n typeof FinalizationRegistry !== 'undefined' ? new FinalizationRegistry<number>((id) => void perform({ action: 'release', id }).catch(() => undefined)) : null;\n\n/**\n * Audio for a player to play or a sampler to load: `AVAudioFile.open(url)`\n * decodes it (natively it streams), and `read(into:)` fills a buffer from\n * `framePosition`. The URL is the app's file (`file:`), a page's URL, or a\n * `data:` URL.\n */\nexport class AVAudioFile {\n /** Where the next `read` starts, in frames. */\n framePosition = 0;\n\n private constructor(\n readonly id: number,\n readonly url: string,\n readonly length: number,\n readonly processingFormat: AVAudioFormat,\n ) {\n released?.register(this, id, this);\n }\n\n /** Opens a file for reading; rejects with `notFound: …` or `decode: …`. */\n static async open(url: string): Promise<AVAudioFile> {\n const id = newId();\n const info = await perform<AudioFileInfo>({ action: 'openFile', file: id, url });\n return new AVAudioFile(id, url, info.length, { sampleRate: info.sampleRate, channelCount: info.channelCount });\n }\n\n /** Seconds. */\n get duration(): number {\n return this.length / this.processingFormat.sampleRate;\n }\n\n /** Reads frames from `framePosition` into `buffer` (up to its capacity, or `frameCount`) and moves past them. */\n async read(into: AVAudioPCMBuffer, frameCount?: number): Promise<void> {\n const frames = Math.max(0, Math.min(frameCount ?? into.frameCapacity, into.frameCapacity, this.length - this.framePosition));\n const info = await perform<AudioBufferInfo>({ action: 'readFile', file: this.id, buffer: into.id, start: this.framePosition, frames });\n into.frameLength = info.frameLength;\n into.format = { sampleRate: info.sampleRate, channelCount: info.channelCount };\n this.framePosition += info.frameLength;\n }\n\n /** Lets the host free the decoded audio (what a scheduled segment still plays keeps playing). */\n close(): void {\n released?.unregister(this);\n void perform({ action: 'release', id: this.id }).catch(() => undefined);\n }\n}\n\n/**\n * PCM audio a player schedules: read from a file (`AVAudioFile.read(into:)`)\n * or written from the app's own samples (`write`, one `Float32Array` per\n * channel, -1 … 1), which is how a JavaScript app hands over sound it\n * computed.\n */\nexport class AVAudioPCMBuffer {\n readonly id = newId();\n frameLength = 0;\n\n constructor(\n public format: AVAudioFormat,\n readonly frameCapacity: number,\n ) {\n released?.register(this, this.id, this);\n }\n\n /** Seconds of audio it holds. */\n get duration(): number {\n return this.frameLength / this.format.sampleRate;\n }\n\n /** Fills the buffer with the app's samples, one array per channel (up to its capacity). */\n async write(channels: readonly Float32Array[]): Promise<void> {\n const frames = Math.min(this.frameCapacity, ...channels.map((data) => data.length));\n await perform({\n action: 'writeBuffer',\n buffer: this.id,\n sampleRate: this.format.sampleRate,\n channels: channels.map((data) => (data.length === frames ? data : data.subarray(0, frames))),\n });\n this.frameLength = frames;\n this.format = { sampleRate: this.format.sampleRate, channelCount: channels.length };\n }\n\n /** Lets the host free the audio. */\n close(): void {\n released?.unregister(this);\n void perform({ action: 'release', id: this.id }).catch(() => undefined);\n }\n}\n\n/** A node in an engine's graph. Its properties are kept until it is attached, then sent as they change. */\nexport abstract class AVAudioNode {\n readonly id = newId();\n /** The engine it is attached to, or null. */\n engine: AVAudioEngine | null = null;\n protected readonly values: Record<string, AudioValue> = {};\n /**\n * The command kind it is attached as (null: one an engine makes itself). A\n * package's node subclasses this with its own kind (@swiftbrowser/dsp's\n * `DSPNode` is `program`), which the host makes from what the package\n * registered.\n */\n abstract readonly kind: AudioNodeKind | CustomAudioNodeKind | null;\n\n protected get<T extends AudioValue>(key: string, fallback: T): T {\n return (this.values[key] as T | undefined) ?? fallback;\n }\n\n protected set(key: string, value: AudioValue): void {\n this.values[key] = value;\n this.engine?.fire({ action: 'set', node: this.id, values: { [key]: value } });\n }\n\n /** The properties to attach it with. */\n attachValues(): Record<string, AudioValue> {\n return { ...this.values };\n }\n\n /** How many EQ bands it has (only an EQ has any). */\n get bandCount(): number | undefined {\n return undefined;\n }\n\n /** What its engine must be for a call to reach it. */\n protected attached(): AVAudioEngine {\n if (!this.engine) throw new Error('notAttached: attach the node to an engine first');\n return this.engine;\n }\n\n /** Its output's level now (0 silent … 1 at 0 dB, from -50 dB), as a tap on it would measure; 0 when not attached. */\n async meter(): Promise<number> {\n if (!this.engine) return 0;\n const result = await this.engine.send<{ level?: number }>({ action: 'meter', node: this.id });\n return typeof result?.level === 'number' ? result.level : 0;\n }\n}\n\n/** A node that mixes into what it connects to (`AVAudioMixing`): its volume (0 … 1) and pan (-1 left … 1 right). */\nabstract class MixingNode extends AVAudioNode {\n get volume(): number {\n return this.get('volume', 1);\n }\n\n set volume(value: number) {\n this.set('volume', value);\n }\n\n get pan(): number {\n return this.get('pan', 0);\n }\n\n set pan(value: number) {\n this.set('pan', value);\n }\n}\n\n/** `AVAudioMixerNode`: sums what connects to it; `outputVolume` scales the sum. An engine's `mainMixerNode` is one. */\nexport class AVAudioMixerNode extends MixingNode {\n readonly kind: AudioNodeKind | null = 'mixer';\n\n get outputVolume(): number {\n return this.get('outputVolume', 1);\n }\n\n set outputVolume(value: number) {\n this.set('outputVolume', value);\n }\n}\n\n/** The engine's output to the speakers. */\nexport class AVAudioOutputNode extends AVAudioNode {\n readonly kind = null;\n}\n\n/** The microphone: connect it (to a mixer, an effect) and start the engine, which asks for the microphone then. */\nexport class AVAudioInputNode extends MixingNode {\n readonly kind = null;\n}\n\n/** What a scheduled buffer does (`AVAudioPlayerNodeBufferOptions`). */\nexport interface AVAudioPlayerNodeBufferOptions {\n /** Plays it over and over, until the player stops or another buffer interrupts it. */\n loops?: boolean;\n /** Stops what the player is playing and plays this now. */\n interrupts?: boolean;\n /** As `interrupts`, once a looping buffer that is playing finishes its pass (a pattern swapped on the bar line). */\n interruptsAtLoop?: boolean;\n}\n\n/**\n * `AVAudioPlayerNode`: a timeline of scheduled files, segments and\n * buffers. Each plays after the last, or at its own `AVAudioTime`; `play()`\n * starts the timeline once the engine runs. Each `schedule…` resolves\n * (and calls its completion handler) when its audio has played, or the\n * player stopped.\n */\nexport class AVAudioPlayerNode extends MixingNode {\n readonly kind = 'player' as const;\n private playing = false;\n\n get isPlaying(): boolean {\n return this.playing && this.engine?.isRunning === true;\n }\n\n scheduleFile(file: AVAudioFile, at: AVAudioTime | null = null, completionHandler?: () => void): Promise<void> {\n return this.schedule({ action: 'scheduleFile', node: this.id, file: file.id, ...(at ? { at: at.spec } : {}) }, completionHandler);\n }\n\n scheduleSegment(file: AVAudioFile, startingFrame: number, frameCount: number, at: AVAudioTime | null = null, completionHandler?: () => void): Promise<void> {\n return this.schedule(\n {\n action: 'scheduleFile',\n node: this.id,\n file: file.id,\n start: Math.max(0, Math.floor(startingFrame)),\n frames: Math.max(0, Math.floor(frameCount)),\n ...(at ? { at: at.spec } : {}),\n },\n completionHandler,\n );\n }\n\n scheduleBuffer(\n buffer: AVAudioPCMBuffer,\n at: AVAudioTime | null = null,\n options: AVAudioPlayerNodeBufferOptions = {},\n completionHandler?: () => void,\n ): Promise<void> {\n const command: Extract<AudioEngineCommand, { action: 'scheduleBuffer' }> = {\n action: 'scheduleBuffer',\n node: this.id,\n buffer: buffer.id,\n ...(at ? { at: at.spec } : {}),\n };\n if (options.loops) command.loops = true;\n if (options.interruptsAtLoop) command.interruptsAtLoop = true;\n else if (options.interrupts) command.interrupts = true;\n return this.schedule(command, completionHandler);\n }\n\n private schedule(command: AudioEngineCommand, completionHandler: (() => void) | undefined): Promise<void> {\n const engine = this.attached();\n return engine.send(command).then(() => completionHandler?.());\n }\n\n /** Starts (or resumes) the timeline, now or at `at`; the engine must be running. */\n play(at: AVAudioTime | null = null): void {\n const engine = this.attached();\n this.playing = true;\n engine.fire({ action: 'play', node: this.id, ...(at ? { at: at.spec } : {}) });\n }\n\n /** Holds the timeline where it is; `play()` goes on from there. */\n pause(): void {\n this.playing = false;\n this.engine?.fire({ action: 'pausePlayer', node: this.id });\n }\n\n /** Drops everything scheduled (each completion called) and returns the timeline to 0. */\n stop(): void {\n this.playing = false;\n this.engine?.fire({ action: 'stopPlayer', node: this.id });\n }\n\n /** Where the timeline is now (`playerTime(forNodeTime: lastRenderTime)`), or null before it plays. */\n async playerTime(): Promise<AVAudioTime | null> {\n const time = await this.attached().send<{ sampleTime: number; sampleRate: number } | null>({ action: 'playerTime', node: this.id });\n return time && typeof time.sampleTime === 'number' ? new AVAudioTime(time.sampleTime, time.sampleRate) : null;\n }\n\n /** Called by the engine when it stops: the player stops with it. */\n engineStopped(): void {\n this.playing = false;\n }\n}\n\n/** Options for `loadAudioFiles`: where each file sits on the keyboard, and the notes' envelope. */\nexport interface SamplerLoadOptions {\n /** Each file's root note (MIDI), in the order of the URLs; absent, read from each file's name. */\n rootNotes?: readonly number[];\n /** Seconds from silence to full level (0.002). */\n attack?: number;\n /** Seconds to fade once a note is let go (0.15). */\n release?: number;\n}\n\nconst NOTE_CLASSES: Record<string, number> = { c: 0, d: 2, e: 4, f: 5, g: 7, a: 9, b: 11 };\n\n/**\n * The MIDI note a sample's file name names: `C4` (middle C, 60), `F#2`,\n * `Bb3`, `A-1`, or a bare number `60`; the last one in the name wins. Null\n * when it names none.\n */\nexport function noteInName(url: string): number | null {\n const name = decodeURIComponent(url.split(/[/\\\\]/).pop() ?? '').replace(/\\.[^.]*$/, '');\n const named = [...name.matchAll(/(?:^|[^A-Za-z])([A-Ga-g])([#♯]|b|♭)?(-?\\d)(?!\\d)/g)].pop();\n if (named) {\n const pitchClass = NOTE_CLASSES[named[1]!.toLowerCase()]!;\n const accidental = named[2] === '#' || named[2] === '♯' ? 1 : named[2] ? -1 : 0;\n const note = (Number(named[3]) + 1) * 12 + pitchClass + accidental;\n return note >= 0 && note <= 127 ? note : null;\n }\n const numbered = [...name.matchAll(/(?:^|\\D)(\\d{1,3})(?!\\d)/g)].pop();\n if (numbered) {\n const note = Number(numbered[1]);\n return note <= 127 ? note : null;\n }\n return null;\n}\n\n/**\n * Zones for samples at their root notes: sorted by root, each covering the\n * keys from halfway after the one below to halfway to the one above (the\n * lowest down to 0, the highest up to 127). A second sample on a root\n * already taken is left out.\n */\nexport function samplerZones(samples: readonly { file: number; root: number }[]): SamplerZone[] {\n const sorted = [...samples].sort((a, b) => a.root - b.root).filter((sample, i, all) => i === 0 || sample.root !== all[i - 1]!.root);\n return sorted.map((sample, i) => {\n const below = sorted[i - 1];\n const above = sorted[i + 1];\n return {\n file: sample.file,\n root: sample.root,\n low: below ? Math.floor((below.root + sample.root) / 2) + 1 : 0,\n high: above ? Math.floor((sample.root + above.root) / 2) : 127,\n };\n });\n}\n\n/**\n * `AVAudioUnitSampler`: notes played from samples. `loadAudioFiles(urls)`\n * places each file on the keyboard (see the file comment) and pitches it\n * across its zone; `startNote` and `stopNote` play, with velocity, the\n * sustain pedal and other controllers (`sendController`) and the pitch\n * wheel (`sendPitchBend`). Natively `loadInstrument` and\n * `loadSoundBankInstrument` load an `.aupreset`, a DLS or a SoundFont too.\n */\nexport class AVAudioUnitSampler extends MixingNode {\n readonly kind = 'sampler' as const;\n private files: AVAudioFile[] = [];\n\n /** Decibels, -90 … 12. */\n get overallGain(): number {\n return this.get('overallGain', 0);\n }\n\n set overallGain(value: number) {\n this.set('overallGain', value);\n }\n\n /** Cents, -2400 … 2400. */\n get globalTuning(): number {\n return this.get('globalTuning', 0);\n }\n\n set globalTuning(value: number) {\n this.set('globalTuning', value);\n }\n\n /** -100 left … 100 right. */\n get stereoPan(): number {\n return this.get('stereoPan', 0);\n }\n\n set stereoPan(value: number) {\n this.set('stereoPan', value);\n }\n\n async loadAudioFiles(urls: readonly string[], options: SamplerLoadOptions = {}): Promise<void> {\n const engine = this.attached();\n const roots = urls.map((url, i) => options.rootNotes?.[i] ?? noteInName(url) ?? 60);\n const files = await Promise.all(urls.map((url) => AVAudioFile.open(url)));\n const zones = samplerZones(files.map((file, i) => ({ file: file.id, root: roots[i]! })));\n await engine.send({ action: 'loadZones', node: this.id, zones, attack: options.attack ?? 0.002, release: options.release ?? 0.15 });\n const previous = this.files;\n this.files = files;\n for (const file of previous) file.close();\n }\n\n /** Loads an `.aupreset`, a DLS or a SoundFont's first instrument (natively; a page rejects with `unsupported: …`). */\n async loadInstrument(url: string): Promise<void> {\n await this.attached().send({ action: 'loadInstrument', node: this.id, url });\n }\n\n /** Loads one instrument of a SoundFont or DLS bank by program and bank (natively; a page rejects with `unsupported: …`). */\n async loadSoundBankInstrument(url: string, program: number, bankMSB = 0x79, bankLSB = 0): Promise<void> {\n await this.attached().send({ action: 'loadInstrument', node: this.id, url, program, bankMSB, bankLSB });\n }\n\n startNote(note: number, withVelocity: number, onChannel = 0): void {\n this.attached().fire({ action: 'startNote', node: this.id, note: Math.round(note), velocity: Math.round(withVelocity), channel: onChannel });\n }\n\n stopNote(note: number, onChannel = 0): void {\n this.attached().fire({ action: 'stopNote', node: this.id, note: Math.round(note), channel: onChannel });\n }\n\n /** A MIDI controller: 64 the sustain pedal, 7 volume, 11 expression, 10 pan, 123 all notes off. */\n sendController(controller: number, withValue: number, onChannel = 0): void {\n this.attached().fire({ action: 'controller', node: this.id, controller, value: Math.round(withValue), channel: onChannel });\n }\n\n /** The pitch wheel: 0 … 16383, 8192 centered (±2 semitones). */\n sendPitchBend(pitchbend: number, onChannel = 0): void {\n this.attached().fire({ action: 'pitchBend', node: this.id, value: Math.round(pitchbend), channel: onChannel });\n }\n}\n\n/** An effect node: `bypass` passes its input through untouched. */\nexport abstract class AVAudioUnitEffect extends AVAudioNode {\n get bypass(): boolean {\n return this.get('bypass', false);\n }\n\n set bypass(value: boolean) {\n this.set('bypass', value);\n }\n}\n\nexport type AVAudioUnitReverbPreset =\n | 'smallRoom'\n | 'mediumRoom'\n | 'largeRoom'\n | 'mediumHall'\n | 'largeHall'\n | 'plate'\n | 'mediumChamber'\n | 'largeChamber'\n | 'cathedral'\n | 'largeRoom2'\n | 'mediumHall2'\n | 'mediumHall3'\n | 'largeHall2';\n\n/** `AVAudioUnitReverb`: a room, a hall or a plate (`loadFactoryPreset`), mixed in by `wetDryMix` (percent). */\nexport class AVAudioUnitReverb extends AVAudioUnitEffect {\n readonly kind = 'reverb' as const;\n\n constructor() {\n super();\n this.values['preset'] = 'mediumHall';\n this.values['wetDryMix'] = 100;\n }\n\n get wetDryMix(): number {\n return this.get('wetDryMix', 100);\n }\n\n set wetDryMix(value: number) {\n this.set('wetDryMix', value);\n }\n\n loadFactoryPreset(preset: AVAudioUnitReverbPreset): void {\n this.values['preset'] = preset;\n this.engine?.fire({ action: 'preset', node: this.id, preset });\n }\n}\n\n/** `AVAudioUnitDelay`: an echo `delayTime` seconds later (0 … 2), fed back by `feedback` percent, darkened above `lowPassCutoff` Hz. */\nexport class AVAudioUnitDelay extends AVAudioUnitEffect {\n readonly kind = 'delay' as const;\n\n constructor() {\n super();\n Object.assign(this.values, { delayTime: 1, feedback: 50, lowPassCutoff: 15000, wetDryMix: 100 });\n }\n\n get delayTime(): number {\n return this.get('delayTime', 1);\n }\n\n set delayTime(value: number) {\n this.set('delayTime', value);\n }\n\n get feedback(): number {\n return this.get('feedback', 50);\n }\n\n set feedback(value: number) {\n this.set('feedback', value);\n }\n\n get lowPassCutoff(): number {\n return this.get('lowPassCutoff', 15000);\n }\n\n set lowPassCutoff(value: number) {\n this.set('lowPassCutoff', value);\n }\n\n get wetDryMix(): number {\n return this.get('wetDryMix', 100);\n }\n\n set wetDryMix(value: number) {\n this.set('wetDryMix', value);\n }\n}\n\nexport type AVAudioUnitDistortionPreset =\n | 'drumsBitBrush'\n | 'drumsBufferBeats'\n | 'drumsLoFi'\n | 'multiBrokenSpeaker'\n | 'multiCellphoneConcert'\n | 'multiDecimated1'\n | 'multiDecimated2'\n | 'multiDecimated3'\n | 'multiDecimated4'\n | 'multiDistortedFunk'\n | 'multiDistortedCubed'\n | 'multiDistortedSquared'\n | 'multiEcho1'\n | 'multiEcho2'\n | 'multiEchoTight1'\n | 'multiEchoTight2'\n | 'multiEverythingIsBroken'\n | 'speechAlienChatter'\n | 'speechCosmicInterference'\n | 'speechGoldenPi'\n | 'speechRadioTower'\n | 'speechWaves';\n\n/** `AVAudioUnitDistortion`: driven by `preGain` (dB), mixed in by `wetDryMix`, its character from a factory preset. */\nexport class AVAudioUnitDistortion extends AVAudioUnitEffect {\n readonly kind = 'distortion' as const;\n\n constructor() {\n super();\n Object.assign(this.values, { preGain: -6, wetDryMix: 50 });\n }\n\n get preGain(): number {\n return this.get('preGain', -6);\n }\n\n set preGain(value: number) {\n this.set('preGain', value);\n }\n\n get wetDryMix(): number {\n return this.get('wetDryMix', 50);\n }\n\n set wetDryMix(value: number) {\n this.set('wetDryMix', value);\n }\n\n loadFactoryPreset(preset: AVAudioUnitDistortionPreset): void {\n this.values['preset'] = preset;\n this.engine?.fire({ action: 'preset', node: this.id, preset });\n }\n}\n\nexport type AVAudioUnitEQFilterType =\n | 'parametric'\n | 'lowPass'\n | 'highPass'\n | 'resonantLowPass'\n | 'resonantHighPass'\n | 'bandPass'\n | 'bandStop'\n | 'lowShelf'\n | 'highShelf'\n | 'resonantLowShelf'\n | 'resonantHighShelf';\n\n/** One band of an `AVAudioUnitEQ`. A band is bypassed until the app sets `bypass = false`, as Apple's are. */\nexport class AVAudioUnitEQFilterParameters {\n constructor(\n private readonly eq: AVAudioUnitEQ,\n private readonly index: number,\n ) {}\n\n private key(field: string): string {\n return `bands.${this.index}.${field}`;\n }\n\n get filterType(): AVAudioUnitEQFilterType {\n return this.eq.band(this.key('filterType'), 'parametric') as AVAudioUnitEQFilterType;\n }\n\n set filterType(value: AVAudioUnitEQFilterType) {\n this.eq.setBand(this.key('filterType'), value);\n }\n\n /** Hz. */\n get frequency(): number {\n return this.eq.band(this.key('frequency'), 1000) as number;\n }\n\n set frequency(value: number) {\n this.eq.setBand(this.key('frequency'), value);\n }\n\n /** Octaves (0.05 … 5). */\n get bandwidth(): number {\n return this.eq.band(this.key('bandwidth'), 0.5) as number;\n }\n\n set bandwidth(value: number) {\n this.eq.setBand(this.key('bandwidth'), value);\n }\n\n /** Decibels (-96 … 24). */\n get gain(): number {\n return this.eq.band(this.key('gain'), 0) as number;\n }\n\n set gain(value: number) {\n this.eq.setBand(this.key('gain'), value);\n }\n\n get bypass(): boolean {\n return this.eq.band(this.key('bypass'), true) as boolean;\n }\n\n set bypass(value: boolean) {\n this.eq.setBand(this.key('bypass'), value);\n }\n}\n\n/** `AVAudioUnitEQ(numberOfBands:)`: a filter per band and a `globalGain` (dB). */\nexport class AVAudioUnitEQ extends AVAudioUnitEffect {\n readonly kind = 'eq' as const;\n readonly bands: readonly AVAudioUnitEQFilterParameters[];\n\n constructor(numberOfBands = 1) {\n super();\n const count = Math.max(1, Math.min(32, Math.floor(numberOfBands)));\n this.bands = Array.from({ length: count }, (_, i) => new AVAudioUnitEQFilterParameters(this, i));\n for (let i = 0; i < count; i += 1) {\n Object.assign(this.values, {\n [`bands.${i}.filterType`]: 'parametric',\n [`bands.${i}.frequency`]: 1000,\n [`bands.${i}.bandwidth`]: 0.5,\n [`bands.${i}.gain`]: 0,\n [`bands.${i}.bypass`]: true,\n });\n }\n }\n\n override get bandCount(): number {\n return this.bands.length;\n }\n\n get globalGain(): number {\n return this.get('globalGain', 0);\n }\n\n set globalGain(value: number) {\n this.set('globalGain', value);\n }\n\n /** A band's field (for `AVAudioUnitEQFilterParameters`). */\n band(key: string, fallback: AudioValue): AudioValue {\n return this.values[key] ?? fallback;\n }\n\n setBand(key: string, value: AudioValue): void {\n this.set(key, value);\n }\n}\n\n/** `AVAudioUnitTimePitch`: `pitch` in cents (-2400 … 2400) and `rate` (1/32 … 32) apart (natively; a page passes the sound through). */\nexport class AVAudioUnitTimePitch extends AVAudioUnitEffect {\n readonly kind = 'timePitch' as const;\n\n get pitch(): number {\n return this.get('pitch', 0);\n }\n\n set pitch(value: number) {\n this.set('pitch', value);\n }\n\n get rate(): number {\n return this.get('rate', 1);\n }\n\n set rate(value: number) {\n this.set('rate', value);\n }\n\n get overlap(): number {\n return this.get('overlap', 8);\n }\n\n set overlap(value: number) {\n this.set('overlap', value);\n }\n}\n\n/** Frees an engine on the host once the app's engine object is gone, if the app did not `dispose()` it. */\nconst engines =\n typeof FinalizationRegistry !== 'undefined'\n ? new FinalizationRegistry<number>((id) => void perform({ action: 'destroy', engine: id }).catch(() => undefined))\n : null;\n\n/**\n * `AVAudioEngine`: a graph of nodes from players, samplers and the input\n * through effects and mixers to `mainMixerNode` and `outputNode` (the\n * speakers). `start()` resolves once it runs; a failure of a call that\n * answers nothing (a property, a note) goes to `onError`.\n */\nexport class AVAudioEngine {\n readonly id = newId();\n readonly mainMixerNode = new AVAudioMixerNode();\n readonly outputNode = new AVAudioOutputNode();\n readonly inputNode = new AVAudioInputNode();\n readonly attachedNodes = new Set<AVAudioNode>();\n /** Where failures of calls that answer nothing go (a console warning by default). */\n onError: (error: Error) => void = (error) => console.warn(`AVAudioEngine: ${error.message}`);\n private running = false;\n private disposed = false;\n\n /** Whether this page or app has an audio engine. */\n static get isAvailable(): boolean {\n return hostNow() !== undefined;\n }\n\n constructor() {\n for (const node of [this.mainMixerNode, this.outputNode, this.inputNode]) {\n node.engine = this;\n this.attachedNodes.add(node);\n }\n this.fire({ action: 'create', engine: this.id, mixer: this.mainMixerNode.id, output: this.outputNode.id, input: this.inputNode.id });\n engines?.register(this, this.id, this);\n }\n\n get isRunning(): boolean {\n return this.running;\n }\n\n /** Sends a command and answers its result. */\n send<T = unknown>(command: AudioEngineCommand): Promise<T> {\n if (this.disposed) return Promise.reject(new Error('disposed: the engine was disposed'));\n return perform<T>(command);\n }\n\n /** Sends a command that answers nothing; a failure goes to `onError`. */\n fire(command: AudioEngineCommand): void {\n this.send(command).catch((error: unknown) => this.onError(error instanceof Error ? error : new Error(String(error))));\n }\n\n attach(node: AVAudioNode): void {\n if (node.engine === this) return;\n if (node.engine) throw new Error('attached: the node is attached to another engine');\n if (!node.kind) throw new Error('unsupported: an engine makes its own mixer, output and input');\n node.engine = this;\n this.attachedNodes.add(node);\n const bands = node.bandCount;\n this.fire({ action: 'attach', engine: this.id, node: node.id, kind: node.kind, values: node.attachValues(), ...(bands !== undefined ? { bands } : {}) });\n }\n\n detach(node: AVAudioNode): void {\n if (node.engine !== this || !node.kind) return;\n this.fire({ action: 'detach', engine: this.id, node: node.id });\n if (node instanceof AVAudioPlayerNode) node.engineStopped();\n node.engine = null;\n this.attachedNodes.delete(node);\n }\n\n /**\n * Connects `from`'s output to `to` (an array: to each of them), replacing\n * where it went before; a node that is not a mixer takes one input, so\n * what was connected into it is let go. `format` is accepted for Swift's\n * shape: the host picks one that fits both ends.\n */\n connect(from: AVAudioNode, to: AVAudioNode | readonly AVAudioNode[], format: AVAudioFormat | null = null): void {\n void format;\n const destinations = Array.isArray(to) ? (to as readonly AVAudioNode[]) : [to as AVAudioNode];\n for (const node of [from, ...destinations]) {\n if (node.engine !== this) throw new Error('notAttached: attach both nodes to the engine before connecting them');\n }\n this.fire({ action: 'connect', engine: this.id, from: from.id, to: destinations.map((node) => node.id) });\n }\n\n disconnectNodeOutput(node: AVAudioNode): void {\n this.fire({ action: 'disconnectOutput', engine: this.id, node: node.id });\n }\n\n disconnectNodeInput(node: AVAudioNode): void {\n this.fire({ action: 'disconnectInput', engine: this.id, node: node.id });\n }\n\n prepare(): void {\n this.fire({ action: 'prepare', engine: this.id });\n }\n\n /** Starts rendering; with the input connected, asks for the microphone (rejecting `permission: …` when refused). */\n async start(): Promise<void> {\n await this.send({ action: 'start', engine: this.id });\n this.running = true;\n }\n\n /** Pauses rendering; players hold their place and play on at `start()`. */\n pause(): void {\n this.running = false;\n this.fire({ action: 'pause', engine: this.id });\n }\n\n /** Stops rendering; players stop and drop what they had scheduled. */\n stop(): void {\n this.running = false;\n for (const node of this.attachedNodes) if (node instanceof AVAudioPlayerNode) node.engineStopped();\n this.fire({ action: 'stop', engine: this.id });\n }\n\n /** Silences every node (players stop, notes end) without stopping the engine. */\n reset(): void {\n for (const node of this.attachedNodes) if (node instanceof AVAudioPlayerNode) node.engineStopped();\n this.fire({ action: 'reset', engine: this.id });\n }\n\n /** Stops the engine and frees it on the host; it cannot be used after. */\n dispose(): void {\n if (this.disposed) return;\n engines?.unregister(this);\n void perform({ action: 'destroy', engine: this.id }).catch(() => undefined);\n this.disposed = true;\n this.running = false;\n for (const node of this.attachedNodes) node.engine = null;\n this.attachedNodes.clear();\n }\n}\n\n/**\n * An engine for a view: made once (`build` attaches and connects its\n * nodes), disposed when the view goes. Null where there is no audio engine.\n */\nexport function useAudioEngine(build?: (engine: AVAudioEngine) => void): AVAudioEngine | null {\n const [engine] = useState(() => {\n if (!AVAudioEngine.isAvailable) return null;\n const made = new AVAudioEngine();\n build?.(made);\n return made;\n });\n useEffect(() => () => engine?.dispose(), [engine]);\n return engine;\n}\n","/**\n * Foundation Models for a JavaScript app: Apple Intelligence's on-device\n * language model, shaped as the framework is, so an app talks to it as an iOS\n * app does. Check `SystemLanguageModel.default`'s availability (or\n * `useSystemLanguageModel()`), make a `LanguageModelSession` with\n * instructions, then `respond(to:)` for a whole answer or `streamResponse(to:)`\n * for the answer as it grows; a session keeps the conversation, so each prompt\n * follows the ones before it. Natively FoundationModels answers\n * (packages/native, LanguageModelBridge.swift; iOS 26 with Apple\n * Intelligence on); on a page Chrome's built-in model where the browser has\n * one (Web/src/languageModel.ts), else the model is unavailable, as on an\n * iPhone without Apple Intelligence.\n *\n * What differs from Swift: availability is asked for (a promise, or the hook\n * that keeps it current), a stream yields snapshots `{ content }` of the whole\n * response so far and can be `cancel()`ed (as cancelling the task iterating\n * it), failures are `GenerationError`s whose `kind` names the case, and a\n * session the app is done with is `close()`d. Tools are objects with a JSON\n * schema for their arguments and a `call` the model's calls run (natively;\n * a page's model answers without them). Guided generation (`@Generable`) is\n * not here.\n */\n\nimport type {\n GenerationOptionsSpec,\n LanguageModelAvailability,\n LanguageModelChoice,\n LanguageModelDownload,\n LanguageModelCommand,\n LanguageModelHost,\n LanguageModelUnavailableReason,\n} from '@swiftbrowser/web/src/languageModel';\nimport { browserEnvironment } from '@swiftbrowser/web/src/hostRequests';\nimport { useEffect, useState } from 'react';\n\nexport type { LanguageModelAvailability, LanguageModelChoice, LanguageModelDownload, LanguageModelHost, LanguageModelUnavailableReason };\n\n/** One id space for every session and stream. */\nlet nextId = 1;\n\nconst hostNow = (): LanguageModelHost | undefined => browserEnvironment.languageModel;\n\nfunction perform<T>(command: LanguageModelCommand): Promise<T> {\n const host = hostNow();\n if (!host) return Promise.reject(new GenerationError('assetsUnavailable', 'This page or app has no language model.'));\n return (host.perform(command) as Promise<T>).catch((error: unknown) => {\n throw GenerationError.from(error);\n });\n}\n\n// MARK: Errors\n\n/** `LanguageModelSession.GenerationError`'s cases. */\nexport type GenerationErrorKind =\n | 'assetsUnavailable'\n | 'exceededContextWindowSize'\n | 'guardrailViolation'\n | 'unsupportedLanguageOrLocale'\n | 'concurrentRequests'\n | 'rateLimited'\n | 'refusal'\n | 'unknown';\n\nconst KINDS: Record<string, GenerationErrorKind> = {\n unavailable: 'assetsUnavailable',\n context: 'exceededContextWindowSize',\n guardrail: 'guardrailViolation',\n language: 'unsupportedLanguageOrLocale',\n concurrent: 'concurrentRequests',\n rateLimited: 'rateLimited',\n refusal: 'refusal',\n};\n\n/** A failed response, as `LanguageModelSession.GenerationError`. */\nexport class GenerationError extends Error {\n constructor(\n readonly kind: GenerationErrorKind,\n message: string,\n ) {\n super(message);\n this.name = 'GenerationError';\n }\n\n /** The error a host's tagged message (`context: …`) stands for. */\n static from(error: unknown): GenerationError {\n if (error instanceof GenerationError) return error;\n const message = error instanceof Error ? error.message : String(error);\n const match = /^(\\w+): ?([\\s\\S]*)$/.exec(message);\n const kind = match ? KINDS[match[1]!] : undefined;\n return kind ? new GenerationError(kind, match![2]!) : new GenerationError('unknown', message);\n }\n}\n\n// MARK: The model\n\nexport type { GenerationOptionsSpec as GenerationOptions };\n\n/** The on-device model: `SystemLanguageModel.default`. */\nexport class SystemLanguageModel {\n static readonly default = new SystemLanguageModel();\n\n private constructor() {}\n\n /** Views showing the availability, asked again when a download starts or the model goes. */\n private readonly listeners = new Set<() => void>();\n\n /** Whether the model can answer now, or why not. */\n async availability(): Promise<LanguageModelAvailability> {\n if (!hostNow()) return { status: 'unavailable', reason: 'deviceNotEligible' };\n try {\n return await perform<LanguageModelAvailability>({ action: 'availability' });\n } catch {\n return { status: 'unavailable', reason: 'deviceNotEligible' };\n }\n }\n\n async isAvailable(): Promise<boolean> {\n return (await this.availability()).status === 'available';\n }\n\n /**\n * Starts fetching a model the app fetches itself (availability's\n * `download`), which the viewer asked for: show its size first. Not part\n * of FoundationModels, whose model the system manages.\n */\n async download(): Promise<void> {\n await perform({ action: 'download' });\n this.changed();\n }\n\n /**\n * Makes the model with this `id` (one of availability's `models`) the one\n * that answers, from the next session on; remembered across launches.\n */\n async selectModel(id: string): Promise<void> {\n await perform({ action: 'select', id });\n this.changed();\n }\n\n /** Stops such a download, or removes the model from the device to free its space. */\n async deleteDownload(): Promise<void> {\n await perform({ action: 'deleteDownload' });\n this.changed();\n }\n\n /** @internal `useSystemLanguageModel` hears downloads start and models go. */\n listen(listener: () => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n private changed(): void {\n for (const listener of this.listeners) listener();\n }\n}\n\n/**\n * The model's availability, kept current: null until known, then asked again\n * while the model is not ready yet (it is downloading), every few seconds or,\n * while a download reports its `progress`, every second, and whenever\n * `download()` or `deleteDownload()` changes it, as a view reading\n * `SystemLanguageModel.default.availability` would update.\n */\nexport function useSystemLanguageModel(model: SystemLanguageModel = SystemLanguageModel.default): LanguageModelAvailability | null {\n const [availability, setAvailability] = useState<LanguageModelAvailability | null>(null);\n useEffect(() => {\n let live = true;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const check = (): void => {\n if (timer !== undefined) clearTimeout(timer);\n timer = undefined;\n void model.availability().then((next) => {\n if (!live) return;\n setAvailability((current) => (JSON.stringify(current) === JSON.stringify(next) ? current : next));\n if (timer !== undefined) return;\n if (next.download?.progress !== undefined) timer = setTimeout(check, 1000);\n else if (next.status === 'unavailable' && next.reason === 'modelNotReady' && !next.download) timer = setTimeout(check, 5000);\n });\n };\n check();\n const stop = model.listen(check);\n return () => {\n live = false;\n stop();\n if (timer !== undefined) clearTimeout(timer);\n };\n }, [model]);\n return availability;\n}\n\n// MARK: Sessions\n\n/** A whole response: `Response<String>`. */\nexport interface Response {\n content: string;\n}\n\n/**\n * A response as it grows (`ResponseStream`): iterate it for snapshots of the\n * whole response so far, or `collect()` the last. The request starts when the\n * stream is made; `cancel()` (or leaving a `for await` early) ends it.\n */\nexport class ResponseStream implements AsyncIterable<Response> {\n private readonly id = nextId++;\n private readonly started: Promise<unknown>;\n private finished = false;\n private last: Response = { content: '' };\n\n /** @internal Made by `LanguageModelSession.streamResponse`. */\n constructor(\n session: LanguageModelSession,\n opened: Promise<unknown>,\n prompt: string,\n options: GenerationOptionsSpec | undefined,\n private readonly ended: () => void,\n ) {\n this.started = opened.then(() =>\n perform({ action: 'stream', session: session.id, stream: this.id, prompt, ...(options ? { options } : {}) }),\n );\n this.started.catch(() => this.end());\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<Response> {\n try {\n await this.started;\n while (!this.finished) {\n const { content, done } = await perform<{ content: string; done: boolean }>({ action: 'next', stream: this.id });\n if (done) this.end();\n if (content !== this.last.content) {\n this.last = { content };\n yield this.last;\n }\n }\n } catch (error) {\n this.end();\n throw error;\n } finally {\n // Left early (`break`, `return`): the model stops too.\n this.cancel();\n }\n }\n\n /** The whole response, once it has ended. */\n async collect(): Promise<Response> {\n for await (const snapshot of this) this.last = snapshot;\n return this.last;\n }\n\n /** Stops the response; the iteration ends with what came so far. */\n cancel(): void {\n if (this.finished) return;\n this.end();\n void this.started.then(() => perform({ action: 'cancel', stream: this.id })).catch(() => {});\n }\n\n private end(): void {\n if (this.finished) return;\n this.finished = true;\n this.ended();\n }\n}\n\n/**\n * A function the model may call while it answers (`Tool`): what it is\n * called and does, its arguments as a JSON schema (an object of properties:\n * strings, enums of strings, numbers, integers, booleans, arrays), and `call`,\n * whose answer the model reads (a string, or a value as JSON).\n */\nexport interface Tool<Arguments = Record<string, unknown>> {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n call(args: Arguments): unknown;\n}\n\nexport interface LanguageModelSessionOptions {\n model?: SystemLanguageModel;\n /** What the model is, does and avoids, followed over every prompt. */\n instructions?: string;\n /** Functions the model may call while it answers. */\n tools?: readonly Tool<never>[];\n}\n\n/**\n * A conversation with the model (`LanguageModelSession`): each prompt sees the\n * ones before it and their responses. One request at a time; another while it\n * responds fails with `concurrentRequests`.\n */\nexport class LanguageModelSession {\n readonly id = nextId++;\n readonly instructions: string | undefined;\n readonly tools: readonly Tool<never>[];\n private readonly opened: Promise<unknown>;\n private responses = 0;\n private closed = false;\n\n constructor(options: LanguageModelSessionOptions = {}) {\n this.instructions = options.instructions;\n this.tools = options.tools ?? [];\n const tools = this.tools.map(({ name, description, parameters }) => ({ name, description, parameters }));\n this.opened = perform({\n action: 'open',\n session: this.id,\n ...(options.instructions ? { instructions: options.instructions } : {}),\n ...(tools.length > 0 ? { tools } : {}),\n });\n this.opened.catch(() => {});\n if (tools.length > 0) void this.opened.then(() => this.serveTools()).catch(() => {});\n }\n\n /** Runs the model's tool calls as they come, until the session closes. */\n private async serveTools(): Promise<void> {\n while (!this.closed) {\n const request = await perform<{ call?: number; name?: string; arguments?: unknown; closed?: boolean }>({ action: 'toolCall', session: this.id });\n if (!request || request.closed || request.call === undefined) return;\n const tool = this.tools.find((candidate) => candidate.name === request.name);\n let answer: { output: string } | { error: string };\n try {\n if (!tool) throw new Error(`no tool named ${String(request.name)}`);\n const output = await (tool.call as (args: unknown) => unknown)(request.arguments ?? {});\n answer = { output: typeof output === 'string' ? output : JSON.stringify(output ?? null) };\n } catch (error) {\n answer = { error: error instanceof Error ? error.message : String(error) };\n }\n await perform({ action: 'toolResult', session: this.id, call: request.call, ...answer });\n }\n }\n\n /** Whether a response is under way. */\n get isResponding(): boolean {\n return this.responses > 0;\n }\n\n /** Loads the model ahead of the first prompt, so it answers sooner. */\n prewarm(): void {\n void this.opened.then(() => perform({ action: 'prewarm', session: this.id })).catch(() => {});\n }\n\n async respond(to: string, options?: GenerationOptionsSpec): Promise<Response> {\n this.responses += 1;\n try {\n await this.opened;\n return await perform<Response>({ action: 'respond', session: this.id, prompt: to, ...(options ? { options } : {}) });\n } finally {\n this.responses -= 1;\n }\n }\n\n streamResponse(to: string, options?: GenerationOptionsSpec): ResponseStream {\n this.responses += 1;\n return new ResponseStream(this, this.opened, to, options, () => {\n this.responses -= 1;\n });\n }\n\n /** Ends the session: the host lets its conversation go. */\n close(): void {\n if (this.closed) return;\n this.closed = true;\n void this.opened.then(() => perform({ action: 'close', session: this.id })).catch(() => {});\n }\n}\n","/**\n * `useWakeLock(active)`: the screen stays awake while `active` (a recording\n * under way, a recipe being followed), through the Screen Wake Lock API,\n * which a page has from the browser and a native app from the runtime\n * (`navigator.wakeLock` over the host's idle timer). A browser releases the\n * lock when the document hides; it is taken again when the document shows.\n * Returns whether a lock is held now; nothing happens, and false is\n * returned, where there is no `navigator.wakeLock`.\n */\n\nimport { useEffect, useState } from 'react';\n\ninterface WakeLockSentinelLike {\n released: boolean;\n release(): Promise<void>;\n addEventListener(type: 'release', listener: () => void): void;\n}\n\ninterface WakeLockLike {\n request(type: 'screen'): Promise<WakeLockSentinelLike>;\n}\n\n/** The API, from the page's or the runtime's `navigator`. */\nfunction wakeLockAPI(): WakeLockLike | null {\n const nav = (globalThis as { navigator?: { wakeLock?: WakeLockLike } }).navigator;\n return nav?.wakeLock ?? null;\n}\n\nexport function useWakeLock(active = true): boolean {\n const [held, setHeld] = useState(false);\n useEffect(() => {\n const api = wakeLockAPI();\n if (!active || !api) {\n setHeld(false);\n return;\n }\n let sentinel: WakeLockSentinelLike | null = null;\n let stopped = false;\n const acquire = (): void => {\n if (stopped || (sentinel && !sentinel.released)) return;\n api.request('screen').then(\n (next) => {\n if (stopped) {\n void next.release();\n return;\n }\n sentinel = next;\n setHeld(true);\n // The browser lets go when the document hides; `visibilitychange` below takes it back.\n next.addEventListener('release', () => {\n if (sentinel === next) setHeld(false);\n });\n },\n () => setHeld(false),\n );\n };\n const onVisible = (): void => {\n if (typeof document === 'undefined' || document.visibilityState === 'visible') acquire();\n };\n acquire();\n const doc = typeof document !== 'undefined' ? document : null;\n doc?.addEventListener('visibilitychange', onVisible);\n return () => {\n stopped = true;\n doc?.removeEventListener('visibilitychange', onVisible);\n if (sentinel && !sentinel.released) void sentinel.release();\n sentinel = null;\n setHeld(false);\n };\n }, [active]);\n return held;\n}\n","import type { ButtonRole, ButtonStyle, PickerStyle, SliderLabel, TextFieldStyle, ToggleStyle } from '@swiftbrowser/web/src/protocol';\nimport { Fragment, type ReactElement, type ReactNode } from 'react';\nimport { readBinding, type BindingValue } from '../binding';\nimport { useViewEnvironment, withEnvironment, type ControlSize } from '../environment';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, styled, takeModifier, toolbarPlacement, type ToolbarItemPlacementName, type ViewModifiers } from '../modifiers';\nimport { AttributedText, fromProtocolRuns, protocolRuns, type TextSelection } from '../attributedText';\nimport { flattenChildren } from './stacks';\nimport { useKeyboardShortcut } from '../pointer';\nimport { Image, Text, type TextProps } from './text';\n\n// ---------------------------------------------------------------------------\n// Button\n// ---------------------------------------------------------------------------\n\nexport interface ButtonProps extends ViewModifiers {\n title?: string;\n role?: 'destructive' | 'cancel';\n action?: () => void;\n /** The label, when there is no `title`. */\n children?: ReactNode;\n /**\n * What `EditButton` sets: the edit mode the button shows and flips. The\n * `button` op carries it so a native renderer can draw the platform's edit\n * button (iOS's checkmark while editing); the web renderer draws the title.\n */\n editMode?: 'active' | 'inactive';\n}\n\nexport function Button(props: ButtonProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const environment = useViewEnvironment();\n const ownStyle = takeModifier(modifiers, 'buttonStyle');\n const ownSize = takeModifier(modifiers, 'controlSize');\n const style: ButtonStyle = ownStyle ?? environment.buttonStyle ?? 'automatic';\n const controlSize: ControlSize | undefined = ownSize ?? environment.controlSize;\n const buttonProps: Record<string, unknown> = { role: (own.role ?? null) as ButtonRole, style };\n if (controlSize !== undefined && controlSize !== 'regular') buttonProps['controlSize'] = controlSize;\n if (own.editMode !== undefined) buttonProps['editMode'] = own.editMode;\n const label = own.title !== undefined ? <Text>{own.title}</Text> : own.children;\n const tap = (): void => {\n own.action?.();\n environment.dismissAlert?.();\n };\n const shortcut = takeModifier(modifiers, 'keyboardShortcut');\n useKeyboardShortcut(typeof shortcut === 'string' ? { key: shortcut } : shortcut, () => {\n if (!buttonDisabled(modifiers)) tap();\n });\n return applyModifiers(sb('button', buttonProps, { tap }, label), modifiers);\n}\n\n// ---------------------------------------------------------------------------\n// Toggle\n// ---------------------------------------------------------------------------\n\nexport interface ToggleProps extends ViewModifiers {\n isOn: BindingValue<boolean>;\n onChange?: (isOn: boolean) => void;\n title?: string;\n children?: ReactNode;\n}\n\nexport function Toggle(props: ToggleProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const environment = useViewEnvironment();\n const style: ToggleStyle = takeModifier(modifiers, 'toggleStyle') ?? environment.toggleStyle ?? 'automatic';\n const [isOn, setOn] = readBinding(own.isOn, own.onChange);\n const label = own.title !== undefined ? <Text>{own.title}</Text> : own.children;\n const toggleProps: Record<string, unknown> = { isOn };\n if (style !== 'automatic') toggleProps['style'] = style;\n return applyModifiers(sb('toggle', toggleProps, { toggle: (event) => setOn(event.value) }, label), modifiers);\n}\n\n// ---------------------------------------------------------------------------\n// Picker\n// ---------------------------------------------------------------------------\n\nexport interface PickerOption<T> {\n label: string;\n tag: T;\n}\n\nexport interface PickerProps<T> extends ViewModifiers {\n label: string;\n selection: BindingValue<T>;\n onChange?: (value: T) => void;\n /** The options, or `<Text tag={…}>` children (a `Text` without a tag is tagged with its string). */\n options?: readonly (T | PickerOption<T>)[];\n children?: ReactNode;\n}\n\nexport function Picker<T>(props: PickerProps<T>): ReactNode {\n const { own, modifiers } = splitProps(props);\n const environment = useViewEnvironment();\n const ownStyle = takeModifier(modifiers, 'pickerStyle');\n const style: PickerStyle = ownStyle ?? environment.pickerStyle ?? 'menu';\n const [selection, setSelection] = readBinding(own.selection, own.onChange);\n const options = pickerOptions<T>(own.options, own.children);\n const selected = Math.max(\n 0,\n options.findIndex((option) => Object.is(option.tag, selection)),\n );\n return applyModifiers(\n sb(\n 'picker',\n { style, label: own.label, options: options.map((option) => option.label), selected },\n { select: (event) => options[event.value] && setSelection(options[event.value]!.tag) },\n ),\n modifiers,\n );\n}\n\nfunction pickerOptions<T>(options: readonly (T | PickerOption<T>)[] | undefined, children: ReactNode): PickerOption<T>[] {\n if (options) {\n return options.map((option) =>\n typeof option === 'object' && option !== null && 'label' in option && 'tag' in option\n ? (option as PickerOption<T>)\n : { label: String(option), tag: option as T },\n );\n }\n return flattenChildren(children).map((element) => {\n const label = plainText(element);\n const tag = (element.props as { tag?: T }).tag;\n return { label, tag: (tag !== undefined ? tag : label) as T };\n });\n}\n\n/** The string of a `<Text>` element (other elements read as their title, else \"\"). */\nexport function plainText(element: ReactElement): string {\n const props = element.props as TextProps & { title?: unknown };\n if (element.type === Text) return collectText(props.children);\n if (typeof props.title === 'string') return props.title;\n return '';\n}\n\nfunction collectText(node: ReactNode): string {\n if (node === null || node === undefined || typeof node === 'boolean') return '';\n if (typeof node === 'string' || typeof node === 'number') return String(node);\n if (Array.isArray(node)) return node.map(collectText).join('');\n if (typeof node === 'object' && 'props' in node) {\n const element = node as ReactElement<{ children?: ReactNode }>;\n if (element.type === Fragment || element.type === Text) return collectText(element.props.children);\n }\n return '';\n}\n\n// ---------------------------------------------------------------------------\n// Slider, Stepper\n// ---------------------------------------------------------------------------\n\nexport interface SliderProps extends ViewModifiers {\n value: BindingValue<number>;\n onChange?: (value: number) => void;\n /** `onEditingChanged`: true as a drag begins, false as it ends (a scrubber stops following the position while the thumb is held). */\n onEditingChanged?: (editing: boolean) => void;\n /** `in: 0...1` */\n range?: readonly [number, number];\n step?: number;\n /** What the slider is for: VoiceOver reads it; iOS (and so the page) does not draw it. */\n label?: ReactNode;\n /** Drawn at the track's leading end (an icon, a value). */\n minimumValueLabel?: ReactNode;\n maximumValueLabel?: ReactNode;\n}\n\nexport function Slider(props: SliderProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const environment = useViewEnvironment();\n const [value, setValue] = readBinding(own.value, own.onChange);\n const [min, max] = own.range ?? [0, 1];\n const labels: SliderLabel[] = [];\n const children: ReactNode[] = [];\n if (own.label !== undefined && !environment.labelsHidden) {\n labels.push('label');\n children.push(<Fragment key=\"label\">{own.label}</Fragment>);\n }\n if (own.minimumValueLabel !== undefined || own.maximumValueLabel !== undefined) {\n labels.push('min', 'max');\n children.push(<Fragment key=\"min\">{own.minimumValueLabel}</Fragment>, <Fragment key=\"max\">{own.maximumValueLabel}</Fragment>);\n }\n return applyModifiers(\n sb(\n 'slider',\n { value, min, max, step: own.step ?? null, labels },\n {\n slide: (event) => {\n if (event.editing === true) own.onEditingChanged?.(true);\n setValue(event.value);\n if (event.editing === false) own.onEditingChanged?.(false);\n },\n },\n children.length ? children : undefined,\n ),\n modifiers,\n );\n}\n\nexport interface StepperProps extends ViewModifiers {\n value: BindingValue<number>;\n onChange?: (value: number) => void;\n /** `in: 1...10` */\n range?: readonly [number, number];\n step?: number;\n title?: string;\n children?: ReactNode;\n}\n\nexport function Stepper(props: StepperProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const [value, setValue] = readBinding(own.value, own.onChange);\n const step = own.step ?? 1;\n const [min, max] = own.range ?? [-Infinity, Infinity];\n const label = own.title !== undefined ? <Text>{own.title}</Text> : own.children;\n return applyModifiers(\n sb(\n 'stepper',\n { canIncrement: value < max, canDecrement: value > min },\n { step: (event) => setValue(Math.min(max, Math.max(min, value + Math.sign(event.value) * step))) },\n label,\n ),\n modifiers,\n );\n}\n\n// ---------------------------------------------------------------------------\n// Text fields\n// ---------------------------------------------------------------------------\n\nexport interface TextFieldBaseProps extends ViewModifiers {\n /** The placeholder (SwiftUI's title). */\n placeholder?: string;\n text: BindingValue<string>;\n onChange?: (text: string) => void;\n onSubmit?: () => void;\n /**\n * Backspace with nothing selected and the caret at the start of the text\n * (an empty field included): there is nothing for the key to delete, so\n * the app hears it, to merge the field into what comes before it, say.\n */\n onDeleteBackward?: () => void;\n textFieldStyle?: TextFieldStyle;\n secure?: boolean;\n axis?: 'vertical';\n}\n\nexport type TextFieldProps<F extends FocusValue = FocusValue> = TextFieldBaseProps & FocusProps<F>;\n\n/**\n * `TextField(\"Name\", text:)`. Overloads for the two focus bindings\n * (`FocusProps`) rather than their union alone, so an inline binding's\n * setter still infers its type.\n */\nexport function TextField(props: TextFieldBaseProps & BoundFocusProps): ReactNode;\nexport function TextField<F extends FocusValue>(props: TextFieldBaseProps & SharedFocusProps<F>): ReactNode;\nexport function TextField(props: TextFieldProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const environment = useViewEnvironment();\n const ownSubmitLabel = takeModifier(modifiers, 'submitLabel');\n // The text input hints written on the field itself, over the environment's.\n const keyboardType = takeModifier(modifiers, 'keyboardType');\n const textContentType = takeModifier(modifiers, 'textContentType');\n const autocapitalization = takeModifier(modifiers, 'textInputAutocapitalization');\n const autocorrectionDisabled = takeModifier(modifiers, 'autocorrectionDisabled');\n const hints = {\n ...environment.textInputHints,\n ...(keyboardType !== undefined ? { keyboard: keyboardType } : {}),\n ...(textContentType !== undefined ? { contentType: textContentType ?? undefined } : {}),\n ...(autocapitalization !== undefined ? { autocapitalization: autocapitalization ?? undefined } : {}),\n ...(autocorrectionDisabled !== undefined ? { autocorrectionDisabled } : {}),\n };\n const [text, setText] = readBinding(own.text, own.onChange);\n const fieldProps: Record<string, unknown> = {\n text,\n placeholder: own.placeholder ?? '',\n style: own.textFieldStyle ?? 'plain',\n secure: own.secure ?? false,\n };\n if (own.onSubmit) fieldProps['submit'] = true;\n if (own.onDeleteBackward) fieldProps['deleteBackward'] = true;\n if (own.axis) fieldProps['axis'] = own.axis;\n const submitLabel = ownSubmitLabel ?? environment.submitLabel;\n if (submitLabel) fieldProps['submitLabel'] = submitLabel;\n if (hints.keyboard && hints.keyboard !== 'default') fieldProps['keyboard'] = hints.keyboard;\n if (hints.contentType) fieldProps['contentType'] = hints.contentType;\n if (hints.autocapitalization) fieldProps['autocapitalization'] = hints.autocapitalization;\n if (hints.autocorrectionDisabled) fieldProps['autocorrectionDisabled'] = true;\n const focus = focusBinding(own);\n if (focus) fieldProps['focused'] = focus[0];\n return applyModifiers(\n sb('textfield', fieldProps, {\n text: (event) => setText(event.value),\n submit: () => own.onSubmit?.(),\n deletebackward: () => own.onDeleteBackward?.(),\n focus: (event) => focus?.[1](event.value),\n }),\n modifiers,\n );\n}\n\nexport function SecureField(props: Omit<TextFieldBaseProps & BoundFocusProps, 'secure'>): ReactNode;\nexport function SecureField<F extends FocusValue>(props: Omit<TextFieldBaseProps & SharedFocusProps<F>, 'secure'>): ReactNode;\nexport function SecureField(props: Omit<TextFieldProps, 'secure'>): ReactNode {\n // The union is one of the overloads' props; the cast picks one for the spread.\n return <TextField {...(props as TextFieldBaseProps & BoundFocusProps)} secure />;\n}\n\n// ---------------------------------------------------------------------------\n// Focus\n// ---------------------------------------------------------------------------\n\n/** `@FocusState var field: Field?`: what stands for a field among those sharing one focus binding. */\nexport type FocusValue = string | number;\n\n/**\n * `.focused($isFocused)`: the field takes the focus while true, and sets it\n * as the viewer focuses or leaves it. A value the app sets from `onSubmit`\n * (true again) wins over the keyboard's dismissal, and a field that takes\n * the focus is scrolled into view.\n */\nexport interface BoundFocusProps {\n focused?: BindingValue<boolean>;\n focusedValue?: undefined;\n}\n\n/**\n * `.focused($field, equals: value)`: the binding holds the focused field's\n * value (null for none) and is shared by the fields, each naming its own\n * with `focusedValue`. A field taking the focus sets its value; one losing\n * it clears the value only while it is still its own, so a handler for\n * `onSubmit` that moved the focus to another field (or set this one's\n * again) wins over the keyboard's dismissal, and the field it names is\n * scrolled into view.\n */\nexport interface SharedFocusProps<F extends FocusValue> {\n focused: BindingValue<F | null>;\n focusedValue: F;\n}\n\nexport type FocusProps<F extends FocusValue = FocusValue> = BoundFocusProps | SharedFocusProps<F>;\n\n/**\n * A field's own focus over its `FocusProps` (read loosely: `splitProps`\n * flattens the union): whether it has the focus, and the setter for a change\n * the renderer reports; null when unbound.\n */\nexport function focusBinding<F extends FocusValue>(props: { focused?: BindingValue<boolean> | BindingValue<F | null> | undefined; focusedValue?: F | undefined }): [boolean, (on: boolean) => void] | null {\n if (props.focused === undefined) return null;\n if (props.focusedValue === undefined) return readBinding(props.focused as BindingValue<boolean>);\n const value = props.focusedValue;\n const [current, set] = readBinding(props.focused as BindingValue<F | null>);\n return [\n current === value,\n (on) => {\n if (on) set(value);\n else if (current === value) set(null);\n },\n ];\n}\n\n// ---------------------------------------------------------------------------\n// ProgressView\n// ---------------------------------------------------------------------------\n\nexport interface ProgressViewProps extends ViewModifiers {\n /** Determinate progress (`value / total`); absent: the spinning indicator. */\n value?: number;\n total?: number;\n label?: ReactNode;\n currentValueLabel?: ReactNode;\n /** The label, as children. */\n children?: ReactNode;\n}\n\nexport function ProgressView(props: ProgressViewProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n if (own.value === undefined) {\n return applyModifiers(\n styled({ foreground: { hierarchical: 2 } }, styled({ font: { size: 20 } }, <Image systemName=\"progress.indicator\" />)),\n modifiers,\n );\n }\n const label = own.label ?? own.children;\n const children: ReactNode[] = [];\n if (label !== undefined && label !== null) children.push(<Fragment key=\"label\">{label}</Fragment>);\n if (own.currentValueLabel !== undefined && own.currentValueLabel !== null) {\n children.push(<Fragment key=\"current\">{styled({ foreground: { hierarchical: 2 } }, own.currentValueLabel)}</Fragment>);\n }\n return applyModifiers(\n sb(\n 'gauge',\n { value: own.value / (own.total ?? 1), style: 'progress', hasLabel: true, hasCurrentValueLabel: true },\n undefined,\n children.length ? children : undefined,\n ),\n modifiers,\n );\n}\n\n// ---------------------------------------------------------------------------\n// Toolbar\n// ---------------------------------------------------------------------------\n\nexport interface ToolbarItemProps {\n placement?: ToolbarItemPlacementName;\n /** `.sharedBackgroundVisibility(_:)`: `hidden` draws the item without the bar's shared glass. */\n sharedBackgroundVisibility?: 'automatic' | 'visible' | 'hidden';\n children?: ReactNode;\n}\n\n/**\n * `ToolbarItem(placement:) { }`, inside a `toolbar` modifier. A `Label` in\n * it shows its icon alone, its title the icon's accessible name, as iOS\n * draws a bar's labels (and as the Swift shim's bars do); a `Label` given\n * `labelStyle=\"titleAndIcon\"` shows both, and a `Menu`'s items keep theirs,\n * as do `secondaryAction` items, which an iPhone lists in its More menu.\n */\nexport function ToolbarItem(props: ToolbarItemProps): ReactNode {\n const hidden = props.sharedBackgroundVisibility === 'hidden';\n const placement = toolbarPlacement(props.placement);\n // `.secondaryAction` items are the More button's menu rows on an iPhone, a Label's title beside its icon there:\n // they keep their Labels whole (the native renderer's SwiftUI draws a Label in a bar as its icon by itself).\n const items = placement === 'secondary' ? props.children : withEnvironment({ labelStyle: 'iconOnly' }, props.children);\n return sb('toolbar', hidden ? { placement, sharedBackground: 'hidden' } : { placement }, undefined, items);\n}\n\nexport const ToolbarItemGroup = ToolbarItem;\n\nexport interface ToolbarSpacerProps {\n /**\n * `flexible` (the default) shares the room the groups leave, pushing them\n * apart; `fixed` is a standard gap (8 in a bottom bar, 12 in the\n * navigation bar) and keeps the row centered.\n */\n sizing?: 'flexible' | 'fixed';\n placement?: ToolbarItemPlacementName;\n}\n\n/**\n * `ToolbarSpacer(_:placement:)` (iOS 26), inside a `toolbar` modifier: ends\n * the glass capsule of the items before it, so the items after it float on\n * a capsule of their own, in the navigation bar as in a bottom bar.\n */\nexport function ToolbarSpacer(props: ToolbarSpacerProps): ReactNode {\n return sb('toolbar', { placement: toolbarPlacement(props.placement), spacer: props.sizing ?? 'flexible' });\n}\n\n// ---------------------------------------------------------------------------\n// DatePicker, TextEditor\n// ---------------------------------------------------------------------------\n\nexport type DatePickerComponents = 'date' | 'hourAndMinute' | 'dateAndTime';\n\nexport interface DatePickerProps extends ViewModifiers {\n label?: string;\n selection: BindingValue<Date>;\n onChange?: (date: Date) => void;\n /** `displayedComponents:`; `date` by default. */\n displayedComponents?: DatePickerComponents;\n /** `in:` bounds. */\n range?: readonly [Date | null, Date | null];\n /** The IANA time zone the date and time are shown and edited in (`.environment(\\\\.timeZone)`); the viewer's when absent. */\n timeZone?: string;\n}\n\n/** `DatePicker(\"Date\", selection:)`: the compact style, with the browser's native pickers. */\nexport function DatePicker(props: DatePickerProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const environment = useViewEnvironment();\n const [date, setDate] = readBinding(own.selection, own.onChange);\n const labelsHidden = takeModifier(modifiers, 'labelsHidden') ?? environment.labelsHidden ?? false;\n const seconds = (value: Date | null | undefined): number | null => (value ? Math.floor(value.getTime() / 1000) : null);\n const pickerProps: Record<string, unknown> = {\n seconds: seconds(date) ?? 0,\n components: own.displayedComponents ?? 'date',\n min: seconds(own.range?.[0]),\n max: seconds(own.range?.[1]),\n };\n if (labelsHidden) pickerProps['labelsHidden'] = true;\n if (own.timeZone) pickerProps['timeZone'] = own.timeZone;\n const label = labelsHidden || own.label === undefined ? undefined : <Text>{own.label}</Text>;\n return applyModifiers(sb('datepicker', pickerProps, { date: (event) => setDate(new Date(event.value * 1000)) }, label), modifiers);\n}\n\ninterface TextEditorBaseProps extends ViewModifiers {\n /**\n * `TextEditor(text:selection:)`, on a plain editor or a rich one: the\n * editor writes the selection as the viewer moves the caret or selects\n * (UTF-16 offsets into the text), and one the app sets moves the caret\n * (when the app focuses the editor, if it is not focused).\n */\n selection?: BindingValue<TextSelection>;\n /** As a `TextField`'s: Backspace with the caret at the start of the text and nothing selected. */\n onDeleteBackward?: () => void;\n}\n\nexport interface PlainTextEditorProps extends TextEditorBaseProps {\n text: BindingValue<string>;\n onChange?: (text: string) => void;\n}\n\n/** A rich editor: its text is `AttributedText`, drawn with each run's attributes. */\nexport interface AttributedTextEditorProps extends TextEditorBaseProps {\n text: BindingValue<AttributedText>;\n onChange?: (text: AttributedText) => void;\n}\n\n/** The editor's props with a focus binding as a `TextField`'s (`FocusProps`). */\nexport type TextEditorProps<F extends FocusValue = FocusValue> = (PlainTextEditorProps | AttributedTextEditorProps) & FocusProps<F>;\n\n/**\n * `TextEditor(text:)`: a multi-line field filling its proposal (as tall as\n * its lines under `.scrollDisabled(true)`). Given `AttributedText` it is\n * the rich editor: what the viewer types takes the attributes of the text\n * around it (`AttributedText.replacingCharacters`). Overloads (the text,\n * then the focus binding) rather than the union alone, so an inline\n * binding's setter still infers its type.\n */\nexport function TextEditor(props: PlainTextEditorProps & BoundFocusProps): ReactNode;\nexport function TextEditor<F extends FocusValue>(props: PlainTextEditorProps & SharedFocusProps<F>): ReactNode;\nexport function TextEditor(props: AttributedTextEditorProps & BoundFocusProps): ReactNode;\nexport function TextEditor<F extends FocusValue>(props: AttributedTextEditorProps & SharedFocusProps<F>): ReactNode;\nexport function TextEditor(props: TextEditorProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const [text, setText] = readBinding(own.text as BindingValue<string | AttributedText>, own.onChange as ((text: string | AttributedText) => void) | undefined);\n const focus = focusBinding(own);\n const selection = own.selection !== undefined ? readBinding(own.selection) : null;\n const rich = typeof text !== 'string';\n const editor: Record<string, unknown> = { text: rich ? AttributedText.plain(text) : text };\n if (rich) editor['runs'] = protocolRuns(text);\n if (focus) editor['focused'] = focus[0];\n if (selection) editor['selection'] = { start: selection[0].start, end: selection[0].end };\n if (own.onDeleteBackward) editor['deleteBackward'] = true;\n return applyModifiers(\n sb('texteditor', editor, {\n text: (event) => setText(rich ? AttributedText.replacingCharacters(text, event.value) : event.value),\n deletebackward: () => own.onDeleteBackward?.(),\n // The native editor's own Bold, Italic or Underline over the text (iOS 26's edit menu): the runs it now shows.\n runs: (event) => {\n if (rich) setText(fromProtocolRuns(event.value));\n },\n focus: (event) => focus?.[1](event.value),\n selection: (event) => selection?.[1](event.value),\n }),\n modifiers,\n );\n}\n\n/** A `disabled` modifier on the button itself turns its shortcut off too. */\nfunction buttonDisabled(modifiers: readonly [string, unknown][]): boolean {\n return modifiers.some(([key, value]) => key === 'disabled' && value === true);\n}\n","import type { ShapeKind, Stroke } from '@swiftbrowser/web/src/protocol';\nimport { useState, type ReactNode } from 'react';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, type ShapeSpec, type ViewModifiers } from '../modifiers';\nimport { Path, type CGRect } from '../path';\nimport { ColorValues, color, shapeStyle, type ColorValue, type StyleValue } from '../values';\n\nexport interface StrokeSpec {\n style?: StyleValue;\n lineWidth?: number;\n dash?: number[];\n dashPhase?: number;\n lineCap?: 'butt' | 'round' | 'square';\n lineJoin?: 'miter' | 'round' | 'bevel';\n miterLimit?: number;\n}\n\nexport type StrokeValue = StyleValue | StrokeSpec;\n\nexport interface ShapeProps extends ViewModifiers {\n /** `.fill(_:)`; without a fill or stroke the shape draws in the foreground color. */\n fill?: StyleValue;\n /** `.stroke(_:lineWidth:)` */\n stroke?: StrokeValue;\n /** `.strokeBorder(_:style:)`: the stroke inside the bounds. */\n strokeBorder?: StrokeValue;\n trim?: { from: number; to: number };\n}\n\nconst STYLE_KEYS = ['r', 'name', 'named', 'hierarchical', 'linearGradient', 'radialGradient', 'angularGradient', 'colorGradient', 'material'];\n\nfunction strokeOf(value: StrokeValue | undefined, inset: boolean): Stroke | null {\n if (value === undefined) return null;\n const isSpec = typeof value === 'object' && value !== null && !STYLE_KEYS.some((key) => key in value);\n const spec: StrokeSpec = isSpec ? (value as StrokeSpec) : { style: value as StyleValue };\n const stroke: Stroke = { color: shapeStyle(spec.style ?? 'primary'), lineWidth: spec.lineWidth ?? 1 };\n if (inset) stroke.inset = true;\n if (spec.dash) stroke.dash = spec.dash;\n if (spec.dashPhase !== undefined) stroke.dashPhase = spec.dashPhase;\n if (spec.lineCap) stroke.lineCap = spec.lineCap;\n if (spec.lineJoin) stroke.lineJoin = spec.lineJoin;\n if (spec.miterLimit !== undefined) stroke.miterLimit = spec.miterLimit;\n return stroke;\n}\n\nfunction shape(kind: ShapeKind, cornerRadius: number, props: ShapeProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const shapeProps: Record<string, unknown> = {\n shape: kind,\n cornerRadius,\n fill: own.fill !== undefined ? shapeStyle(own.fill) : null,\n stroke: strokeOf(own.strokeBorder, true) ?? strokeOf(own.stroke, false),\n };\n if (own.trim) shapeProps['trim'] = own.trim;\n return applyModifiers(sb('shape', shapeProps), modifiers);\n}\n\n/** Capsules, circles and ellipses carry this radius, like the shim. */\nconst ROUND = 9999;\n\nexport function Rectangle(props: ShapeProps): ReactNode {\n return shape('rectangle', 0, props);\n}\nRectangle.shape = { kind: 'rectangle', cornerRadius: 0 } satisfies ShapeSpec;\n\nexport interface RoundedRectangleProps extends ShapeProps {\n cornerRadius: number;\n}\n\nexport function RoundedRectangle(props: RoundedRectangleProps): ReactNode {\n const { cornerRadius, ...rest } = props;\n return shape('roundedRectangle', cornerRadius, rest);\n}\nRoundedRectangle.shape = { kind: 'roundedRectangle', cornerRadius: null } satisfies ShapeSpec;\n\nexport function Circle(props: ShapeProps): ReactNode {\n return shape('circle', ROUND, props);\n}\nCircle.shape = { kind: 'circle', cornerRadius: ROUND } satisfies ShapeSpec;\n\nexport function Capsule(props: ShapeProps): ReactNode {\n return shape('capsule', ROUND, props);\n}\nCapsule.shape = { kind: 'capsule', cornerRadius: ROUND } satisfies ShapeSpec;\n\nexport function Ellipse(props: ShapeProps): ReactNode {\n return shape('ellipse', ROUND, props);\n}\nEllipse.shape = { kind: 'ellipse', cornerRadius: ROUND } satisfies ShapeSpec;\n\nexport interface ContainerRelativeShapeProps extends ShapeProps {\n /** The container's corner radius (a widget's, a card's). */\n cornerRadius?: number;\n}\n\n/** `ContainerRelativeShape`: a rounded rectangle with its container's corners. */\nexport function ContainerRelativeShape(props: ContainerRelativeShapeProps): ReactNode {\n const { cornerRadius, ...rest } = props;\n return shape('containerRelative', cornerRadius ?? 0, rest);\n}\nContainerRelativeShape.shape = { kind: 'containerRelative', cornerRadius: null } satisfies ShapeSpec;\n\n// ---------------------------------------------------------------------------\n// Custom shapes\n// ---------------------------------------------------------------------------\n\nexport interface CustomShapeProps extends Omit<ShapeProps, 'trim'> {\n /** `path(in:)`: the shape's path for a rectangle of the size it is laid out at. */\n path: (rect: CGRect) => Path;\n /** `FillStyle(eoFill: true)` */\n evenOdd?: boolean;\n}\n\n/**\n * A custom `Shape`. A path whose every number is affine in the rectangle's\n * size (a point a fraction of the way across, a margin in from an edge) is\n * sent once as that (`affinePath`), and the page draws it at whatever size the\n * shape is laid out at, from its first frame. Any other path waits for the\n * element to report its laid-out size, and is drawn for that size, as the\n * Swift shim does.\n */\nexport function Shape(props: CustomShapeProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const [size, setSize] = useState<{ width: number; height: number } | null>(null);\n const affine = affinePath(own.path);\n const shapeProps: Record<string, unknown> = {\n shape: 'path',\n cornerRadius: 0,\n fill: own.fill !== undefined ? shapeStyle(own.fill) : null,\n // A custom shape's border is its path stroked as is (the shim insets an InsettableShape first).\n stroke: strokeOf(own.strokeBorder ?? own.stroke, false),\n reportsSize: affine === null,\n path: affine === null && size ? own.path({ x: 0, y: 0, width: size.width, height: size.height }).svg() : '',\n size: (affine === null && size) || { width: 0, height: 0 },\n };\n if (affine) shapeProps['affinePath'] = affine;\n if (own.evenOdd) shapeProps['fillRule'] = 'evenodd';\n return applyModifiers(\n sb(\n 'shape',\n shapeProps,\n affine\n ? undefined\n : {\n geometry: (event) => {\n if (!size || size.width !== event.width || size.height !== event.height) setSize({ width: event.width, height: event.height });\n },\n },\n ),\n modifiers,\n );\n}\n\n/**\n * A path as its numbers' parts: SVG path data with each number its value for\n * an empty rectangle, and how much each grows a point of the rectangle's width\n * and of its height.\n */\nexport interface AffinePath {\n path: string;\n width: number[];\n height: number[];\n}\n\n/** A number in SVG path data, as `Path` writes them. */\nconst NUMBER = /(-?(?:\\d+\\.?\\d*|\\.\\d+)(?:e[-+]?\\d+)?)/;\n/** The sizes a path's parts are worked out from (a large one, a point each way apart): */\nconst BASE = 1000;\n/** and the sizes they are checked at, a tiny one among them (where a clamp, as a corner's to half the side, shows). */\nconst CHECKS: readonly [number, number][] = [\n [613, 389],\n [257, 911],\n [3, 2],\n];\n\n/**\n * `path` as an `AffinePath`, or null where it is not one: where its commands\n * change with the size, or a number is not the same straight function of the\n * width and height at every size it is checked at (to the hundredth a point\n * the data is rounded to).\n */\nexport function affinePath(path: (rect: CGRect) => Path): AffinePath | null {\n try {\n const at = (width: number, height: number): string[] => path({ x: 0, y: 0, width, height }).svg().split(NUMBER);\n const base = at(BASE, BASE);\n const wider = at(2 * BASE, BASE);\n const taller = at(BASE, 2 * BASE);\n const same = (parts: string[]): boolean => parts.length === base.length && parts.every((part, i) => i % 2 === 1 || part === base[i]);\n if (!same(wider) || !same(taller)) return null;\n const round = (n: number, places: number): number => Math.round(n * 10 ** places) / 10 ** places || 0;\n const count = (base.length - 1) / 2;\n const width: number[] = [];\n const height: number[] = [];\n const constant: number[] = [];\n for (let i = 0; i < count; i += 1) {\n const n = Number(base[2 * i + 1]);\n width.push(round((Number(wider[2 * i + 1]) - n) / BASE, 6));\n height.push(round((Number(taller[2 * i + 1]) - n) / BASE, 6));\n constant.push(round(n - BASE * width[i]! - BASE * height[i]!, 4));\n }\n for (const [w, h] of CHECKS) {\n const parts = at(w, h);\n if (!same(parts)) return null;\n for (let i = 0; i < count; i += 1) {\n if (Math.abs(constant[i]! + w * width[i]! + h * height[i]! - Number(parts[2 * i + 1])) > 0.02) return null;\n }\n }\n const text = base.map((part, i) => (i % 2 === 1 ? String(constant[(i - 1) / 2]) : part)).join('');\n if (constant.some((n) => !Number.isFinite(n))) return null;\n return { path: text, width, height };\n } catch {\n return null;\n }\n}\n\nexport interface UnevenRoundedRectangleProps extends ShapeProps {\n topLeadingRadius?: number;\n bottomLeadingRadius?: number;\n bottomTrailingRadius?: number;\n topTrailingRadius?: number;\n}\n\n/** `UnevenRoundedRectangle`: a custom shape with a radius per corner. */\nexport function UnevenRoundedRectangle(props: UnevenRoundedRectangleProps): ReactNode {\n const { topLeadingRadius = 0, bottomLeadingRadius = 0, bottomTrailingRadius = 0, topTrailingRadius = 0, trim: _trim, ...rest } = props;\n const path = (rect: CGRect): Path => {\n const clamp = (radius: number): number => Math.max(0, Math.min(radius, rect.width / 2, rect.height / 2));\n const tl = clamp(topLeadingRadius);\n const tr = clamp(topTrailingRadius);\n const br = clamp(bottomTrailingRadius);\n const bl = clamp(bottomLeadingRadius);\n const { width: w, height: h } = rect;\n const p = new Path().move({ x: tl, y: 0 }).addLine({ x: w - tr, y: 0 });\n if (tr) p.addArc({ x: w - tr, y: tr }, tr, -90, 0, false);\n p.addLine({ x: w, y: h - br });\n if (br) p.addArc({ x: w - br, y: h - br }, br, 0, 90, false);\n p.addLine({ x: bl, y: h });\n if (bl) p.addArc({ x: bl, y: h - bl }, bl, 90, 180, false);\n p.addLine({ x: 0, y: tl });\n if (tl) p.addArc({ x: tl, y: tl }, tl, 180, 270, false);\n return p.closeSubpath();\n };\n return <Shape {...rest} path={path} />;\n}\n\n// ---------------------------------------------------------------------------\n// Color as a view\n// ---------------------------------------------------------------------------\n\nexport interface ColorViewProps extends ViewModifiers {\n color: ColorValue;\n}\n\n/** `Color.red` as a view: a box of the color that fills its proposal. */\nfunction ColorView(props: ColorViewProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n return applyModifiers(sb('color', { color: color(own.color) }), modifiers);\n}\n\n/**\n * `Color`: as a view, `<Color color=\"red\" />`; as values, `Color.red`,\n * `Color.opacity('black', 0.2)`, `Color.gradient('teal')`, `Color.hex('#336699')`.\n */\nexport const Color: typeof ColorView & typeof ColorValues = Object.assign(ColorView, ColorValues);\n","/**\n * Sign in with Apple: `signInWithApple()` asks the viewer and resolves with\n * the credential (`ASAuthorizationAppleIDCredential`'s fields: the stable\n * `user`, the name and email shared the first time, the identity token and\n * authorization code for the app's server), `appleCredentialState(user)` asks\n * what the credential is now, and `SignInWithAppleButton` is SwiftUI's\n * button, drawn from a button, the Apple logo and the label in the black,\n * white or white-outline style. Natively the system sheet answers; on a page\n * Apple's JS does, once the app named its Services ID and return URL with\n * `configureSignInWithApple` (both registered with Apple for the domain), and\n * without that the request fails `unsupported:`.\n */\n\nimport type { AppleCredentialState, AppleIDCredential } from '@swiftbrowser/web/src/hostRequests';\nimport { browserEnvironment } from '@swiftbrowser/web/src/hostRequests';\nimport { configureSignInWithApple } from '@swiftbrowser/web/src/appleSignIn';\nimport { type ReactNode } from 'react';\nimport { splitProps, type ViewModifiers } from './modifiers';\nimport { Button } from './components/controls';\nimport { HStack } from './components/stacks';\nimport { Image, Text } from './components/text';\nimport { RoundedRectangle } from './components/shapes';\nimport { system } from './values';\n\nexport type { AppleCredentialState, AppleIDCredential };\nexport { configureSignInWithApple };\n\nexport interface SignInWithAppleOptions {\n /** What to ask the viewer to share; both by default. Shared the first time only, as on iOS. */\n scopes?: ('fullName' | 'email')[];\n /** A nonce the identity token carries, for the app's server to check. */\n nonce?: string;\n /** Echoed back in the credential. */\n state?: string;\n}\n\n/** Whether this page or app can sign in with Apple (natively always; on a page once configured). */\nexport function canSignInWithApple(): boolean {\n return browserEnvironment.appleSignIn !== undefined;\n}\n\nexport async function signInWithApple(options: SignInWithAppleOptions = {}): Promise<AppleIDCredential> {\n const host = browserEnvironment.appleSignIn;\n if (!host) throw new Error('unsupported: Sign in with Apple is not available here (configureSignInWithApple on a page)');\n return host.signIn({ scopes: options.scopes ?? ['fullName', 'email'], ...(options.nonce ? { nonce: options.nonce } : {}), ...(options.state ? { state: options.state } : {}) });\n}\n\n/** `ASAuthorizationAppleIDProvider.credentialState(forUserID:)`; `unknown` where the host cannot ask (a page). */\nexport async function appleCredentialState(user: string): Promise<AppleCredentialState> {\n const host = browserEnvironment.appleSignIn;\n if (!host) return 'unknown';\n return host.credentialState(user);\n}\n\nexport type SignInWithAppleLabel = 'signIn' | 'signUp' | 'continue';\nexport type SignInWithAppleStyle = 'black' | 'white' | 'whiteOutline';\n\nexport interface SignInWithAppleButtonProps extends ViewModifiers {\n /** `.signIn` (\"Sign in with Apple\"), `.signUp` or `.continue`. */\n label?: SignInWithAppleLabel;\n /** `.signInWithAppleButtonStyle`: `black` by default. */\n style?: SignInWithAppleStyle;\n /** What to ask for: `onRequest` on iOS. Both scopes by default. */\n scopes?: ('fullName' | 'email')[];\n nonce?: string;\n state?: string;\n /** The credential, or the error (`cancelled: …` when the viewer dismissed the sheet). */\n onCompletion: (result: { credential: AppleIDCredential; error?: undefined } | { credential?: undefined; error: Error }) => void;\n}\n\nconst LABELS: Record<SignInWithAppleLabel, string> = { signIn: 'Sign in with Apple', signUp: 'Sign up with Apple', continue: 'Continue with Apple' };\n\nexport function SignInWithAppleButton(props: SignInWithAppleButtonProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const style = own.style ?? 'black';\n const background = style === 'black' ? 'black' : 'white';\n const foreground = style === 'black' ? 'white' : 'black';\n const action = (): void => {\n signInWithApple({ ...(own.scopes ? { scopes: own.scopes } : {}), ...(own.nonce ? { nonce: own.nonce } : {}), ...(own.state ? { state: own.state } : {}) }).then(\n (credential) => own.onCompletion({ credential }),\n (error: unknown) => own.onCompletion({ error: error instanceof Error ? error : new Error(String(error)) }),\n );\n };\n return (\n <Button\n action={action}\n buttonStyle=\"plain\"\n foregroundStyle={foreground}\n background={<RoundedRectangle cornerRadius={8} fill={background} />}\n {...(style === 'whiteOutline' ? { overlay: <RoundedRectangle cornerRadius={8} strokeBorder={{ style: 'black', lineWidth: 1 }} /> } : {})}\n {...Object.fromEntries(modifiers)}\n >\n <HStack spacing={6} frame={{ maxWidth: Infinity, height: 50 }} font={system(19, 'medium')}>\n <Image systemName=\"apple.logo\" />\n <Text>{LABELS[own.label ?? 'signIn']}</Text>\n </HStack>\n </Button>\n );\n}\n","/**\n * `useGeolocation(options)`: the viewer's position through the Geolocation\n * API, which a page has from the browser and a native app from the runtime\n * (`navigator.geolocation` over `CLLocationManager`; the app's Info.plist\n * names `NSLocationWhenInUseUsageDescription`). Nothing is asked until\n * `request()` (the first ask prompts the viewer), unless `immediate` is set;\n * `watch` keeps following the position until the view goes.\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\n\nexport interface GeolocationFix {\n latitude: number;\n longitude: number;\n /** Meters. */\n accuracy: number;\n altitude: number | null;\n heading: number | null;\n speed: number | null;\n /** Milliseconds since the epoch. */\n timestamp: number;\n}\n\nexport type GeolocationStatus = 'idle' | 'locating' | 'located' | 'denied' | 'failed';\n\nexport interface GeolocationOptions {\n /** Keep following the position (`watchPosition`) instead of asking once. */\n watch?: boolean;\n /** Ask as soon as the view appears. */\n immediate?: boolean;\n enableHighAccuracy?: boolean;\n /** Milliseconds to wait for a fix. */\n timeout?: number;\n maximumAge?: number;\n}\n\nexport interface GeolocationState {\n /** Whether the environment has `navigator.geolocation`. */\n available: boolean;\n status: GeolocationStatus;\n /** The latest fix, kept across a later failure. */\n position: GeolocationFix | null;\n error: string | null;\n /** Asks (again); with `watch`, starts following. */\n request(): void;\n /** Stops a watch; the position stays. */\n stop(): void;\n}\n\ninterface GeolocationLike {\n getCurrentPosition(success: (p: PositionLike) => void, failure?: (e: ErrorLike) => void, options?: object): void;\n watchPosition(success: (p: PositionLike) => void, failure?: (e: ErrorLike) => void, options?: object): number;\n clearWatch(id: number): void;\n}\ninterface PositionLike {\n coords: { latitude: number; longitude: number; accuracy: number; altitude: number | null; heading: number | null; speed: number | null };\n timestamp: number;\n}\ninterface ErrorLike {\n code: number;\n message: string;\n}\n\nfunction geolocationAPI(): GeolocationLike | null {\n const nav = (globalThis as { navigator?: { geolocation?: GeolocationLike } }).navigator;\n return nav?.geolocation ?? null;\n}\n\nexport function useGeolocation(options: GeolocationOptions = {}): GeolocationState {\n const { watch = false, immediate = false, enableHighAccuracy = false, timeout, maximumAge } = options;\n const api = geolocationAPI();\n const [status, setStatus] = useState<GeolocationStatus>('idle');\n const [position, setPosition] = useState<GeolocationFix | null>(null);\n const [error, setError] = useState<string | null>(null);\n const watching = useRef<number | null>(null);\n const mounted = useRef(true);\n\n const stop = useCallback((): void => {\n if (watching.current !== null) {\n geolocationAPI()?.clearWatch(watching.current);\n watching.current = null;\n }\n }, []);\n\n const request = useCallback((): void => {\n const geo = geolocationAPI();\n if (!geo) {\n setStatus('failed');\n setError('geolocation: not available');\n return;\n }\n stop();\n setStatus('locating');\n setError(null);\n const positionOptions = { enableHighAccuracy, ...(timeout !== undefined ? { timeout } : {}), ...(maximumAge !== undefined ? { maximumAge } : {}) };\n const onFix = (p: PositionLike): void => {\n if (!mounted.current) return;\n setPosition({\n latitude: p.coords.latitude,\n longitude: p.coords.longitude,\n accuracy: p.coords.accuracy,\n altitude: p.coords.altitude ?? null,\n heading: p.coords.heading ?? null,\n speed: p.coords.speed ?? null,\n timestamp: p.timestamp,\n });\n setStatus('located');\n setError(null);\n };\n const onError = (e: ErrorLike): void => {\n if (!mounted.current) return;\n setStatus(e.code === 1 ? 'denied' : 'failed');\n setError(e.message);\n if (e.code === 1) stop();\n };\n if (watch) watching.current = geo.watchPosition(onFix, onError, positionOptions);\n else geo.getCurrentPosition(onFix, onError, positionOptions);\n }, [watch, enableHighAccuracy, timeout, maximumAge, stop]);\n\n useEffect(() => {\n mounted.current = true;\n if (immediate) request();\n return () => {\n mounted.current = false;\n stop();\n };\n }, [immediate, request, stop]);\n\n return { available: api !== null, status, position, error, request, stop };\n}\n","/**\n * Speech through the Web Speech API, which a page has from the browser and a\n * native app from the runtime (`speechSynthesis` on `AVSpeechSynthesizer`,\n * `SpeechRecognition` on `SFSpeechRecognizer`): `useSpeechSynthesis()` reads\n * text aloud, `useSpeechRecognition()` turns the viewer's speech into text.\n * Each reads `available` where the environment lacks the API.\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\n\n// MARK: Synthesis\n\nexport interface SpeakOptions {\n /** A BCP 47 tag (`en-US`); the environment's voice for it. */\n lang?: string;\n /** A multiple of the normal rate (1). */\n rate?: number;\n pitch?: number;\n volume?: number;\n}\n\nexport interface SpeechSynthesisState {\n available: boolean;\n speaking: boolean;\n paused: boolean;\n /** Reads `text` aloud, after what is queued (`cancel()` first to interrupt). */\n speak(text: string, options?: SpeakOptions): void;\n /** Stops and empties the queue. */\n cancel(): void;\n pause(): void;\n resume(): void;\n}\n\ninterface UtteranceLike {\n text: string;\n lang: string;\n rate: number;\n pitch: number;\n volume: number;\n onstart: ((e: unknown) => void) | null;\n onend: ((e: unknown) => void) | null;\n onerror: ((e: unknown) => void) | null;\n onpause: ((e: unknown) => void) | null;\n onresume: ((e: unknown) => void) | null;\n}\ninterface SynthesisLike {\n speaking: boolean;\n paused: boolean;\n speak(utterance: UtteranceLike): void;\n cancel(): void;\n pause(): void;\n resume(): void;\n}\n\nfunction synthesisAPI(): { synthesis: SynthesisLike; Utterance: new (text: string) => UtteranceLike } | null {\n const g = globalThis as { speechSynthesis?: SynthesisLike; SpeechSynthesisUtterance?: new (text: string) => UtteranceLike };\n return g.speechSynthesis && g.SpeechSynthesisUtterance ? { synthesis: g.speechSynthesis, Utterance: g.SpeechSynthesisUtterance } : null;\n}\n\nexport function useSpeechSynthesis(): SpeechSynthesisState {\n const api = synthesisAPI();\n const [speaking, setSpeaking] = useState(false);\n const [paused, setPaused] = useState(false);\n const mounted = useRef(true);\n /** The utterances this hook queued and not yet done. */\n const queued = useRef(0);\n\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n // What this view was reading stops with it.\n if (queued.current > 0) synthesisAPI()?.synthesis.cancel();\n };\n }, []);\n\n const speak = useCallback((text: string, options: SpeakOptions = {}): void => {\n const current = synthesisAPI();\n if (!current) return;\n const utterance = new current.Utterance(text);\n if (options.lang) utterance.lang = options.lang;\n if (options.rate !== undefined) utterance.rate = options.rate;\n if (options.pitch !== undefined) utterance.pitch = options.pitch;\n if (options.volume !== undefined) utterance.volume = options.volume;\n queued.current++;\n const done = (): void => {\n queued.current = Math.max(0, queued.current - 1);\n if (!mounted.current) return;\n if (queued.current === 0) {\n setSpeaking(false);\n setPaused(false);\n }\n };\n utterance.onstart = () => {\n if (!mounted.current) return;\n setSpeaking(true);\n setPaused(false);\n };\n utterance.onpause = () => mounted.current && setPaused(true);\n utterance.onresume = () => mounted.current && setPaused(false);\n utterance.onend = done;\n utterance.onerror = done;\n current.synthesis.speak(utterance);\n }, []);\n\n const cancel = useCallback((): void => {\n synthesisAPI()?.synthesis.cancel();\n }, []);\n const pause = useCallback((): void => synthesisAPI()?.synthesis.pause(), []);\n const resume = useCallback((): void => synthesisAPI()?.synthesis.resume(), []);\n\n return { available: api !== null, speaking, paused, speak, cancel, pause, resume };\n}\n\n// MARK: Recognition\n\nexport interface SpeechRecognitionOptions {\n /** A BCP 47 tag; the environment's language by default. */\n lang?: string;\n /** Keep listening after a pause instead of ending at the first final result. */\n continuous?: boolean;\n /** Report what is heard as it is heard (`interim`), before it is final. */\n interimResults?: boolean;\n}\n\nexport interface SpeechRecognitionState {\n available: boolean;\n listening: boolean;\n /** The final transcripts of this session, joined. */\n transcript: string;\n /** What is being heard now, not yet final. */\n interim: string;\n /** `not-allowed`, `audio-capture`, `no-speech`, `network`, `aborted` … */\n error: string | null;\n start(): void;\n /** Stops listening; the last words still arrive. */\n stop(): void;\n /** Stops listening and keeps nothing more. */\n abort(): void;\n}\n\ninterface RecognitionLike {\n lang: string;\n continuous: boolean;\n interimResults: boolean;\n onstart: (() => void) | null;\n onresult: ((e: { resultIndex: number; results: ArrayLike<{ isFinal: boolean; 0: { transcript: string } }> }) => void) | null;\n onerror: ((e: { error: string }) => void) | null;\n onend: (() => void) | null;\n start(): void;\n stop(): void;\n abort(): void;\n}\n\nfunction recognitionAPI(): (new () => RecognitionLike) | null {\n const g = globalThis as { SpeechRecognition?: new () => RecognitionLike; webkitSpeechRecognition?: new () => RecognitionLike };\n return g.SpeechRecognition ?? g.webkitSpeechRecognition ?? null;\n}\n\nexport function useSpeechRecognition(options: SpeechRecognitionOptions = {}): SpeechRecognitionState {\n const { lang, continuous = false, interimResults = true } = options;\n const api = recognitionAPI();\n const [listening, setListening] = useState(false);\n const [transcript, setTranscript] = useState('');\n const [interim, setInterim] = useState('');\n const [error, setError] = useState<string | null>(null);\n const current = useRef<RecognitionLike | null>(null);\n const mounted = useRef(true);\n\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n current.current?.abort();\n current.current = null;\n };\n }, []);\n\n const start = useCallback((): void => {\n const Recognition = recognitionAPI();\n if (!Recognition) {\n setError('not-allowed');\n return;\n }\n if (current.current) return;\n const recognition = new Recognition();\n if (lang) recognition.lang = lang;\n recognition.continuous = continuous;\n recognition.interimResults = interimResults;\n setTranscript('');\n setInterim('');\n setError(null);\n recognition.onstart = () => mounted.current && setListening(true);\n recognition.onresult = (e) => {\n if (!mounted.current) return;\n const finals: string[] = [];\n let heard = '';\n for (let i = 0; i < e.results.length; i++) {\n const result = e.results[i]!;\n if (result.isFinal) finals.push(result[0].transcript.trim());\n else heard = result[0].transcript;\n }\n setTranscript(finals.filter(Boolean).join(' '));\n setInterim(heard);\n };\n recognition.onerror = (e) => mounted.current && setError(e.error);\n recognition.onend = () => {\n if (current.current === recognition) current.current = null;\n if (!mounted.current) return;\n setListening(false);\n setInterim('');\n };\n current.current = recognition;\n recognition.start();\n }, [lang, continuous, interimResults]);\n\n const stop = useCallback((): void => current.current?.stop(), []);\n const abort = useCallback((): void => current.current?.abort(), []);\n\n return { available: api !== null, listening, transcript, interim, error, start, stop, abort };\n}\n","/**\n * `useAppStorage(key, default)`: SwiftUI's `@AppStorage`. A value kept under a\n * key in the app's storage (`localStorage`: the browser's on a page, the\n * device's in a SwiftBrowser Native app) as JSON, read back at the next\n * launch, and shared by every view that reads the key: a write through any of\n * them re-renders them all. The default stands in while nothing is stored,\n * and setting `undefined` removes the key, as assigning nil does.\n *\n * The hook is the key's writer: it keeps what it read and re-reads storage\n * only when another tab writes the key (the window's `storage` event). A\n * write that storage refuses (a page's storage is full) still takes effect\n * in the app, for the session, and is reported to `onError`.\n */\n\nimport { useCallback, useState, useSyncExternalStore } from 'react';\n\n/** Where the values go: `localStorage`'s shape. */\nexport interface AppStorageStore {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n}\n\nexport interface AppStorageOptions<T> {\n /** The storage; `localStorage` by default (memory where a page has none, or refuses it). */\n store?: AppStorageStore;\n /**\n * What a stored value becomes on load: a migration from what an older\n * version of the app saved. A throw falls back to the default. The readers\n * of a key share one; the last to mount decides.\n */\n decode?: (stored: unknown) => T;\n /** A write storage refused (out of room). The value is kept in memory regardless. */\n onError?: (error: unknown) => void;\n}\n\n/** The new value, or a function of the current one, as `useState`'s setter takes. */\nexport type AppStorageSetter<T> = (value: T | ((current: T) => T)) => void;\n\ninterface Entry {\n /** The stored JSON, null for no value (or one that would not parse). */\n raw: string | null;\n /** What `raw` decodes to; meaningless while `raw` is null. */\n value: unknown;\n /** Whether `value` is current for `raw`. */\n decoded: boolean;\n decode: ((stored: unknown) => unknown) | undefined;\n listeners: Set<() => void>;\n}\n\nconst stores = new WeakMap<AppStorageStore, Map<string, Entry>>();\n\nfunction entryFor(store: AppStorageStore, key: string): Entry {\n let entries = stores.get(store);\n if (!entries) {\n entries = new Map();\n stores.set(store, entries);\n if (store === pageStorage) watchOtherTabs();\n }\n let entry = entries.get(key);\n if (!entry) {\n let raw: string | null = null;\n try {\n raw = store.getItem(key);\n } catch {\n // Unreadable (a private window, blocked site data): nothing is stored.\n }\n entry = { raw, value: undefined, decoded: false, decode: undefined, listeners: new Set() };\n entries.set(key, entry);\n }\n return entry;\n}\n\n/** The entry's value, decoding the stored JSON once; `absent` while nothing (that parses) is stored. */\nfunction valueOf(entry: Entry, absent: unknown): unknown {\n if (entry.raw === null) return absent;\n if (!entry.decoded) {\n try {\n const parsed: unknown = JSON.parse(entry.raw);\n entry.value = entry.decode ? entry.decode(parsed) : parsed;\n } catch {\n // Not JSON, or the decode refused it: as good as nothing stored.\n entry.raw = null;\n return absent;\n }\n entry.decoded = true;\n }\n return entry.value;\n}\n\nfunction notify(entry: Entry): void {\n for (const listener of [...entry.listeners]) listener();\n}\n\n/** Takes `raw` as the stored JSON (another tab wrote it), to decode on the next read. */\nfunction invalidate(entry: Entry, raw: string | null): void {\n if (entry.raw === raw && entry.decoded) return;\n entry.raw = raw;\n entry.decoded = false;\n notify(entry);\n}\n\n// ---------------------------------------------------------------------------\n// The default store: the page's localStorage, or memory\n// ---------------------------------------------------------------------------\n\n/** `localStorage` where the page has one and lets the app at it, else null. */\nfunction readPageStorage(): AppStorageStore | null {\n try {\n const storage = (globalThis as { localStorage?: AppStorageStore }).localStorage;\n return storage && typeof storage.getItem === 'function' ? storage : null;\n } catch {\n return null;\n }\n}\n\nconst memory = new Map<string, string>();\n\n/** For a page without `localStorage`: the values last the session. */\nconst memoryStorage: AppStorageStore = {\n getItem: (key) => memory.get(key) ?? null,\n setItem: (key, value) => void memory.set(key, value),\n removeItem: (key) => void memory.delete(key),\n};\n\nconst pageStorage = readPageStorage();\n\n/** The store `useAppStorage` uses when none is given. */\nexport const appStorage: AppStorageStore = pageStorage ?? memoryStorage;\n\nlet watching = false;\n\n/** Another tab's writes to `localStorage` reach this one as `storage` events. */\nfunction watchOtherTabs(): void {\n if (watching || !pageStorage) return;\n watching = true;\n const target = (globalThis as { addEventListener?: (type: string, listener: (event: StorageEvent) => void) => void });\n if (typeof target.addEventListener !== 'function') return;\n target.addEventListener('storage', (event: StorageEvent) => {\n if (event.storageArea !== pageStorage) return;\n const entries = stores.get(pageStorage);\n if (!entries) return;\n if (event.key === null) {\n for (const entry of entries.values()) invalidate(entry, null);\n } else {\n const entry = entries.get(event.key);\n if (entry) invalidate(entry, event.newValue);\n }\n });\n}\n\n// ---------------------------------------------------------------------------\n// The hook\n// ---------------------------------------------------------------------------\n\n/**\n * The value stored under `key`, or `defaultValue` (a value, or a function\n * making one, as `useState` takes) while there is none, and its setter. The\n * value must survive JSON: plain objects, arrays, strings, numbers,\n * booleans, null.\n */\nexport function useAppStorage<T>(key: string, defaultValue: T | (() => T), options: AppStorageOptions<T> = {}): [T, AppStorageSetter<T>] {\n const { store = appStorage, decode, onError } = options;\n const [fallback] = useState(defaultValue);\n const entry = entryFor(store, key);\n entry.decode = decode;\n const subscribe = useCallback(\n (listener: () => void) => {\n const subscribed = entryFor(store, key);\n subscribed.listeners.add(listener);\n return () => void subscribed.listeners.delete(listener);\n },\n [store, key],\n );\n const read = useCallback((): T => valueOf(entryFor(store, key), fallback) as T, [store, key, fallback]);\n const value = useSyncExternalStore(subscribe, read, read);\n const set = useCallback<AppStorageSetter<T>>(\n (next) => {\n const target = entryFor(store, key);\n const current = valueOf(target, fallback) as T;\n const value = typeof next === 'function' ? (next as (current: T) => T)(current) : next;\n const raw = value === undefined ? null : JSON.stringify(value);\n try {\n if (raw === null) store.removeItem(key);\n else store.setItem(key, raw);\n } catch (error) {\n onError?.(error);\n }\n // Decoded already: the value the app set is the one it reads back.\n target.raw = raw;\n target.value = value;\n target.decoded = raw !== null;\n notify(target);\n },\n [store, key, fallback, onError],\n );\n return [value, set];\n}\n","/**\n * `fileManager`: Foundation's `FileManager.default` for the app's own files,\n * with `URL.documentsDirectory` and its siblings. Paths are `file:` URLs. On\n * a page the files live in the app's IndexedDB database, the same iOS-like\n * home a Swift app has there (`/data`: `Documents`, `Library/Application\n * Support`, `Library/Caches`, and `/tmp` for the session); in a SwiftBrowser\n * Native app they are the app's sandbox. The calls are asynchronous on both,\n * since the page's storage is: the one departure from Swift.\n *\n * `loadURL` is what a `VideoPlayer`, an `AudioPlayer` or an `Image` loads a\n * file at; they call it themselves for a `file:` URL, so an app hands them\n * the file's URL as it would natively.\n */\n\nimport type { FileAttributes, FileDirectories, FilesHost } from '@swiftbrowser/web/src/files';\nimport { fileURL } from '@swiftbrowser/web/src/files';\nimport { browserEnvironment } from '@swiftbrowser/web/src/hostRequests';\n\nexport type { FileAttributes, FileDirectories };\n\n/**\n * What `write` takes: bytes, a Blob or a File, or text (written as UTF-8). A\n * Blob or File is handed to the host as it is, so a picked or dropped file\n * is kept without passing through memory (IndexedDB stores the Blob; the\n * native app copies the file on disk).\n */\nexport type FileContents = Uint8Array | ArrayBuffer | Blob | string;\n\n/** A byte range of a file: from `start` up to `end` (exclusive, clamped to the file's size). */\nexport interface FileRange {\n start: number;\n end: number;\n}\n\nexport interface FileManager {\n /** Whether this page or app keeps files; the calls below fail `unsupported: …` where it does not. */\n readonly available: boolean;\n /** `URL.documentsDirectory`: the app's documents, kept across launches. */\n readonly documentsDirectory: string;\n /** `URL.applicationSupportDirectory`: the app's own data, kept across launches. */\n readonly applicationSupportDirectory: string;\n /** `URL.cachesDirectory`: what can be made again. */\n readonly cachesDirectory: string;\n /** `FileManager.temporaryDirectory`: empty at every launch. */\n readonly temporaryDirectory: string;\n /** `url.appending(path:)`: the `file:` URL of `path` below `directory`. */\n url(directory: string, path: string): string;\n /**\n * `Data(contentsOf:)`: the file's bytes; with `range`, only those from\n * `range.start` up to `range.end`, read without the rest where the host can\n * (`FileHandle` natively, a `Blob` slice on a page), so a large file is read\n * a piece at a time.\n */\n contents(url: string, range?: FileRange): Promise<Uint8Array>;\n /** `String(contentsOf:)`: the file as UTF-8 text. */\n text(url: string): Promise<string>;\n /**\n * `Data.write(to:)`: writes the file, replacing one there; its directory\n * must exist. A `Blob` or `File` is kept as it is (see `FileContents`).\n */\n write(url: string, contents: FileContents): Promise<void>;\n /** `contentsOfDirectory(at:)`: the URLs of what the directory holds, by name. */\n contentsOfDirectory(url: string): Promise<string[]>;\n /** `createDirectory(at:withIntermediateDirectories: true)`. */\n createDirectory(url: string): Promise<void>;\n /** `fileExists(atPath:)`. */\n fileExists(url: string): Promise<boolean>;\n /** `attributesOfItem(atPath:)`: the size, the modification and creation times where known, whether it is a directory, and the MIME type its extension names; fails `notFound: …`. */\n attributesOfItem(url: string): Promise<FileAttributes>;\n /** `moveItem(at:to:)`: to a URL nothing is at, in a directory that exists. */\n moveItem(from: string, to: string): Promise<void>;\n /** `copyItem(at:to:)`: to a URL nothing is at, in a directory that exists. */\n copyItem(from: string, to: string): Promise<void>;\n /** `removeItem(at:)`: a file, or a directory and all it holds. */\n removeItem(url: string): Promise<void>;\n /** A URL the page can load the file at (an object URL of its bytes; natively the URL itself, downloaded from iCloud Drive first). */\n loadURL(url: string): Promise<string>;\n /**\n * `FileManager.url(forUbiquityContainerIdentifier:)`, then `Documents`: the\n * app's folder in iCloud Drive, where the app has the iCloud entitlement\n * (`swiftbrowser native init --icloud`) and the viewer iCloud Drive. The\n * files there follow the viewer to their other devices and show in the\n * Files app. Null without it, and on a page. Reading a file another device\n * wrote downloads it first.\n */\n iCloudDirectory(): Promise<string | null>;\n /**\n * Calls `listener` with the URLs that changed: what this app wrote, and\n * natively what another device wrote to iCloud Drive. Returns a function\n * that stops listening. `useFileStorage` reads a file again on it.\n */\n watch(listener: (urls: string[]) => void): () => void;\n}\n\n/** The directories a page without a files host would have, for the properties to answer something. */\nconst NONE: FileDirectories = {\n documents: 'file:///data/Documents',\n applicationSupport: 'file:///data/Library/Application%20Support',\n caches: 'file:///data/Library/Caches',\n temporary: 'file:///tmp',\n};\n\n/** What the host is given for `write`: bytes, or the Blob itself. */\nfunction hostData(contents: FileContents): Uint8Array | Blob {\n if (typeof contents === 'string') return new TextEncoder().encode(contents);\n if (contents instanceof Uint8Array) return contents;\n if (contents instanceof ArrayBuffer) return new Uint8Array(contents);\n return contents;\n}\n\n/** A file manager over the host `host` answers (the environment's, looked up at each call, for the default). */\nexport function createFileManager(host: () => FilesHost | undefined): FileManager {\n const required = (): FilesHost => {\n const files = host();\n if (!files) throw new Error('unsupported: this page keeps no files');\n return files;\n };\n const directories = (): FileDirectories => host()?.directories ?? NONE;\n return {\n get available() {\n return host() !== undefined;\n },\n get documentsDirectory() {\n return directories().documents;\n },\n get applicationSupportDirectory() {\n return directories().applicationSupport;\n },\n get cachesDirectory() {\n return directories().caches;\n },\n get temporaryDirectory() {\n return directories().temporary;\n },\n url: (directory, path) => fileURL(directory, path),\n contents: async (url, range) => {\n const files = required();\n if (!range) return files.read(url);\n if (files.readRange) return files.readRange(url, range.start, range.end);\n const all = await files.read(url);\n const start = Math.min(Math.max(0, range.start), all.byteLength);\n return all.subarray(start, Math.min(Math.max(start, range.end), all.byteLength));\n },\n text: async (url) => new TextDecoder().decode(await required().read(url)),\n write: async (url, contents) => required().write(url, hostData(contents)),\n contentsOfDirectory: async (url) => required().list(url),\n createDirectory: async (url) => required().createDirectory(url),\n fileExists: async (url) => (await required().attributes(url)) !== null,\n attributesOfItem: async (url) => {\n const attributes = await required().attributes(url);\n if (!attributes) throw new Error(`notFound: nothing at ${url}`);\n return attributes;\n },\n moveItem: async (from, to) => required().move(from, to),\n copyItem: async (from, to) => required().copy(from, to),\n removeItem: async (url) => required().remove(url),\n loadURL: async (url) => required().loadURL(url),\n iCloudDirectory: async () => (await host()?.iCloud?.()) ?? null,\n watch: (listener) => host()?.watch?.(listener) ?? (() => {}),\n };\n}\n\n/** `FileManager.default`: the app's files through the renderer environment's host. */\nexport const fileManager: FileManager = createFileManager(() => browserEnvironment.files);\n","/**\n * `useFileStorage(url, default)`: a value kept as a JSON file through\n * `fileManager`, the way `useAppStorage` keeps one under a key. The file is\n * read when the URL is given (the default stands in until then, and where\n * there is no file yet), written on each set, and read again when\n * `fileManager.watch` says it changed: another view wrote it, or another\n * device did, in iCloud Drive. A document app keeps its documents this way:\n * put the file in `iCloudDirectory()` where there is one, in\n * `documentsDirectory` elsewhere, and it is the same code on both.\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { fileManager, type FileManager } from './fileManager';\n\nexport interface FileStorageOptions<T> {\n /** What a stored value becomes on load: a migration from what an older version wrote. A throw falls back to the default. */\n decode?: (stored: unknown) => T;\n /** A read or write that failed (the file could not be downloaded, the storage is full). */\n onError?: (error: unknown) => void;\n /** The file manager; `fileManager` by default. */\n manager?: FileManager;\n}\n\n/** The new value, or a function of the current one, as `useState`'s setter takes. */\nexport type FileStorageSetter<T> = (value: T | ((current: T) => T)) => void;\n\n/** `loading` until the file was read (or found missing); `ready` after; `error` when the read failed (the default stands). */\nexport type FileStorageStatus = 'loading' | 'ready' | 'error';\n\nexport function useFileStorage<T>(url: string | null, defaultValue: T | (() => T), options: FileStorageOptions<T> = {}): [T, FileStorageSetter<T>, FileStorageStatus] {\n const manager = options.manager ?? fileManager;\n const [value, setValue] = useState<T>(defaultValue);\n const [status, setStatus] = useState<FileStorageStatus>(url === null ? 'ready' : 'loading');\n const latest = useRef({ value, options, url, defaultValue });\n latest.current = { value, options, url, defaultValue };\n /** The URL the state is for; another one starts from the default again. */\n const shown = useRef(url);\n /** The JSON last read or written, to tell a change of ours from another writer's. */\n const known = useRef<string | null>(null);\n /** Writes in flight, in order. */\n const writing = useRef<Promise<void>>(Promise.resolve());\n\n const load = useCallback(\n async (target: string): Promise<void> => {\n let text: string | null;\n try {\n text = await manager.text(target);\n } catch (error) {\n if (latest.current.url !== target) return;\n if (error instanceof Error && error.message.startsWith('notFound:')) {\n known.current = null;\n setStatus('ready');\n return;\n }\n latest.current.options.onError?.(error);\n setStatus('error');\n return;\n }\n if (latest.current.url !== target) return;\n if (text !== known.current) {\n known.current = text;\n try {\n const stored: unknown = JSON.parse(text);\n setValue(latest.current.options.decode ? latest.current.options.decode(stored) : (stored as T));\n } catch (error) {\n latest.current.options.onError?.(error);\n }\n }\n setStatus('ready');\n },\n [manager],\n );\n\n useEffect(() => {\n known.current = null;\n if (shown.current !== url) {\n shown.current = url;\n const fresh = latest.current.defaultValue;\n const value = typeof fresh === 'function' ? (fresh as () => T)() : fresh;\n latest.current.value = value;\n setValue(value);\n }\n if (url === null) {\n setStatus('ready');\n return;\n }\n setStatus('loading');\n void load(url);\n return manager.watch((urls) => {\n if (urls.includes(url)) void load(url);\n });\n }, [url, load, manager]);\n\n const set = useCallback<FileStorageSetter<T>>(\n (next) => {\n const resolved = typeof next === 'function' ? (next as (current: T) => T)(latest.current.value) : next;\n latest.current.value = resolved;\n setValue(resolved);\n const target = latest.current.url;\n if (target === null) return;\n const text = JSON.stringify(resolved);\n known.current = text;\n writing.current = writing.current.then(async () => {\n try {\n await manager.write(target, text);\n } catch (error) {\n latest.current.options.onError?.(error);\n }\n });\n },\n [manager],\n );\n\n return [value, set, status];\n}\n","import type { ListStyle } from '@swiftbrowser/web/src/protocol';\nimport { Fragment, isValidElement, useContext, type ReactElement, type ReactNode } from 'react';\nimport { SplitSelectionContext, useReportSplitSelection } from './split';\nimport { readBinding, type BindingValue } from '../binding';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, takeModifier, type ViewModifiers } from '../modifiers';\nimport { plainText } from './controls';\nimport { NavigationLink } from './navigation';\nimport { ListSelectionContext, Row, type ListSelection, type RowProps } from './row';\nimport { PinnedContext, flattenChildren, providingScrollSettings, takeScrollSettings, useRefreshable } from './stacks';\nimport { edgeEffectProp, useScrollSettings } from '../scrollEnvironment';\nimport { LazyContext, LazyGroup, type LazyGroupProps } from '../lazy';\nimport { Text } from './text';\n\nconst NO_CLEAR = (): void => {};\n\n/** A selection: one value (or `null`), or a `Set` of values. */\nexport type Selection<T> = T | null | Set<T>;\n\nexport interface ListProps<T = unknown> extends ViewModifiers {\n listStyle?: ListStyle;\n /** A `Form`: on a Mac the rows are laid out in the columns style (labels in a column before their controls). */\n form?: boolean;\n /** `.formStyle(_:)` on a `Form`: on a Mac `grouped` lays it out in grouped sections, `columns` (and the default) in the columns style. */\n formStyle?: 'automatic' | 'grouped' | 'columns';\n /**\n * This list's rows are at least this tall, over the\n * `defaultMinListRowHeight` set above it (the modifier, which every list\n * below inherits; set it once at an app's top). Absent both, the\n * platform's default (44 on iOS, 24 on a Mac).\n */\n minRowHeight?: number;\n /** Edit mode (`EditButton`). */\n editing?: BindingValue<boolean>;\n /** `List(selection:)`: rows with a `tag` (or a `NavigationLink` value) become selectable; a `Set` selects several. */\n selection?: BindingValue<Set<T>> | BindingValue<T | null> | undefined;\n onSelectionChange?: ((selection: Selection<T>) => void) | undefined;\n children?: ReactNode;\n}\n\nexport function List<T = unknown>(props: ListProps<T>): ReactNode {\n const { own, modifiers } = splitProps(props);\n const [editing] = own.editing !== undefined ? readBinding(own.editing) : [false];\n const listProps: Record<string, unknown> = { style: own.listStyle ?? 'insetGrouped' };\n if (own.form) listProps['form'] = true;\n if (own.form && own.formStyle && own.formStyle !== 'automatic') listProps['formStyle'] = own.formStyle;\n if (own.minRowHeight !== undefined && Number.isFinite(own.minRowHeight)) listProps['minRowHeight'] = Math.max(0, own.minRowHeight);\n if (editing) listProps['editing'] = true;\n let selection: ListSelection | null = null;\n const split = useContext(SplitSelectionContext);\n /** Set below to tell the split of a tap's selection in the same update. */\n let reportNow: (selected: boolean, clear: () => void) => void = () => {};\n let selected = false;\n let clearSelection = NO_CLEAR;\n if (own.selection !== undefined) {\n const [value, setValue] = readBinding(own.selection as BindingValue<Selection<T>>, own.onSelectionChange);\n // A `Set` chooses several: in edit mode the native list shows its checkmark circles.\n if (value instanceof Set) listProps['multiSelect'] = true;\n selected = value instanceof Set ? value.size > 0 : value !== null && value !== undefined;\n clearSelection = () => setValue(value instanceof Set ? new Set<T>() : null);\n selection = {\n editing,\n isSelected: (tag) => (value instanceof Set ? value.has(tag as T) : value !== null && Object.is(value, tag)),\n select: (tag) => {\n if (value instanceof Set) {\n const next = new Set(value);\n if (next.has(tag as T)) next.delete(tag as T);\n else next.add(tag as T);\n setValue(next);\n reportNow(next.size > 0, () => setValue(new Set<T>()));\n } else {\n const next = editing && Object.is(value, tag) ? null : (tag as T);\n setValue(next);\n reportNow(next !== null, () => setValue(null));\n }\n },\n };\n }\n reportNow = useReportSplitSelection(split, selected, clearSelection, own.selection !== undefined);\n const refresh = useRefreshable(takeModifier(modifiers, 'refreshable'));\n Object.assign(listProps, refresh.props);\n // `.scrollEdgeEffectStyle` / `.scrollEdgeEffectHidden` (content margins are a scroll view's).\n const ownSettings = takeScrollSettings(modifiers);\n const edgeEffect = edgeEffectProp(useScrollSettings(ownSettings));\n if (edgeEffect) listProps['edgeEffect'] = edgeEffect;\n const element = (\n <LazyContext.Provider value=\"vertical\">\n {sb('list', listProps, refresh.handlers, providingScrollSettings(ownSettings, wrapRows(own.children)))}\n </LazyContext.Provider>\n );\n return applyModifiers(\n selection ? <ListSelectionContext.Provider value={selection}>{element}</ListSelectionContext.Provider> : element,\n modifiers,\n );\n}\n\n/** `Form { }`: an inset grouped list, as the shim draws it; on a Mac its rows are laid out in the columns style. */\nexport function Form(props: Omit<ListProps, 'listStyle' | 'selection' | 'onSelectionChange' | 'form'>): ReactNode {\n return <List {...props} form />;\n}\n\nexport interface SectionProps extends ViewModifiers {\n /** A string or a `<Text>` becomes the section's header text; any other view is a view header. */\n header?: ReactNode;\n footer?: ReactNode;\n /** `Section(isExpanded:)`: the section collapses, in a sidebar-style list (as on iOS); its header's chevron toggles it. */\n isExpanded?: BindingValue<boolean>;\n onExpandedChange?: (expanded: boolean) => void;\n children?: ReactNode;\n}\n\nexport function Section(props: SectionProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const pinned = useContext(PinnedContext);\n const [expanded, setExpanded] = own.isExpanded !== undefined ? readBinding(own.isExpanded, own.onExpandedChange) : [true, (): void => {}];\n const collapsible = own.isExpanded !== undefined;\n let header = supplement(own.header);\n let footer = supplement(own.footer);\n // In a lazy stack that pins its headers (footers), a string one is a view, so it can pin: outside a list the text would not draw.\n if (pinned?.includes('sectionHeaders') && header.text !== null && !header.view) header = { text: null, view: <Text>{header.text}</Text> };\n if (pinned?.includes('sectionFooters') && footer.text !== null && !footer.view) footer = { text: null, view: <Text>{footer.text}</Text> };\n // Keyed, so React does not take the header, the rows and the footer for a list of its own.\n const children: ReactNode[] = [];\n if (header.view) children.push(<Fragment key=\"header\">{sb('sectionheader', {}, undefined, header.view)}</Fragment>);\n if (own.children !== undefined) children.push(<Fragment key=\"rows\">{wrapRows(own.children)}</Fragment>);\n if (footer.view) children.push(<Fragment key=\"footer\">{sb('sectionfooter', {}, undefined, footer.view)}</Fragment>);\n // The rows go whatever the state: the renderers hide them collapsed, as SwiftUI does.\n return applyModifiers(\n sb(\n 'section',\n collapsible ? { header: header.text, footer: footer.text, collapsible: true, expanded } : { header: header.text, footer: footer.text },\n collapsible ? { tap: () => setExpanded(!expanded) } : undefined,\n children,\n ),\n modifiers,\n );\n}\n\n/**\n * Rows with a tag (`.tag`, or a `NavigationLink` value) become `Row`s, so a\n * `List(selection:)` can select them; a `Row` from `ForEach`'s `onDelete`\n * keeps its own. Sections pass through (they wrap their own rows).\n */\nfunction wrapRows(children: ReactNode): ReactNode {\n // Lazy groups stay groups (they build their rows as they scroll in); the\n // rows before one count it as one child, the rows after as its rows.\n let offset = 0;\n return flattenChildren(children, { keepLazy: true }).map((element, index) => {\n const at = index + offset;\n if (element.type === LazyGroup) {\n const group = element.props as LazyGroupProps;\n offset += group.rows.length - 1;\n return { ...withKey(element, index), props: { ...group, start: at, wrap: wrapRow } };\n }\n return wrapRow(withKey(element, index), at);\n });\n}\n\n/** A row as its container holds it: a `Row` knows its index; a tagged view becomes a selectable `Row`. */\nfunction wrapRow(row: ReactElement, containerIndex: number): ReactElement {\n // A lazy group's `ForEach` row is still in its fragments (flattenChildren took the others out): the one view inside carries the tag.\n const inner = row.type === Fragment ? flattenChildren(row) : null;\n const element = inner?.length === 1 ? { ...inner[0]!, key: row.key } : row;\n if (element.type === Section) return element;\n if (element.type === Row) return { ...element, props: { ...(element.props as RowProps), containerIndex } };\n const props = element.props as { tag?: unknown; value?: unknown };\n const tag = props.tag !== undefined ? props.tag : element.type === NavigationLink ? props.value : undefined;\n if (tag === undefined) return element;\n return (\n <Row key={element.key ?? containerIndex} tag={tag} containerIndex={containerIndex}>\n {element}\n </Row>\n );\n}\n\nfunction withKey(element: ReactElement, index: number): ReactElement {\n return element.key !== null ? element : { ...element, key: String(index) };\n}\n\nfunction supplement(node: ReactNode): { text: string | null; view: ReactElement | null } {\n if (node === undefined || node === null || node === false) return { text: null, view: null };\n if (typeof node === 'string' || typeof node === 'number') return { text: String(node), view: null };\n if (isValidElement(node) && node.type === Text) {\n const props = node.props as { children?: ReactNode };\n const only = Object.keys(props).every((key) => key === 'children');\n if (only) return { text: plainText(node), view: null };\n }\n return { text: null, view: isValidElement(node) ? node : null };\n}\n","import { useState, type ReactNode } from 'react';\nimport { readBinding, type BindingValue } from '../binding';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, takeModifier, type ViewModifiers } from '../modifiers';\nimport { flattenChildren } from './stacks';\n\nexport interface TabViewProps<T> extends ViewModifiers {\n selection?: BindingValue<T>;\n onChange?: (value: T) => void;\n /** `<Tab>` children. */\n children?: ReactNode;\n}\n\nexport function TabView<T = number>(props: TabViewProps<T>): ReactNode {\n const { own, modifiers } = splitProps(props);\n const tabs = flattenChildren(own.children);\n const tags = tabs.map((tab, index) => {\n const tag = (tab.props as { tag?: T }).tag;\n return (tag !== undefined ? tag : index) as T;\n });\n const [internal, setInternal] = useState<T>(tags[0] as T);\n const [selection, setSelection] = own.selection !== undefined ? readBinding(own.selection, own.onChange) : [internal, setInternal];\n const selected = Math.max(\n 0,\n tags.findIndex((tag) => Object.is(tag, selection)),\n );\n return applyModifiers(\n sb('tabview', { selected }, { select: (event) => tags[event.value] !== undefined && setSelection(tags[event.value] as T) }, tabs),\n modifiers,\n );\n}\n\nexport interface TabProps<T> extends ViewModifiers {\n title: string;\n systemImage?: string;\n /** An asset catalog image (a custom symbol), as `Tab(\"Backyards\", image: \"fountain\")`; used when there is no `systemImage`. */\n image?: string;\n role?: 'search';\n tag?: T;\n children?: ReactNode;\n}\n\n/** `Tab(\"Library\", systemImage: \"books.vertical\") { }`, or `Tab(\"Backyards\", image: \"fountain\") { }` */\nexport function Tab<T>(props: TabProps<T>): ReactNode {\n const { own, modifiers } = splitProps(props);\n const badge = takeModifier(modifiers, 'badge');\n const tabProps: Record<string, unknown> = { title: own.title, systemImage: own.systemImage ?? null };\n if (badge !== undefined && badge !== null) tabProps['badge'] = String(badge);\n if (own.role) tabProps['role'] = own.role;\n if (own.image && !own.systemImage) tabProps['image'] = own.image;\n return applyModifiers(sb('tab', tabProps, undefined, own.children), modifiers);\n}\n","/**\n * `Host`: ordinary React DOM inside a SwiftUI tree. The children render in a\n * react-dom root of their own, inside a `host` element the layout engine\n * sizes (docs/ops-protocol.md, \"Host elements\"): by its content, like text,\n * or filling its proposal. The DOM content sees this package's contexts\n * (`useDismiss`, `useNavigation`, the environment) and any it names.\n */\n\nimport { notifyHostContentChange, registerHostContent, unregisterHostContent } from '@swiftbrowser/web/src/hostContent';\nimport { useEffect, useId, useLayoutEffect, useRef, useState, type CSSProperties, type Context, type ReactNode } from 'react';\nimport { createRoot, type Root } from 'react-dom/client';\nimport { flushSync } from 'react-dom';\nimport { useContextBridge } from '../bridge';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, type ViewModifiers } from '../modifiers';\n\nexport interface HostProps extends ViewModifiers {\n /**\n * `content` (the default): the box is as wide as the content wants, at most\n * the proposed width, and as tall as the content at that width. `fill`:\n * the box takes the proposal (combine with `frame`); the content fills it.\n */\n sizing?: 'fill' | 'content';\n /** Contexts of the SwiftUI tree the DOM content reads (this package's own always cross). */\n contexts?: readonly Context<unknown>[];\n className?: string;\n style?: CSSProperties;\n children?: ReactNode;\n}\n\nexport function Host(props: HostProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const key = useId();\n // The content element, one per mount. It is registered from the effects\n // below, not here: StrictMode runs this initializer twice and keeps one\n // result, and a registration made here would name the other.\n const [content] = useState<HTMLElement | null>(() => {\n if (typeof document === 'undefined') return null;\n const element = document.createElement('div');\n element.className = 'sb-host-content';\n return element;\n });\n const bridge = useContextBridge(own.contexts);\n const root = useRef<Root | null>(null);\n const mounted = useRef(false);\n // In `fill` sizing the wrapper is as tall as the box, so percentage\n // heights in the content (`height: 100%`) reach it.\n const sizing = own.sizing ?? 'content';\n const style: CSSProperties | undefined = sizing === 'fill' ? { height: '100%', ...own.style } : own.style;\n const tree = bridge(\n <div className={own.className} style={style}>\n {own.children}\n </div>,\n );\n\n useLayoutEffect(() => {\n if (!content) return;\n mounted.current = true;\n // After the commit that created the `host` element: the renderer adopts a\n // content registered late at the change notice below. Registered again\n // after StrictMode's simulated unmount, which unregistered it.\n registerHostContent(key, content);\n root.current ??= createRoot(content);\n const current = root.current;\n // In a microtask: still before the browser paints, but outside any commit\n // react-dom may be in the middle of (a `SwiftUIView` is one of its\n // components). The synchronous render lets the engine measure the new\n // content right away, and the tree is laid out again around it.\n queueMicrotask(() => {\n if (root.current !== current) return;\n flushSync(() => current.render(tree));\n notifyHostContentChange(key);\n });\n });\n\n useEffect(\n () => () => {\n mounted.current = false;\n unregisterHostContent(key);\n // Not inside the SwiftUI root's commit; and not at all when the host\n // mounted again meanwhile (StrictMode's simulated remount keeps the root).\n queueMicrotask(() => {\n if (mounted.current) return;\n const current = root.current;\n root.current = null;\n current?.unmount();\n });\n },\n [key],\n );\n\n return applyModifiers(sb('host', { content: key, sizing }), modifiers);\n}\n","/**\n * `RegisteredView`: a view a package draws itself, named as the package\n * registered it with `ViewRegistry`: in a native app a SwiftUI view\n * (SwiftBrowserNative's `ViewRegistry.register(name) { context in … }`), on\n * a page the package's own DOM (`ViewRegistry.register(name, (context) =>\n * …)`, from @swiftbrowser/web). One element on both, for what a package\n * draws from data that never crosses the bridge: an audio node's frames\n * (`ScopeView` in @swiftbrowser/dsp), a map's tiles, a camera's preview.\n * It takes the size it is given (`frame`, a stack's proposal), as\n * `GeometryReader` does.\n *\n * ```tsx\n * <RegisteredView name=\"Meter\" props={{ level }} onEvent={(value) => …} frame={{ height: 40 }} />\n * ```\n */\n\nimport type { ReactNode } from 'react';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, type ViewModifiers } from '../modifiers';\n\nexport { ViewRegistry, type RegisteredViewBuilder, type RegisteredViewContext, type RegisteredViewInstance } from '@swiftbrowser/web/src/viewRegistry';\n\nexport interface RegisteredViewProps extends ViewModifiers {\n /** The name the view is registered under, on each platform. */\n name: string;\n /** JSON-serializable props for the view. */\n props?: Record<string, unknown>;\n /** A value the view sent (`context.send(value)`). */\n onEvent?: (value: unknown) => void;\n /** Views for the native view to place (`context.content`); a page's view has none. */\n children?: ReactNode;\n}\n\nexport function RegisteredView(all: RegisteredViewProps): ReactNode {\n const { own, modifiers } = splitProps(all);\n const on = own.onEvent ? { registered: (event: { value: unknown }) => own.onEvent!(event.value) } : undefined;\n return applyModifiers(sb('registered', { name: own.name, props: own.props ?? {} }, on, own.children), modifiers);\n}\n","import { Fragment, type ReactNode } from 'react';\nimport { readBinding, type BindingValue } from '../binding';\nimport { withEnvironment } from '../environment';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, type ViewModifiers } from '../modifiers';\nimport { Button } from './controls';\nimport { Text } from './text';\n\nexport interface MenuProps extends ViewModifiers {\n /** The label: a title, or any view. */\n title?: string;\n label?: ReactNode;\n /** The items: buttons, pickers, dividers, sections, texts, nested menus. */\n children?: ReactNode;\n}\n\n/** `Menu(\"Sort\") { … }`: the label opens a popover of the items. */\nexport function Menu(props: MenuProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const label = own.title !== undefined ? <Text>{own.title}</Text> : own.label;\n // The items' labels show title and icon even in a bar, whose own labels\n // are icons (a filter menu's checked entries), as a menu's do on iOS.\n const items = withEnvironment({ labelStyle: 'automatic' }, own.children);\n return applyModifiers(\n sb('menu', {}, undefined, [\n <Fragment key=\"label\">{sb('zstack', { alignment: 'center' }, undefined, label)}</Fragment>,\n <Fragment key=\"items\">{items}</Fragment>,\n ]),\n modifiers,\n );\n}\n\nexport interface EditButtonProps extends ViewModifiers {\n /** The list's edit mode (`List editing={…}`). */\n editMode: BindingValue<boolean>;\n onChange?: (editing: boolean) => void;\n}\n\n/** `EditButton()`: \"Edit\" / \"Done\", flipping the edit mode it is given. */\nexport function EditButton(props: EditButtonProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const [editing, setEditing] = readBinding(own.editMode, own.onChange);\n return applyModifiers(<Button title={editing ? 'Done' : 'Edit'} editMode={editing ? 'active' : 'inactive'} action={() => setEditing(!editing)} />, modifiers);\n}\n","import { loadableURL } from '@swiftbrowser/web/src/hostRequests';\nimport { useEffect, useState, type ReactNode } from 'react';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, type ViewModifiers } from '../modifiers';\nimport { ZStack } from './stacks';\n\n/** How long a load runs before `loadingIndicator` shows. */\nexport const LOADING_INDICATOR_DELAY_MS = 300;\n\nexport interface AsyncImageProps extends ViewModifiers {\n url: string;\n /** `.resizable()` on the loaded image. */\n resizable?: boolean;\n /**\n * Shown until the image loaded (nothing by default). The image's modifiers\n * (its frame, aspect ratio, corner radius) apply to it as they do to the\n * picture, as a SwiftUI `AsyncImage`'s do in every phase: a framed image\n * keeps its box while it loads, so the row beside it does not move.\n */\n placeholder?: ReactNode;\n /** Shown when the image failed to load (the placeholder by default), under the same modifiers. */\n failure?: ReactNode;\n /**\n * Shown over the placeholder once a load has run for `loadingIndicatorDelay`\n * ms (300 by default): a `<ProgressView />` for a big picture on a slow\n * connection, nothing for one that comes quickly or from the cache.\n */\n loadingIndicator?: ReactNode;\n loadingIndicatorDelay?: number;\n /**\n * Keep the browser's own image interactions: a long press's Save / Share /\n * Copy on iOS, dragging the image out, the right-click menu. Off by\n * default, as a SwiftUI image is inert; for an image with no tap, gesture\n * or context menu of its own.\n */\n webInteractions?: boolean;\n /** `.accessibilityLabel(_:)`: what the picture shows (alt text). */\n accessibilityLabel?: string | undefined;\n}\n\ninterface Loaded {\n url: string;\n width: number;\n height: number;\n}\n\nconst loaded = new Map<string, Loaded | 'failed'>();\n\n/**\n * In a SwiftBrowser Native app: JavaScriptCore with the native bridge and no\n * DOM, so no `Image` to load with. (A page has `Image`, the native round\n * trip's included; a server render or a test has no bridge.)\n */\nfunction inNativeApp(): boolean {\n return typeof Image === 'undefined' && (globalThis as { __sbNative?: unknown }).__sbNative !== undefined;\n}\n\n/**\n * `AsyncImage(url:)`: the page loads the image to learn its size (the\n * engine lays a remote image out by its pixel size, as the Swift core does\n * after its `image` request), then shows it. A SwiftBrowser Native app's\n * runtime gives it an `Image` too (@swiftbrowser/native's image.ts, over\n * the host's image loader), so the placeholder shows there as well; on a\n * host without one the URL goes to the renderer at once and SwiftUI's own\n * `AsyncImage` loads it.\n */\nexport function AsyncImage(props: AsyncImageProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const [state, setState] = useState<Loaded | 'failed' | null>(() => loaded.get(own.url) ?? null);\n useEffect(() => {\n const cached = loaded.get(own.url);\n if (cached) {\n setState(cached);\n return;\n }\n if (typeof Image === 'undefined') return;\n let live = true;\n const image = new Image();\n image.onload = () => {\n const result: Loaded = { url: own.url, width: image.naturalWidth, height: image.naturalHeight };\n loaded.set(own.url, result);\n if (live) setState(result);\n };\n image.onerror = () => {\n loaded.set(own.url, 'failed');\n if (live) setState('failed');\n };\n // A `file:` URL of the app's files probes at its object URL.\n const src = loadableURL(own.url);\n if (typeof src === 'string') image.src = src;\n else void src.then((resolved) => live && (image.src = resolved));\n return () => {\n live = false;\n };\n }, [own.url]);\n // The indicator, once a load has taken its while.\n const hasIndicator = own.loadingIndicator !== undefined && own.loadingIndicator !== null;\n const delay = own.loadingIndicatorDelay ?? LOADING_INDICATOR_DELAY_MS;\n const [slow, setSlow] = useState(false);\n useEffect(() => {\n if (state !== null || !hasIndicator) {\n setSlow(false);\n return;\n }\n const timer = setTimeout(() => setSlow(true), delay);\n return () => clearTimeout(timer);\n }, [state, hasIndicator, delay]);\n if (inNativeApp()) {\n return applyModifiers(sb('image', { ...imageProps(own), url: own.url, width: 0, height: 0 }), modifiers);\n }\n // Before the picture: what the app shows for the phase, or an empty stack\n // (no size of its own), under the image's modifiers, so a frame or an\n // aspect ratio holds the picture's box.\n if (state === null) {\n const placeholder = own.placeholder ?? <ZStack />;\n const shown =\n slow && hasIndicator ? (\n <ZStack>\n {placeholder}\n {own.loadingIndicator}\n </ZStack>\n ) : (\n placeholder\n );\n return applyModifiers(shown, modifiers);\n }\n if (state === 'failed') return applyModifiers(own.failure ?? own.placeholder ?? <ZStack />, modifiers);\n return applyModifiers(sb('image', { ...imageProps(own), url: state.url, width: state.width, height: state.height }), modifiers);\n}\n\n/** The `image` element's props besides its URL and size. */\nfunction imageProps(own: AsyncImageProps): Record<string, unknown> {\n return {\n resizable: own.resizable ?? false,\n ...(own.webInteractions ? { webInteractions: true } : {}),\n ...(own.accessibilityLabel ? { accessibilityLabel: own.accessibilityLabel } : {}),\n };\n}\n","/**\n * Swift Charts: `Chart` with bar, line, area, point and rule marks. The\n * marks are declarations; `Chart` reads them, builds the scales (bands for\n * categories, \"nice\" numeric domains, calendar strides for dates), turns\n * every value into the protocol's unit coordinates and emits one `chart`\n * element with its axes and legend, as Sources/SwiftUI/Charts does.\n */\n\nimport type {\n ChartAxis,\n ChartInterpolation,\n ChartLegend,\n ChartMark,\n ChartSymbol,\n FrameAlignment,\n ShapeStyle,\n} from '@swiftbrowser/web/src/protocol';\nimport { Fragment, type ReactElement, type ReactNode } from 'react';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, type ViewModifiers } from '../modifiers';\nimport { shapeStyle, type StyleValue } from '../values';\nimport { flattenChildren } from './stacks';\n\nexport type ChartValue = number | Date | string;\n\nexport interface AnnotationSpec {\n position?: 'top' | 'bottom' | 'leading' | 'trailing' | 'overlay';\n alignment?: FrameAlignment;\n spacing?: number;\n content: ReactNode;\n}\n\ninterface MarkCommon {\n foregroundStyle?: StyleValue;\n /** `.foregroundStyle(by:)`: a series name; the palette colors it and the legend lists it. */\n foregroundStyleBy?: string;\n opacity?: number;\n /** `.annotation(position:alignment:spacing:) { }` */\n annotation?: AnnotationSpec;\n}\n\nexport interface BarMarkProps extends MarkCommon {\n x: ChartValue;\n y: ChartValue;\n /** `yStart:` (0 by default). */\n yStart?: number;\n cornerRadius?: number;\n /** `width: .fixed(points)` */\n width?: number;\n /**\n * `.position(by:)`: bars at the same `x` side by side, one slot of the\n * band per value (in first-seen order across the chart's bars).\n */\n positionBy?: string;\n}\nexport interface LineMarkProps extends MarkCommon {\n x: ChartValue;\n y: number;\n series?: string;\n interpolation?: ChartInterpolation;\n lineWidth?: number;\n symbol?: ChartSymbol;\n symbolSize?: number;\n}\nexport interface AreaMarkProps extends MarkCommon {\n x: ChartValue;\n y: number;\n yStart?: number;\n series?: string;\n interpolation?: ChartInterpolation;\n}\nexport interface PointMarkProps extends MarkCommon {\n x: ChartValue;\n y: number;\n symbol?: ChartSymbol;\n symbolSize?: number;\n}\nexport interface RuleMarkProps extends MarkCommon {\n /** A vertical rule at `x`, or a horizontal one at `y`. */\n x?: ChartValue;\n y?: number;\n xStart?: ChartValue;\n xEnd?: ChartValue;\n yStart?: number;\n yEnd?: number;\n lineWidth?: number;\n}\n\n/** The marks render nothing themselves; `Chart` reads them. */\nexport function BarMark(_props: BarMarkProps): null {\n return null;\n}\nexport function LineMark(_props: LineMarkProps): null {\n return null;\n}\nexport function AreaMark(_props: AreaMarkProps): null {\n return null;\n}\nexport function PointMark(_props: PointMarkProps): null {\n return null;\n}\nexport function RuleMark(_props: RuleMarkProps): null {\n return null;\n}\n\nexport interface ChartProps extends ViewModifiers {\n /** `.chartXAxis(.hidden)` is `null`; the position otherwise. */\n xAxis?: 'bottom' | 'top' | null;\n yAxis?: 'trailing' | 'leading' | null;\n /** `.chartLegend`: the position, or `null` to hide it. Shown at the top when a series exists. */\n legend?: 'top' | 'bottom' | 'leading' | 'trailing' | null;\n /** `.chartXScale(domain:)`: numbers, dates or the categories in order. */\n xScale?: { domain?: readonly [ChartValue, ChartValue] | readonly string[] };\n /** `.chartYScale(domain:)`; `includesZero` is true by default, as in Swift Charts. */\n yScale?: { domain?: readonly [number, number]; includesZero?: boolean };\n /** `.chartYAxis { AxisMarks(format:) }`: the text of a numeric axis's labels (`(v) => `$${v}``). */\n yAxisFormat?: (value: number) => string;\n children?: ReactNode;\n}\n\nconst PALETTE = ['blue', 'green', 'orange', 'purple', 'red', 'teal', 'yellow', 'pink', 'indigo', 'mint', 'cyan', 'brown'] as const;\nconst SYMBOLS: ChartSymbol[] = ['circle', 'square', 'triangle', 'diamond', 'cross', 'plus', 'asterisk'];\n\ntype MarkKind = 'bar' | 'line' | 'area' | 'point' | 'rule';\ninterface Declared {\n kind: MarkKind;\n props: BarMarkProps & LineMarkProps & AreaMarkProps & PointMarkProps & RuleMarkProps;\n}\n\nfunction declaredMarks(children: ReactNode): Declared[] {\n const kinds = new Map<unknown, MarkKind>([\n [BarMark, 'bar'],\n [LineMark, 'line'],\n [AreaMark, 'area'],\n [PointMark, 'point'],\n [RuleMark, 'rule'],\n ]);\n const result: Declared[] = [];\n for (const element of flattenChildren(children)) {\n const kind = kinds.get(element.type);\n if (kind) result.push({ kind, props: element.props as Declared['props'] });\n }\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Scales\n// ---------------------------------------------------------------------------\n\ninterface Scale {\n /** Unit position of a value along the axis (0 → 1 left to right / bottom to top). */\n unit(value: ChartValue): number;\n /** The band of a category, or the band around a continuous center. */\n band(value: ChartValue): [number, number];\n ticks: number[];\n gridLines: number[];\n labels: { at: number; text: string; anchor?: 'leading' }[];\n domain: [number, number];\n kind: 'band' | 'number' | 'time';\n}\n\nconst asNumber = (value: ChartValue): number => (value instanceof Date ? value.getTime() : typeof value === 'number' ? value : NaN);\n\nfunction bandScale(categories: string[]): Scale {\n const n = Math.max(categories.length, 1);\n const index = new Map(categories.map((c, i) => [c, i]));\n const center = (value: ChartValue): number => ((index.get(String(value)) ?? 0) + 0.5) / n;\n return {\n kind: 'band',\n unit: center,\n band: (value) => {\n const i = index.get(String(value)) ?? 0;\n return [i / n, (i + 1) / n];\n },\n ticks: categories.map((_, i) => (i + 0.5) / n),\n gridLines: [],\n labels: categories.map((text, i) => ({ at: (i + 0.5) / n, text })),\n domain: [0, n],\n };\n}\n\n/** Steps of 1, 2, 2.5, 5 × 10ᵏ, the one nearest `span / (desired − 1)`. */\nexport function niceStep(span: number, desired = 5): number {\n if (!(span > 0)) return 1;\n const raw = span / Math.max(desired - 1, 1);\n const magnitude = 10 ** Math.floor(Math.log10(raw));\n let best = magnitude;\n // A tie goes to the larger step (fewer ticks).\n for (const candidate of [1, 2, 2.5, 5, 10].map((m) => m * magnitude)) {\n if (Math.abs(candidate - raw) <= Math.abs(best - raw)) best = candidate;\n }\n return best;\n}\n\nfunction decimalsOf(step: number): number {\n const text = step.toString();\n const dot = text.indexOf('.');\n return dot < 0 ? 0 : text.length - dot - 1;\n}\n\nfunction numberScale(values: number[], options: { includesZero?: boolean | undefined; domain?: readonly [number, number] | undefined } = {}): Scale {\n let min = Math.min(...values);\n let max = Math.max(...values);\n if (!Number.isFinite(min) || !Number.isFinite(max)) {\n min = 0;\n max = 1;\n }\n if (options.includesZero) {\n min = Math.min(min, 0);\n max = Math.max(max, 0);\n }\n if (min === max) {\n if (min === 0) max = 1;\n else {\n min = Math.min(min, 0);\n max = Math.max(max, 0);\n if (min === max) max = min + 1;\n }\n }\n const step = niceStep(max - min);\n let lo: number;\n let hi: number;\n if (options.domain) [lo, hi] = options.domain;\n else {\n lo = Math.floor(min / step + 1e-9) * step;\n hi = Math.ceil(max / step - 1e-9) * step;\n }\n const ticks: number[] = [];\n const first = Math.ceil(lo / step - 1e-9) * step;\n for (let value = first; value <= hi + 1e-9; value += step) ticks.push(Number(value.toFixed(10)));\n const decimals = decimalsOf(step);\n const unit = (value: ChartValue): number => (asNumber(value) - lo) / (hi - lo || 1);\n const format = new Intl.NumberFormat('en-US', { maximumFractionDigits: decimals });\n return {\n kind: 'number',\n unit,\n band: (value) => [unit(value), unit(value)],\n ticks: ticks.map(unit),\n gridLines: ticks.map(unit),\n labels: ticks.map((value) => ({ at: unit(value), text: format.format(value) })),\n domain: [lo, hi],\n };\n}\n\nconst HOUR = 3_600_000;\nconst DAY = 24 * HOUR;\nconst MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\n\n/** Calendar ticks in UTC, with the stride that gives at most `desired + 1` intervals. */\nexport function timeTicks(min: number, max: number, desired = 8): { ticks: number[]; format: (ms: number) => string } {\n const span = Math.max(max - min, 1);\n const pick = (strides: number[], unit: number): number => strides.find((s) => span / (s * unit) <= desired + 1) ?? strides[strides.length - 1]!;\n const ticks: number[] = [];\n if (span <= 3 * DAY) {\n const hours = pick([1, 3, 6, 12], HOUR);\n const start = Math.floor(min / (hours * HOUR)) * hours * HOUR;\n for (let t = start; t <= max; t += hours * HOUR) if (t >= min) ticks.push(t);\n return {\n ticks,\n format: (ms) => {\n const h = new Date(ms).getUTCHours();\n const minute = new Date(ms).getUTCMinutes();\n const suffix = h < 12 ? 'AM' : 'PM';\n const hour12 = h % 12 === 0 ? 12 : h % 12;\n return minute === 0 ? `${hour12} ${suffix}` : `${hour12}:${String(minute).padStart(2, '0')} ${suffix}`;\n },\n };\n }\n if (span <= 45 * DAY) {\n const days = pick([1, 2, 7, 14], DAY);\n const start = Math.floor(min / DAY) * DAY;\n for (let t = start; t <= max; t += days * DAY) if (t >= min) ticks.push(t);\n return { ticks, format: (ms) => `${MONTHS[new Date(ms).getUTCMonth()]} ${new Date(ms).getUTCDate()}` };\n }\n const months = span / (30.4 * DAY);\n if (months <= 6 * (desired + 1)) {\n const stride = pick([1, 2, 3, 6], 30.4 * DAY);\n const first = new Date(min);\n let year = first.getUTCFullYear();\n let month = Math.floor(first.getUTCMonth() / stride) * stride;\n for (;;) {\n const t = Date.UTC(year, month, 1);\n if (t > max) break;\n if (t >= min) ticks.push(t);\n month += stride;\n if (month >= 12) {\n month -= 12;\n year += 1;\n }\n }\n const years = new Set(ticks.map((t) => new Date(t).getUTCFullYear()));\n return {\n ticks,\n format: (ms) => {\n const d = new Date(ms);\n return years.size > 1 ? `${MONTHS[d.getUTCMonth()]} ${d.getUTCFullYear()}` : MONTHS[d.getUTCMonth()]!;\n },\n };\n }\n const stride = pick([1, 2, 5, 10], 365.25 * DAY);\n const startYear = Math.floor(new Date(min).getUTCFullYear() / stride) * stride;\n for (let year = startYear; ; year += stride) {\n const t = Date.UTC(year, 0, 1);\n if (t > max) break;\n if (t >= min) ticks.push(t);\n }\n return { ticks, format: (ms) => String(new Date(ms).getUTCFullYear()) };\n}\n\nfunction timeScale(values: number[], domain?: readonly [ChartValue, ChartValue]): Scale {\n let lo = domain ? asNumber(domain[0]) : Math.min(...values);\n let hi = domain ? asNumber(domain[1]) : Math.max(...values);\n if (!Number.isFinite(lo) || !Number.isFinite(hi)) {\n lo = 0;\n hi = DAY;\n }\n if (lo === hi) hi = lo + DAY;\n const { ticks, format } = timeTicks(lo, hi);\n const unit = (value: ChartValue): number => (asNumber(value) - lo) / (hi - lo);\n return {\n kind: 'time',\n unit,\n band: (value) => [unit(value), unit(value)],\n ticks: ticks.map(unit),\n gridLines: ticks.map(unit),\n labels: ticks.map((t) => ({ at: unit(t), text: format(t), anchor: 'leading' as const })),\n domain: [lo, hi],\n };\n}\n\nfunction scaleFor(values: ChartValue[], options: { includesZero?: boolean | undefined; domain?: (ChartProps['xScale'] extends infer S ? (S extends { domain?: infer D } ? D : never) : never) | undefined }): Scale {\n const domain = options.domain;\n if (domain && domain.length > 2) return bandScale([...(domain as readonly string[])]);\n if (domain && domain.length === 2 && typeof domain[0] === 'string') return bandScale([...(domain as readonly string[])]);\n if (values.some((v) => typeof v === 'string')) {\n const categories: string[] = [];\n for (const v of values) if (!categories.includes(String(v))) categories.push(String(v));\n return bandScale(categories);\n }\n if (values.some((v) => v instanceof Date)) return timeScale(values.map(asNumber), domain as readonly [ChartValue, ChartValue] | undefined);\n return numberScale(values.map(asNumber), { includesZero: options.includesZero, domain: domain as readonly [number, number] | undefined });\n}\n\n// ---------------------------------------------------------------------------\n// Chart\n// ---------------------------------------------------------------------------\n\nexport function Chart(props: ChartProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const marks = declaredMarks(own.children);\n\n // Series, in first-seen order, colored from the palette.\n const series: string[] = [];\n for (const mark of marks) {\n const key = mark.props.foregroundStyleBy;\n if (key !== undefined && !series.includes(key)) series.push(key);\n }\n const styleOf = (mark: Declared): ShapeStyle => {\n if (mark.props.foregroundStyle !== undefined) return shapeStyle(mark.props.foregroundStyle);\n const key = mark.props.foregroundStyleBy;\n if (key !== undefined) return { name: PALETTE[series.indexOf(key) % PALETTE.length]! };\n return { name: 'blue' };\n };\n\n // Scales from every value a mark touches.\n const xValues: ChartValue[] = [];\n const yValues: ChartValue[] = [];\n for (const { kind, props: p } of marks) {\n if (p.x !== undefined) xValues.push(p.x);\n if (p.xStart !== undefined) xValues.push(p.xStart);\n if (p.xEnd !== undefined) xValues.push(p.xEnd);\n if (p.y !== undefined) yValues.push(p.y);\n if (p.yStart !== undefined) yValues.push(p.yStart);\n if (p.yEnd !== undefined) yValues.push(p.yEnd);\n if (kind === 'bar' || kind === 'area') yValues.push(p.yStart ?? 0);\n }\n const xScale = scaleFor(xValues, { domain: own.xScale?.domain });\n const yScale = scaleFor(yValues, { includesZero: own.yScale?.includesZero ?? true, domain: own.yScale?.domain });\n if (own.yAxisFormat && yScale.kind === 'number') {\n const [lo, hi] = yScale.domain;\n const format = own.yAxisFormat;\n yScale.labels = yScale.labels.map((label) => ({ ...label, text: format(Number((lo + label.at * (hi - lo)).toFixed(10))) }));\n }\n // Unit coordinates, rounded so equal values compare equal.\n const round = (n: number): number => Math.round(n * 1e6) / 1e6;\n const ux = (v: ChartValue): number => round(xScale.unit(v));\n const uy = (v: ChartValue): number => round(1 - yScale.unit(v));\n\n // Bars on a continuous x axis: the band is the smallest gap between centers.\n let continuousBand = 1;\n if (xScale.kind !== 'band') {\n const centers = [...new Set(marks.filter((m) => m.kind === 'bar').map((m) => ux(m.props.x)))].sort((a, b) => a - b);\n for (let i = 1; i < centers.length; i++) continuousBand = Math.min(continuousBand, centers[i]! - centers[i - 1]!);\n }\n\n // `.position(by:)`: each value a slot of the bar's band, in first-seen order.\n const positions: string[] = [];\n for (const mark of marks) {\n const key = mark.kind === 'bar' ? mark.props.positionBy : undefined;\n if (key !== undefined && !positions.includes(key)) positions.push(key);\n }\n\n const encoded: ChartMark[] = [];\n const items: ReactElement[] = [];\n const annotate = (mark: Declared, rect: { x0: number; x1: number; y0: number; y1: number }): void => {\n const annotation = mark.props.annotation;\n if (!annotation) return;\n items.push(\n <Fragment key={items.length}>\n {sb(\n 'chartitem',\n {\n role: 'annotation',\n ...rect,\n position: annotation.position ?? 'top',\n alignment: annotation.alignment ?? 'center',\n spacing: annotation.spacing ?? 4,\n },\n undefined,\n annotation.content,\n )}\n </Fragment>,\n );\n };\n const common = (mark: Declared): { style: ShapeStyle; opacity?: number } => {\n const base: { style: ShapeStyle; opacity?: number } = { style: styleOf(mark) };\n if (mark.props.opacity !== undefined) base.opacity = mark.props.opacity;\n return base;\n };\n\n // Lines and areas group by series key, in first-seen order, points in x order.\n const groups = new Map<string, Declared[]>();\n for (const mark of marks) {\n if (mark.kind !== 'line' && mark.kind !== 'area') continue;\n const key = `${mark.kind}:${mark.props.series ?? mark.props.foregroundStyleBy ?? ''}`;\n const group = groups.get(key);\n if (group) group.push(mark);\n else groups.set(key, [mark]);\n }\n const emittedGroups = new Set<string>();\n\n for (const mark of marks) {\n const p = mark.props;\n switch (mark.kind) {\n case 'bar': {\n const style = common(mark);\n let [b0, b1] = xScale.kind === 'band' ? xScale.band(p.x) : [ux(p.x) - continuousBand / 2, ux(p.x) + continuousBand / 2];\n if (p.positionBy !== undefined && positions.length > 1) {\n // The bars of a group share 80% of the band, each 90% of its slot.\n const slot = ((b1 - b0) * 0.8) / positions.length;\n const start = b0 + (b1 - b0) * 0.1 + slot * positions.indexOf(p.positionBy);\n [b0, b1] = [start - slot / 16, start + slot + slot / 16];\n }\n const center = round((b0 + b1) / 2);\n const half = round(((b1 - b0) * 0.8) / 2);\n const top = uy(Math.max(asNumber(p.y), p.yStart ?? 0));\n const bottom = uy(Math.min(asNumber(p.y), p.yStart ?? 0));\n const rect: ChartMark = {\n kind: 'rect',\n ...style,\n x0: p.width !== undefined ? center : round(center - half),\n x1: p.width !== undefined ? center : round(center + half),\n y0: top,\n y1: bottom,\n cornerRadius: p.cornerRadius ?? 0,\n fixedWidth: p.width ?? null,\n };\n encoded.push(rect);\n annotate(mark, { x0: rect.x0, x1: rect.x1, y0: top, y1: bottom });\n break;\n }\n case 'line':\n case 'area': {\n const key = `${mark.kind}:${p.series ?? p.foregroundStyleBy ?? ''}`;\n if (emittedGroups.has(key)) {\n annotate(mark, { x0: ux(p.x), x1: ux(p.x), y0: uy(p.y), y1: uy(p.y) });\n break;\n }\n emittedGroups.add(key);\n const group = [...groups.get(key)!].sort((a, b) => ux(a.props.x) - ux(b.props.x));\n const first = group[0]!;\n if (mark.kind === 'line') {\n const line: ChartMark = {\n kind: 'line',\n ...common(first),\n points: group.map((m) => ({ x: ux(m.props.x), y: uy(m.props.y) })),\n lineWidth: first.props.lineWidth ?? 2,\n interpolation: first.props.interpolation ?? 'linear',\n symbol: first.props.symbol ?? (first.props.foregroundStyleBy !== undefined && marks.some((m) => m.props.symbol) ? SYMBOLS[series.indexOf(first.props.foregroundStyleBy) % SYMBOLS.length]! : null),\n symbolSize: first.props.symbolSize ?? 8,\n };\n encoded.push(line);\n } else {\n const area: ChartMark = {\n kind: 'area',\n ...common(first),\n points: group.map((m) => ({\n x: ux(m.props.x),\n y0: uy(Math.max(m.props.y, m.props.yStart ?? 0)),\n y1: uy(Math.min(m.props.y, m.props.yStart ?? 0)),\n })),\n interpolation: first.props.interpolation ?? 'linear',\n };\n encoded.push(area);\n }\n annotate(mark, { x0: ux(p.x), x1: ux(p.x), y0: uy(p.y), y1: uy(p.y) });\n break;\n }\n case 'point': {\n const point: ChartMark = { kind: 'point', ...common(mark), x: ux(p.x), y: uy(p.y), symbol: p.symbol ?? 'circle', symbolSize: p.symbolSize ?? 8 };\n encoded.push(point);\n annotate(mark, { x0: point.x, x1: point.x, y0: point.y, y1: point.y });\n break;\n }\n case 'rule': {\n const vertical = p.x !== undefined;\n const rule: ChartMark = {\n kind: 'rule',\n ...common(mark),\n x0: vertical ? ux(p.x!) : p.xStart !== undefined ? ux(p.xStart) : 0,\n x1: vertical ? ux(p.x!) : p.xEnd !== undefined ? ux(p.xEnd) : 1,\n y0: vertical ? (p.yEnd !== undefined ? uy(p.yEnd) : 0) : uy(p.y ?? 0),\n y1: vertical ? (p.yStart !== undefined ? uy(p.yStart) : 1) : uy(p.y ?? 0),\n lineWidth: p.lineWidth ?? 1,\n };\n encoded.push(rule);\n annotate(mark, { x0: rule.x0, x1: rule.x1, y0: rule.y0, y1: rule.y1 });\n break;\n }\n default:\n break;\n }\n }\n\n const axis = (scale: Scale, position: ChartAxis['position'], flipY: boolean): ChartAxis => {\n const flip = (u: number): number => round(flipY ? 1 - u : u);\n return {\n position,\n gridLines: scale.gridLines.map(flip),\n ticks: scale.ticks.map(flip),\n labels: scale.labels.map((label) => ({ ...label, at: flip(label.at) })),\n // Swift Charts dashes a date axis's grid lines.\n ...(scale.kind === 'time' ? { dashed: true as const } : {}),\n };\n };\n const chartProps = {\n marks: encoded,\n xAxis: own.xAxis === null ? null : axis(xScale, own.xAxis ?? 'bottom', false),\n yAxis: own.yAxis === null ? null : axis(yScale, own.yAxis ?? 'trailing', true),\n legend:\n own.legend === null || series.length === 0\n ? null\n : ({\n position: own.legend ?? 'top',\n items: series.map((label, index) => ({ label, style: { name: PALETTE[index % PALETTE.length]! }, symbol: null })),\n } satisfies ChartLegend),\n };\n return applyModifiers(sb('chart', chartProps, undefined, items.length ? items : undefined), modifiers);\n}\n","/**\n * Gauges, `ViewThatFits`, lazy stacks, and the composite containers the\n * shim builds from other views: `ContentUnavailableView`, `GroupBox`,\n * `ControlGroup`, `DisclosureGroup`.\n */\n\nimport type { GaugeStyle, HStackAlignment, VStackAlignment } from '@swiftbrowser/web/src/protocol';\nimport { Fragment, useState, type ReactNode } from 'react';\nimport { LazyContext } from '../lazy';\nimport { readBinding, type BindingValue } from '../binding';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, styled, type ViewModifiers } from '../modifiers';\nimport { withAnimation } from '../host/root';\nimport { RoundedRectangle } from './shapes';\nimport { HStack, VStack, type PinnedViews } from './stacks';\nimport { Image, Text } from './text';\n\n// ---------------------------------------------------------------------------\n// Gauge\n// ---------------------------------------------------------------------------\n\nexport interface GaugeProps extends ViewModifiers {\n value: number;\n /** `in: 0...1` */\n range?: readonly [number, number];\n label?: ReactNode;\n currentValueLabel?: ReactNode;\n gaugeStyle?: Exclude<GaugeStyle, 'progress'>;\n}\n\n/** `Gauge(value:in:) { label } currentValueLabel: { }` */\nexport function Gauge(props: GaugeProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const [min, max] = own.range ?? [0, 1];\n const value = (own.value - min) / (max - min || 1);\n const children: ReactNode[] = [];\n const asView = (node: ReactNode): ReactNode => (typeof node === 'string' || typeof node === 'number' ? <Text>{node}</Text> : node);\n if (own.label !== undefined) children.push(<Fragment key=\"label\">{asView(own.label)}</Fragment>);\n if (own.currentValueLabel !== undefined) children.push(<Fragment key=\"current\">{asView(own.currentValueLabel)}</Fragment>);\n return applyModifiers(\n sb(\n 'gauge',\n {\n value: Math.min(1, Math.max(0, value)),\n style: own.gaugeStyle ?? 'automatic',\n hasLabel: own.label !== undefined,\n hasCurrentValueLabel: own.currentValueLabel !== undefined,\n },\n undefined,\n children.length ? children : undefined,\n ),\n modifiers,\n );\n}\n\n// ---------------------------------------------------------------------------\n// ViewThatFits\n// ---------------------------------------------------------------------------\n\nexport interface ViewThatFitsProps extends ViewModifiers {\n /** The axes a candidate must fit on (`in:`); both by default. */\n axes?: 'horizontal' | 'vertical' | 'both';\n /** The candidates, preferred first. */\n children?: ReactNode;\n}\n\n/** `ViewThatFits`: the first child whose ideal size fits, else the last. */\nexport function ViewThatFits(props: ViewThatFitsProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n return applyModifiers(sb('viewthatfits', { axes: own.axes ?? 'both' }, undefined, own.children), modifiers);\n}\n\n// ---------------------------------------------------------------------------\n// Lazy stacks\n// ---------------------------------------------------------------------------\n\n\nexport interface LazyVStackProps extends ViewModifiers {\n alignment?: VStackAlignment;\n spacing?: number | null;\n /** `.scrollTargetLayout()`: the children are the scroll view's snap points. */\n scrollTargetLayout?: boolean;\n /** `pinnedViews: [.sectionHeaders]`: each `Section`'s header stays at the top while its rows scroll by. */\n pinnedViews?: PinnedViews;\n children?: ReactNode;\n}\n\n/** `LazyVStack`: a `VStack` whose long `ForEach`es build their rows as they scroll into view. */\nexport function LazyVStack(props: LazyVStackProps): ReactNode {\n return (\n <LazyContext.Provider value=\"vertical\">\n <VStack {...props} />\n </LazyContext.Provider>\n );\n}\n\nexport interface LazyHStackProps extends ViewModifiers {\n alignment?: HStackAlignment;\n spacing?: number | null;\n scrollTargetLayout?: boolean;\n /** `pinnedViews: [.sectionHeaders]`: each `Section`'s header stays at the leading edge while its cells scroll by. */\n pinnedViews?: PinnedViews;\n children?: ReactNode;\n}\n\nexport function LazyHStack(props: LazyHStackProps): ReactNode {\n return (\n <LazyContext.Provider value=\"horizontal\">\n <HStack {...props} />\n </LazyContext.Provider>\n );\n}\n\n// ---------------------------------------------------------------------------\n// Composites\n// ---------------------------------------------------------------------------\n\nexport interface ContentUnavailableViewProps extends ViewModifiers {\n title: ReactNode;\n systemImage?: string;\n /** A string or a view. */\n description?: ReactNode;\n actions?: ReactNode;\n}\n\n/** `ContentUnavailableView(_:systemImage:description:)`: the empty state iOS shows, filling its space. */\nexport function ContentUnavailableView(props: ContentUnavailableViewProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const title = typeof own.title === 'string' ? <Text>{own.title}</Text> : own.title;\n const description = typeof own.description === 'string' ? <Text>{own.description}</Text> : own.description;\n return applyModifiers(\n <VStack spacing={16} padding={['horizontal', 32]} frame={{ maxWidth: Infinity, maxHeight: Infinity }}>\n <VStack spacing={8}>\n <VStack spacing={12}>\n {own.systemImage !== undefined && <Image systemName={own.systemImage} font={{ size: 48 }} foregroundStyle=\"secondary\" />}\n {styled({ multilineTextAlignment: 'center' }, styled({ font: { textStyle: 'title2', weight: 'bold' } }, title))}\n </VStack>\n {description !== undefined &&\n styled({ multilineTextAlignment: 'center' }, styled({ foreground: { hierarchical: 2 } }, styled({ font: { textStyle: 'callout' } }, description)))}\n </VStack>\n {own.actions}\n </VStack>,\n modifiers,\n );\n}\n\n/** `ContentUnavailableView.search(text:)` */\nContentUnavailableView.search = (text?: string): ReactNode => (\n <ContentUnavailableView\n title={text ? `No Results for “${text}”` : 'No Results'}\n systemImage=\"magnifyingglass\"\n description=\"Check the spelling or try a new search.\"\n />\n);\n\nexport interface GroupBoxProps extends ViewModifiers {\n label?: ReactNode;\n children?: ReactNode;\n}\n\n/** `GroupBox`: the label (headline) over the content, in a padded rounded box. */\nexport function GroupBox(props: GroupBoxProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const label = typeof own.label === 'string' ? <Text>{own.label}</Text> : own.label;\n return applyModifiers(\n <VStack\n alignment=\"leading\"\n spacing={8}\n padding={16}\n background={{ fill: 'secondarySystemBackground', in: <RoundedRectangle cornerRadius={8} /> }}\n >\n {label !== undefined && styled({ font: { textStyle: 'headline' } }, label)}\n {own.children}\n </VStack>,\n modifiers,\n );\n}\n\n/** `ControlGroup`: its controls, flowing in the enclosing stack (or items of their own in a menu). Its label is not drawn. */\nexport function ControlGroup(props: { label?: ReactNode; children?: ReactNode } & ViewModifiers): ReactNode {\n const { own, modifiers } = splitProps(props);\n return modifiers.length ? applyModifiers(<>{own.children}</>, modifiers) : own.children;\n}\n\nexport interface DisclosureGroupProps extends ViewModifiers {\n label: ReactNode;\n isExpanded?: BindingValue<boolean>;\n onExpandedChange?: (expanded: boolean) => void;\n children?: ReactNode;\n}\n\n/**\n * `DisclosureGroup`: a row with the label and a chevron that turns down as\n * the content opens below it. The `disclosuregroup` element carries\n * `expanded`, its label (first, in a `zstack`) and its content, which the\n * renderers show when expanded (the web renderer lays out the label alone\n * otherwise; the native renderer draws SwiftUI's own); a `tap` toggles.\n */\nexport function DisclosureGroup(props: DisclosureGroupProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const [internal, setInternal] = useState(false);\n const [expanded, setExpanded] = own.isExpanded !== undefined ? readBinding(own.isExpanded, own.onExpandedChange) : [internal, setInternal];\n const label = typeof own.label === 'string' ? <Text>{own.label}</Text> : own.label;\n const toggle = (): void => withAnimation({ type: 'easeInOut', duration: 0.25 }, () => setExpanded(!expanded));\n return applyModifiers(\n sb('disclosuregroup', { expanded }, { tap: toggle }, [\n <Fragment key=\"label\">{sb('zstack', { alignment: 'center' }, undefined, label)}</Fragment>,\n <Fragment key=\"content\">{own.children}</Fragment>,\n ]),\n modifiers,\n );\n}\n","/**\n * `Table`, drawn as iOS draws one: a list. In a compact width each row shows\n * the first column; in a regular width every column under a row of the\n * column titles, a sortable title a button with the sort's chevron.\n */\n\nimport { type Key, type ReactNode } from 'react';\nimport { readBinding, type BindingValue } from '../binding';\nimport { useHorizontalSizeClass } from '../environment';\nimport { applyModifiers, splitProps, styled, type ViewModifiers } from '../modifiers';\nimport { Button } from './controls';\nimport { List, type Selection } from './lists';\nimport { ForEach, HStack, VStack } from './stacks';\nimport { Image, Text } from './text';\n\nexport interface TableColumn<T> {\n title: string;\n /** The cell for a row; a function of the row, or a key whose value is shown as text. */\n content: ((row: T) => ReactNode) | keyof T;\n /** A fixed width; the other columns share the rest. */\n width?: number;\n minWidth?: number;\n maxWidth?: number;\n /** A sortable column: the key its title sorts by (the app sorts the rows by `sortOrder`). */\n sortKey?: string;\n}\n\nexport interface SortDescriptor {\n key: string;\n ascending: boolean;\n}\n\nexport interface TableProps<T, K extends Key = Key> extends ViewModifiers {\n data: readonly T[];\n columns: readonly TableColumn<T>[];\n /** Each row's identity (its `id` property by default), what the selection holds. */\n id?: (row: T, index: number) => K;\n selection?: BindingValue<Set<K>> | BindingValue<K | null>;\n onSelectionChange?: (selection: Selection<K>) => void;\n /** The sort order, first descriptor first; tapping a sortable title puts it first or reverses it. */\n sortOrder?: BindingValue<readonly SortDescriptor[]>;\n}\n\nconst COLUMN_SPACING = 12;\n\nfunction cell<T>(column: TableColumn<T>, content: ReactNode): ReactNode {\n if (column.width !== undefined) return styled({ layoutPriority: 0 }, styled({ frame: { width: column.width, alignment: 'leading' } }, content));\n return styled(\n { layoutPriority: 0 },\n styled({ frame: { minWidth: column.minWidth ?? 0, maxWidth: column.maxWidth ?? 'infinity', alignment: 'leading' } }, content),\n );\n}\n\nfunction cellContent<T>(column: TableColumn<T>, row: T): ReactNode {\n if (typeof column.content === 'function') return column.content(row);\n return <Text>{String(row[column.content] ?? '')}</Text>;\n}\n\nexport function Table<T, K extends Key = Key>(props: TableProps<T, K>): ReactNode {\n const { own, modifiers } = splitProps(props);\n const compact = useHorizontalSizeClass() !== 'regular';\n const sort = own.sortOrder !== undefined ? readBinding(own.sortOrder) : null;\n const keyOf = (row: T, index: number): K => {\n if (own.id) return own.id(row, index);\n const id = (row as { id?: unknown }).id;\n return (typeof id === 'string' || typeof id === 'number' ? id : index) as K;\n };\n const row = (value: T): ReactNode => {\n const first = own.columns[0];\n if (!first) return null;\n if (compact) return cellContent(first, value);\n return (\n <HStack spacing={COLUMN_SPACING}>\n {own.columns.map((column, index) => (\n <ColumnCell key={index}>{cell(column, cellContent(column, value))}</ColumnCell>\n ))}\n </HStack>\n );\n };\n const title = (column: TableColumn<T>): ReactNode => {\n if (!sort || column.sortKey === undefined) return <Text>{column.title}</Text>;\n const [order, setOrder] = sort;\n const current = order[0]?.key === column.sortKey ? order[0] : null;\n const tap = (): void => {\n const rest = order.filter((descriptor) => descriptor.key !== column.sortKey);\n setOrder([{ key: column.sortKey!, ascending: current ? !current.ascending : true }, ...rest]);\n };\n return (\n <Button action={tap} buttonStyle=\"plain\">\n <HStack spacing={4}>\n <Text>{column.title}</Text>\n {current && <Image systemName={current.ascending ? 'chevron.up' : 'chevron.down'} font={{ textStyle: 'caption2', weight: 'bold' }} />}\n </HStack>\n </Button>\n );\n };\n const list = (\n <List<K> selection={own.selection as BindingValue<Set<K>>} onSelectionChange={own.onSelectionChange}>\n <ForEach data={own.data} id={keyOf}>\n {(value, index) => <TableRow tag={keyOf(value, index)}>{row(value)}</TableRow>}\n </ForEach>\n </List>\n );\n if (compact) return applyModifiers(list, modifiers);\n return applyModifiers(\n <VStack spacing={0}>\n <HStack\n spacing={COLUMN_SPACING}\n font={{ textStyle: 'subheadline', weight: 'semibold' }}\n foregroundStyle=\"secondary\"\n padding={['horizontal', 20]}\n modifiers={[{ padding: ['vertical', 8] }]}\n >\n {own.columns.map((column, index) => (\n <ColumnCell key={index}>{cell(column, title(column))}</ColumnCell>\n ))}\n </HStack>\n {list}\n </VStack>,\n modifiers,\n );\n}\n\nfunction ColumnCell({ children }: { children?: ReactNode }): ReactNode {\n return children;\n}\n\n/** A table row: its content, tagged for the list's selection. */\nfunction TableRow({ children }: { tag: Key; children?: ReactNode }): ReactNode {\n return children;\n}\n","/** `ColorPicker` and `ShareLink`: controls that open the browser's own chooser and share sheet. */\n\nimport { chooseColor } from '@swiftbrowser/web/src/colorPicker';\nimport { base64Encode } from '@swiftbrowser/web/src/base64';\nimport { browserEnvironment, performHostRequest } from '@swiftbrowser/web/src/hostRequests';\nimport type { RGBAColor, SharedFile, ShareRequestParams } from '@swiftbrowser/web/src/protocol';\nimport type { ReactNode } from 'react';\nimport { readBinding, type BindingValue } from '../binding';\nimport { applyModifiers, splitProps, type ViewModifiers } from '../modifiers';\nimport { Color, Circle } from './shapes';\nimport { Button } from './controls';\nimport { HStack, Spacer } from './stacks';\nimport { Label, Text } from './text';\n\nexport interface ColorPickerProps extends ViewModifiers {\n title?: string;\n label?: ReactNode;\n selection: BindingValue<RGBAColor>;\n onChange?: (color: RGBAColor) => void;\n}\n\nconst hexOf = (c: RGBAColor): string =>\n '#' + [c.r, c.g, c.b].map((v) => Math.round(Math.min(1, Math.max(0, v)) * 255).toString(16).padStart(2, '0')).join('');\n\n/** `ColorPicker(\"Tint\", selection:)`: the label and a swatch; tapping opens the browser's color chooser. */\nexport function ColorPicker(props: ColorPickerProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const [selection, setSelection] = readBinding(own.selection, own.onChange);\n const label = own.label ?? (own.title !== undefined ? <Text>{own.title}</Text> : null);\n const pick = (): void => {\n chooseColor(hexOf(selection))\n .then((chosen) => {\n if (chosen) setSelection({ ...Color.hex(chosen), a: selection.a });\n })\n .catch((error: unknown) => console.error(error));\n };\n return applyModifiers(\n <Button action={pick} buttonStyle=\"plain\">\n <HStack>\n {label}\n <Spacer />\n <Circle\n fill={selection}\n frame={{ width: 28, height: 28 }}\n overlay={<Circle strokeBorder={{ style: Color.opacity('secondary', 0.3), lineWidth: 1 }} />}\n />\n </HStack>\n </Button>,\n modifiers,\n );\n}\n\n/** A file to share: its name, its MIME type (from the name's extension when left out) and its bytes. */\nexport interface SharedFileItem {\n name: string;\n type?: string;\n data: string | ArrayBuffer | Uint8Array | Blob;\n}\n\nexport interface ShareLinkProps extends ViewModifiers {\n /** What is shared: a URL, text, or a file (`ShareLink(item: document)` with a `FileRepresentation`). */\n item: string | URL | SharedFileItem;\n /** More files shared with it. */\n files?: SharedFileItem[];\n subject?: string;\n message?: string;\n /** The label; \"Share\" with the share symbol by default. */\n title?: string;\n children?: ReactNode;\n}\n\nconst isFile = (item: ShareLinkProps['item']): item is SharedFileItem => typeof item === 'object' && !(item instanceof URL) && 'data' in item;\n\nconst MIME_BY_EXTENSION: Record<string, string> = {\n txt: 'text/plain',\n md: 'text/markdown',\n csv: 'text/csv',\n json: 'application/json',\n html: 'text/html',\n pdf: 'application/pdf',\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n gif: 'image/gif',\n svg: 'image/svg+xml',\n m4a: 'audio/mp4',\n mp3: 'audio/mpeg',\n mp4: 'video/mp4',\n mov: 'video/quicktime',\n zip: 'application/zip',\n};\n\nasync function sharedFile(file: SharedFileItem): Promise<SharedFile> {\n const bytes =\n typeof file.data === 'string'\n ? new TextEncoder().encode(file.data)\n : file.data instanceof Uint8Array\n ? file.data\n : file.data instanceof ArrayBuffer\n ? new Uint8Array(file.data)\n : new Uint8Array(await file.data.arrayBuffer());\n const extension = file.name.includes('.') ? file.name.slice(file.name.lastIndexOf('.') + 1).toLowerCase() : '';\n return { name: file.name, type: file.type ?? MIME_BY_EXTENSION[extension] ?? 'application/octet-stream', data: base64Encode(bytes) };\n}\n\n/** The `share` request a `ShareLink` sends: the title, the text (the message, then a text item), the URL, and the files (an item file first). */\nexport async function shareParamsOf(props: Pick<ShareLinkProps, 'item' | 'files' | 'subject' | 'message'>): Promise<ShareRequestParams> {\n const item = props.item;\n const isURL = item instanceof URL || (typeof item === 'string' && /^[a-z][a-z0-9+.-]*:\\/\\//i.test(item));\n const params: ShareRequestParams = {};\n if (props.subject) params.title = props.subject;\n if (isURL) params.url = String(item);\n const text = [props.message, typeof item === 'string' && !isURL ? item : null].filter(Boolean).join('\\n');\n if (text) params.text = text;\n const files = [...(isFile(item) ? [item] : []), ...(props.files ?? [])];\n if (files.length) params.files = await Promise.all(files.map(sharedFile));\n return params;\n}\n\n/** `ShareLink(item:)`: the Web Share API where the browser has it (files too), else a download; natively the share sheet. */\nexport function ShareLink(props: ShareLinkProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const share = (): void => {\n // Within the tap (the files' bytes read first), so the browser lets the share sheet open.\n shareParamsOf(own)\n .then((params) => performHostRequest({ op: 'request', id: 0, kind: 'share', params }, browserEnvironment))\n .catch((error: unknown) => console.error(error));\n };\n return applyModifiers(\n <Button action={share}>{own.children ?? <Label title={own.title ?? 'Share'} systemImage=\"square.and.arrow.up\" />}</Button>,\n modifiers,\n );\n}\n","/**\n * `Canvas`: a `GeometryReader` whose content, at the reported size, is a\n * `canvas` element. The renderer function draws into a `GraphicsContext`\n * that records commands, as Sources/SwiftUI/API/Canvas.swift does; the page\n * draws them as SVG.\n */\n\nimport type { CanvasCommand, CanvasFilter, CanvasShading, CanvasState, Font, GradientStop } from '@swiftbrowser/web/src/protocol';\nimport { Fragment, useState, type ReactNode } from 'react';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, styled, type ViewModifiers } from '../modifiers';\nimport type { Path, Point } from '../path';\nimport { color, font, shapeStyle, unitPoint, type ColorValue, type FontValue, type StyleValue, type UnitPointValue } from '../values';\n\ntype Matrix = [number, number, number, number, number, number];\nconst IDENTITY: Matrix = [1, 0, 0, 1, 0, 0];\n\nfunction multiply(m: Matrix, n: Matrix): Matrix {\n // Applies `n` first, then `m` (CGAffineTransform concatenation order).\n const [a, b, c, d, tx, ty] = m;\n const [a2, b2, c2, d2, tx2, ty2] = n;\n return [a2 * a + b2 * c, a2 * b + b2 * d, c2 * a + d2 * c, c2 * b + d2 * d, tx2 * a + ty2 * c + tx, tx2 * b + ty2 * d + ty];\n}\n\n/** A shading in the drawing's coordinates: a style, or a gradient between two points. */\nexport type Shading =\n | StyleValue\n | { linearGradient: { colors?: ColorValue[]; stops?: { color: ColorValue; location: number }[]; start: Point; end: Point } }\n | { radialGradient: { colors?: ColorValue[]; stops?: { color: ColorValue; location: number }[]; center: Point; startRadius: number; endRadius: number } };\n\nfunction stops(spec: { colors?: ColorValue[]; stops?: { color: ColorValue; location: number }[] }): GradientStop[] {\n if (spec.stops) return spec.stops.map((s) => ({ color: color(s.color), location: s.location }));\n const colors = spec.colors ?? [];\n const last = Math.max(colors.length - 1, 1);\n return colors.map((c, i) => ({ color: color(c), location: i / last }));\n}\n\n/** In a drawing `.primary` / `.secondary`… are the label colors, as `.color(.primary)` is. */\nconst LABEL_COLORS: Record<string, CanvasShading> = {\n primary: { name: 'primary' },\n secondary: { name: 'secondary' },\n tertiary: { name: 'tertiaryLabel' },\n quaternary: { name: 'quaternaryLabel' },\n};\n\nfunction shading(value: Shading): CanvasShading {\n if (typeof value === 'string' && value in LABEL_COLORS) return LABEL_COLORS[value]!;\n if (typeof value === 'object' && value !== null) {\n if ('linearGradient' in value) {\n const g = value.linearGradient as { start: Point & { x: number }; end: Point } & Parameters<typeof stops>[0];\n // `LinearGradient(...)` styles carry stops of protocol colors and unit points; canvas gradients carry `colors` or ColorValue stops in points.\n if (isCanvasGradient(g)) return { canvasLinearGradient: { stops: stops(g), start: g.start, end: g.end } };\n }\n if ('radialGradient' in value) {\n const g = value.radialGradient as { center: Point; startRadius: number; endRadius: number } & Parameters<typeof stops>[0];\n if (isCanvasGradient(g)) return { canvasRadialGradient: { stops: stops(g), center: g.center, startRadius: g.startRadius, endRadius: g.endRadius } };\n }\n }\n return shapeStyle(value as StyleValue);\n}\n\n/** A canvas gradient is written with `colors`, or with stops whose colors are names or `#hex` strings. */\nfunction isCanvasGradient(g: { colors?: unknown; stops?: { color: unknown }[] }): boolean {\n if (Array.isArray(g.colors)) return true;\n return Array.isArray(g.stops) && g.stops.some((s) => typeof s.color === 'string');\n}\n\nexport interface StrokeOptions {\n lineWidth?: number;\n lineCap?: 'butt' | 'round' | 'square';\n lineJoin?: 'miter' | 'round' | 'bevel';\n miterLimit?: number;\n dash?: number[];\n dashPhase?: number;\n}\n\n/** What a canvas image is: a symbol, a catalog image, or a remote image of a known size. */\nexport type CanvasImage = { systemName: string } | { name: string } | { url: string; width: number; height: number };\n\ninterface State {\n transform: Matrix;\n opacity: number;\n blendMode: string | undefined;\n clips: string[];\n filters: CanvasFilter[];\n}\n\n/** A view passed in `Canvas`'s `symbols`, resolved by its id. */\nexport interface ResolvedSymbol {\n symbol: string;\n}\n\n/** Where a symbol was drawn: the point (the context's transform applied) and the look at that moment. */\nexport interface SymbolDraw {\n id: string;\n x: number;\n y: number;\n rotation: number;\n scale: { x: number; y: number };\n opacity: number;\n}\n\n/** `GraphicsContext`: what `Canvas`'s renderer draws with. Methods return the context for chaining. */\nexport class GraphicsContext {\n readonly commands: CanvasCommand[] = [];\n readonly symbolDraws: SymbolDraw[] = [];\n private symbolIds: ReadonlySet<string> = new Set();\n\n /** @internal The ids `symbols` gave the canvas. */\n setSymbols(ids: Iterable<string>): void {\n this.symbolIds = new Set(ids);\n }\n\n /** `resolveSymbol(id:)`: the view the canvas was given under `id`, or null. */\n resolveSymbol(id: string): ResolvedSymbol | null {\n return this.symbolIds.has(id) ? { symbol: id } : null;\n }\n\n /**\n * `draw(symbol, at:)`: the symbol's view centered on the point. Symbols are\n * views laid over the drawing, so they draw above its other commands.\n */\n drawSymbol(symbol: ResolvedSymbol, at: Point): this {\n const [a, b, c, d, tx, ty] = this.state.transform;\n const scaleX = Math.hypot(a, b);\n const scaleY = scaleX > 0 ? (a * d - b * c) / scaleX : Math.hypot(c, d);\n this.symbolDraws.push({\n id: symbol.symbol,\n x: a * at.x + c * at.y + tx,\n y: b * at.x + d * at.y + ty,\n rotation: (Math.atan2(b, a) * 180) / Math.PI,\n scale: { x: scaleX, y: scaleY },\n opacity: this.state.opacity,\n });\n return this;\n }\n private state: State = { transform: IDENTITY, opacity: 1, blendMode: undefined, clips: [], filters: [] };\n\n constructor(readonly size: { width: number; height: number }) {}\n\n get opacity(): number {\n return this.state.opacity;\n }\n set opacity(value: number) {\n this.state.opacity = value;\n }\n get blendMode(): string | undefined {\n return this.state.blendMode;\n }\n set blendMode(value: string | undefined) {\n this.state.blendMode = value;\n }\n\n translateBy(x: number, y: number): this {\n this.state.transform = multiply(this.state.transform, [1, 0, 0, 1, x, y]);\n return this;\n }\n scaleBy(x: number, y: number = x): this {\n this.state.transform = multiply(this.state.transform, [x, 0, 0, y, 0, 0]);\n return this;\n }\n /** Degrees, clockwise on screen. */\n rotate(degrees: number): this {\n const r = (degrees * Math.PI) / 180;\n this.state.transform = multiply(this.state.transform, [Math.cos(r), Math.sin(r), -Math.sin(r), Math.cos(r), 0, 0]);\n return this;\n }\n concatenate(matrix: Matrix): this {\n this.state.transform = multiply(this.state.transform, matrix);\n return this;\n }\n clip(to: Path): this {\n this.state.clips = [...this.state.clips, to.svg()];\n return this;\n }\n addFilter(filter: CanvasFilter): this {\n this.state.filters = [...this.state.filters, filter];\n return this;\n }\n\n /** `drawLayer { }`: draws with a copy of the state, restored after. */\n drawLayer(body: (context: GraphicsContext) => void): this {\n const saved = { ...this.state, clips: [...this.state.clips], filters: [...this.state.filters] };\n body(this);\n this.state = saved;\n return this;\n }\n\n fill(path: Path, with_: Shading, options: { eoFill?: boolean } = {}): this {\n this.push({ op: 'fill', path: path.svg(), shading: shading(with_), ...(options.eoFill ? { evenOdd: true } : {}) });\n return this;\n }\n\n stroke(path: Path, with_: Shading, options: StrokeOptions | number = {}): this {\n const o = typeof options === 'number' ? { lineWidth: options } : options;\n const command: CanvasCommand = { op: 'stroke', path: path.svg(), shading: shading(with_), lineWidth: o.lineWidth ?? 1 };\n if (o.lineCap) command.lineCap = o.lineCap;\n if (o.lineJoin) command.lineJoin = o.lineJoin;\n if (o.miterLimit !== undefined) command.miterLimit = o.miterLimit;\n if (o.dash) command.dash = o.dash;\n if (o.dashPhase !== undefined) command.dashPhase = o.dashPhase;\n this.push(command);\n return this;\n }\n\n /** `draw(Text(...), at:anchor:)` */\n drawText(text: string, at: Point, options: { anchor?: UnitPointValue; font?: FontValue; color?: StyleValue } = {}): this {\n const command: CanvasCommand = {\n op: 'text',\n text,\n x: at.x,\n y: at.y,\n anchor: unitPoint(options.anchor ?? 'center'),\n shading: shading(options.color ?? 'primary'),\n };\n if (options.font !== undefined) (command as { font?: Font }).font = font(options.font);\n this.push(command);\n return this;\n }\n\n /** `draw(Image(...), at:anchor:)` or `draw(_:in:)` with `size`. */\n drawImage(image: CanvasImage, at: Point, options: { anchor?: UnitPointValue; size?: { width: number; height: number }; color?: StyleValue } = {}): this {\n const props = 'url' in image ? { ...image, resizable: true } : 'name' in image ? { name: image.name, resizable: true } : image;\n const command = {\n op: 'image' as const,\n image: props,\n x: at.x,\n y: at.y,\n anchor: unitPoint(options.anchor ?? (options.size ? 'topLeading' : 'center')),\n ...(options.size ? { width: options.size.width, height: options.size.height } : {}),\n ...(options.color !== undefined ? { shading: shading(options.color) } : {}),\n };\n this.push(command as CanvasCommand);\n return this;\n }\n\n private push(command: CanvasCommand): void {\n const state: CanvasState = {};\n if (this.state.transform.some((v, i) => v !== IDENTITY[i])) state.transform = this.state.transform.map((v) => Math.round(v * 1e4) / 1e4) as Matrix;\n if (this.state.opacity !== 1) state.opacity = this.state.opacity;\n if (this.state.blendMode) state.blendMode = this.state.blendMode;\n if (this.state.clips.length) state.clips = [...this.state.clips];\n if (this.state.filters.length) state.filters = [...this.state.filters];\n this.commands.push({ ...state, ...command } as CanvasCommand);\n }\n}\n\nexport interface CanvasProps extends ViewModifiers {\n /** `Canvas { context, size in }` */\n renderer: (context: GraphicsContext, size: { width: number; height: number }) => void;\n /** `Canvas(renderer:symbols:)`: views the renderer draws by id (`resolveSymbol`, `drawSymbol`). */\n symbols?: Record<string, ReactNode>;\n}\n\nexport function Canvas(props: CanvasProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const [size, setSize] = useState<{ width: number; height: number } | null>(null);\n let canvas: ReactNode = null;\n let draws: SymbolDraw[] = [];\n if (size) {\n const context = new GraphicsContext(size);\n if (own.symbols) context.setSymbols(Object.keys(own.symbols));\n own.renderer(context, size);\n canvas = sb('canvas', { width: size.width, height: size.height, commands: context.commands });\n draws = context.symbolDraws;\n }\n const reader = sb(\n 'geometry',\n {},\n {\n geometry: (event) => {\n if (!size || size.width !== event.width || size.height !== event.height) setSize({ width: event.width, height: event.height });\n },\n },\n canvas,\n );\n if (!own.symbols) return applyModifiers(reader, modifiers);\n // The drawn symbols, each its view centered on the point it was drawn at.\n const symbols = draws.map((draw, index) => {\n let view: ReactNode = own.symbols![draw.id];\n if (draw.scale.x !== 1 || draw.scale.y !== 1) view = styled({ scale: draw.scale }, view);\n if (Math.abs(draw.rotation) > 1e-6) view = styled({ rotation: draw.rotation }, view);\n if (draw.opacity !== 1) view = styled({ opacity: draw.opacity }, view);\n return <Fragment key={index}>{styled({ position: { x: draw.x, y: draw.y } }, view)}</Fragment>;\n });\n return applyModifiers(\n sb('zstack', { alignment: 'topLeading' }, undefined, [<Fragment key=\"canvas\">{reader}</Fragment>, ...symbols]),\n modifiers,\n );\n}\n","/** `TimelineView`, and `VideoPlayer` and `AudioPlayer` with `useAVPlayer` and `AVQueuePlayer`. */\n\nimport type { RendererEvent } from '@swiftbrowser/web/src/protocol';\nimport { Fragment, useEffect, useRef, useState, useSyncExternalStore, type ReactNode } from 'react';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, type ViewModifiers } from '../modifiers';\n\n// ---------------------------------------------------------------------------\n// TimelineView\n// ---------------------------------------------------------------------------\n\nexport type TimelineSchedule =\n | 'animation'\n | 'everyMinute'\n | { animation: { minimumInterval?: number; paused?: boolean } }\n | { periodic: { from?: Date; by: number } };\n\nexport interface TimelineViewProps {\n schedule: TimelineSchedule;\n children: (context: { date: Date }) => ReactNode;\n}\n\n/** `TimelineView(.periodic(from:by:)) { context in }`: the content renders again at each date of the schedule. */\nexport function TimelineView({ schedule, children }: TimelineViewProps): ReactNode {\n const [date, setDate] = useState(() => new Date());\n const key = typeof schedule === 'string' ? schedule : JSON.stringify(schedule);\n useEffect(() => {\n if (schedule === 'everyMinute') {\n let interval: ReturnType<typeof setInterval> | undefined;\n const timeout = setTimeout(() => {\n setDate(new Date());\n interval = setInterval(() => setDate(new Date()), 60_000);\n }, 60_000 - (Date.now() % 60_000));\n return () => {\n clearTimeout(timeout);\n if (interval) clearInterval(interval);\n };\n }\n if (typeof schedule === 'object' && 'periodic' in schedule) {\n const every = Math.max(schedule.periodic.by, 0.01) * 1000;\n const from = schedule.periodic.from?.getTime() ?? Date.now();\n // Aligned to the schedule's dates (from + k × interval).\n let timer: ReturnType<typeof setTimeout>;\n const tick = (): void => {\n const now = Date.now();\n const next = from + Math.ceil((now - from + 1) / every) * every;\n timer = setTimeout(() => {\n setDate(new Date(next));\n tick();\n }, Math.max(0, next - now));\n };\n tick();\n return () => clearTimeout(timer);\n }\n const options = typeof schedule === 'object' ? schedule.animation : {};\n if (options.paused) return;\n const minimum = (options.minimumInterval ?? 1 / 20) * 1000;\n let last = 0;\n let frame = 0;\n const loop = (time: number): void => {\n if (time - last >= minimum) {\n last = time;\n setDate(new Date());\n }\n frame = requestAnimationFrame(loop);\n };\n frame = requestAnimationFrame(loop);\n return () => cancelAnimationFrame(frame);\n // The schedule's identity is its JSON.\n }, [key]);\n return children({ date });\n}\n\n// ---------------------------------------------------------------------------\n// AVPlayer\n// ---------------------------------------------------------------------------\n\ntype VideoEvent = Extract<RendererEvent, { type: 'video' }>;\n\ninterface PlayerState {\n url: string | null;\n rate: number;\n muted: boolean;\n volume: number;\n loop: boolean;\n seek: { time: number; serial: number };\n duration: number | null;\n size: { width: number; height: number } | null;\n status: 'playing' | 'waiting' | 'paused';\n failed: string | null;\n}\n\nexport interface AVPlayerOptions {\n loop?: boolean;\n /**\n * `addPeriodicTimeObserver(forInterval:)`: how often, in seconds, the\n * position is reported while playing (`onTime`); four times a second\n * without it. A scrubber that moves with the sound asks for a frame\n * (`1 / 60`): the page reports once per animation frame, the native app\n * sixty times a second.\n */\n report?: number;\n}\n\n/**\n * `AVPlayer`: what plays, the rate, mute and volume, seeks. A view showing\n * it re-renders when those change; the position (`currentTime`, several\n * reports a second, or as often as `report` asks) re-renders nothing: read\n * it or listen with `onTime`.\n */\nexport class AVPlayer {\n protected state: PlayerState;\n private listeners = new Set<() => void>();\n private timeListeners = new Set<(time: number) => void>();\n private time = 0;\n private serial = 0;\n /** @internal The `report` interval for the views showing this player. */\n readonly report: number | undefined;\n\n constructor(url: string | null = null, options: AVPlayerOptions = {}) {\n this.report = options.report;\n this.state = {\n url,\n rate: 0,\n muted: false,\n volume: 1,\n loop: options.loop ?? false,\n seek: { time: 0, serial: 0 },\n duration: null,\n size: null,\n status: 'paused',\n failed: null,\n };\n }\n\n get url(): string | null {\n return this.state.url;\n }\n get rate(): number {\n return this.state.rate;\n }\n get isPlaying(): boolean {\n return this.state.rate > 0;\n }\n get isMuted(): boolean {\n return this.state.muted;\n }\n get volume(): number {\n return this.state.volume;\n }\n get duration(): number | null {\n return this.state.duration;\n }\n get presentationSize(): { width: number; height: number } | null {\n return this.state.size;\n }\n get timeControlStatus(): PlayerState['status'] {\n return this.state.status;\n }\n get error(): string | null {\n return this.state.failed;\n }\n get currentTime(): number {\n return this.time;\n }\n /** @internal */\n get snapshot(): PlayerState {\n return this.state;\n }\n\n play(): void {\n this.update({ rate: 1 });\n }\n pause(): void {\n this.update({ rate: 0 });\n }\n seek(time: number): void {\n this.time = time;\n this.update({ seek: { time, serial: ++this.serial } });\n }\n replaceCurrentItem(url: string | null): void {\n this.time = 0;\n this.update({ url, duration: null, size: null, failed: null, seek: { time: 0, serial: ++this.serial } });\n }\n set isMuted(muted: boolean) {\n this.update({ muted });\n }\n set volume(volume: number) {\n this.update({ volume: Math.min(1, Math.max(0, volume)) });\n }\n set rate(rate: number) {\n this.update({ rate });\n }\n set loop(loop: boolean) {\n this.update({ loop });\n }\n\n subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n };\n\n /** `addPeriodicTimeObserver`: told the position as the page reports it. */\n onTime(listener: (time: number) => void): () => void {\n this.timeListeners.add(listener);\n return () => this.timeListeners.delete(listener);\n }\n\n /** @internal The page's report for a view showing this player. */\n handle(event: VideoEvent): void {\n if (event.time !== undefined) {\n this.time = event.time;\n for (const listener of this.timeListeners) listener(event.time);\n }\n switch (event.event) {\n case 'ready':\n this.update({\n duration: event.duration ?? null,\n size: event.width && event.height ? { width: event.width, height: event.height } : this.state.size,\n });\n break;\n case 'status':\n if (event.status) this.update({ status: event.status });\n break;\n case 'play':\n if (this.state.rate === 0) this.update({ rate: 1 });\n break;\n case 'pause':\n if (this.state.rate !== 0) this.update({ rate: 0 });\n break;\n case 'volume':\n this.update({ muted: event.muted ?? this.state.muted, volume: event.volume ?? this.state.volume });\n break;\n case 'rate':\n if (event.rate !== undefined) this.update({ rate: event.rate });\n break;\n case 'ended':\n this.ended();\n break;\n case 'error':\n this.update({ failed: event.message ?? 'error', rate: 0 });\n break;\n default:\n break;\n }\n }\n\n /** The item played to its end: a looping player plays on, the others pause (`actionAtItemEnd: .pause`; a queue advances). */\n protected ended(): void {\n if (!this.state.loop) this.update({ rate: 0 });\n }\n\n protected update(changes: Partial<PlayerState>): void {\n this.state = { ...this.state, ...changes };\n for (const listener of this.listeners) listener();\n }\n}\n\n/**\n * `AVQueuePlayer`: a player with the items to play after the current one.\n * When the current item ends the next plays (`actionAtItemEnd: .advance`),\n * at the same rate; with none left the player pauses at the end. `items()`\n * is the current item and the rest; `insert` and `remove` edit the rest.\n */\nexport class AVQueuePlayer extends AVPlayer {\n private upcoming: string[] = [];\n\n constructor(urls: readonly string[] = [], options: AVPlayerOptions = {}) {\n super(urls[0] ?? null, options);\n this.upcoming = urls.slice(1);\n }\n\n /** The current item (if any) and the items after it. */\n items(): string[] {\n return this.url === null ? [...this.upcoming] : [this.url, ...this.upcoming];\n }\n\n /** Plays the next item, or ends with nothing (`currentItem` null, paused) when there is none. */\n advanceToNextItem(): void {\n const next = this.upcoming.shift();\n if (next === undefined) {\n this.replaceCurrentItem(null);\n this.update({ rate: 0 });\n return;\n }\n this.replaceCurrentItem(next);\n }\n\n /** Adds `url` after `after` (an item in the queue), or at the end; `after` null puts it first, as `insert(_:after: nil)` does. */\n insert(url: string, after: string | null = null): void {\n if (after === null) {\n this.upcoming.unshift(url);\n } else {\n const at = this.upcoming.indexOf(after);\n if (at === -1) this.upcoming.push(url);\n else this.upcoming.splice(at + 1, 0, url);\n }\n this.update({});\n }\n\n /** Removes a queued item, or the current one, which advances. */\n remove(url: string): void {\n if (url === this.url) {\n this.advanceToNextItem();\n return;\n }\n const at = this.upcoming.indexOf(url);\n if (at !== -1) this.upcoming.splice(at, 1);\n this.update({});\n }\n\n removeAllItems(): void {\n this.upcoming = [];\n this.replaceCurrentItem(null);\n this.update({ rate: 0 });\n }\n\n protected override ended(): void {\n if (this.state.loop) return;\n this.advanceToNextItem();\n }\n}\n\n/** A player kept for the component's life, re-rendering it when what it plays changes. */\nexport function useAVPlayer(url: string | null = null, options: AVPlayerOptions = {}): AVPlayer {\n const ref = useRef<AVPlayer | null>(null);\n ref.current ??= new AVPlayer(url, options);\n const player = ref.current;\n useSyncExternalStore(player.subscribe, () => player.snapshot, () => player.snapshot);\n useEffect(() => {\n if (player.url !== url) player.replaceCurrentItem(url);\n }, [player, url]);\n return player;\n}\n\nexport interface VideoPlayerProps extends ViewModifiers {\n player: AVPlayer | null;\n /** `videoGravity`: fit (default), fill, or stretch. */\n gravity?: 'resizeAspect' | 'resizeAspectFill' | 'resize';\n /** The browser's native controls; true by default, as `VideoPlayer` shows them. */\n controls?: boolean;\n /** `VideoPlayer(player:) { videoOverlay }`: drawn over the video. */\n videoOverlay?: ReactNode;\n}\n\n/** The `video` element showing `player` in `state` (docs/ops-protocol.md, \"Video and audio\"). */\nfunction videoElement(player: AVPlayer, state: PlayerState & { url: string }, options: { gravity: VideoPlayerProps['gravity']; controls: boolean }): ReactNode {\n return sb(\n 'video',\n {\n url: state.url,\n playing: state.rate > 0 && !state.failed,\n muted: state.muted,\n volume: state.volume,\n rate: state.rate > 0 ? state.rate : 1,\n loop: state.loop,\n gravity: options.gravity ?? 'resizeAspect',\n controls: options.controls,\n seek: state.seek,\n ...(player.report !== undefined && player.report > 0 ? { report: player.report } : {}),\n ...(state.size ? { width: state.size.width, height: state.size.height } : {}),\n },\n { video: (event) => player.handle(event) },\n );\n}\n\n/** `VideoPlayer(player:)`: the page's `<video>` showing the player, or black without one. */\nexport function VideoPlayer(props: VideoPlayerProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const player = own.player;\n const state = useSyncExternalStore(\n player?.subscribe ?? NO_SUBSCRIBE,\n () => player?.snapshot ?? null,\n () => player?.snapshot ?? null,\n );\n if (!player || !state || !state.url) return applyModifiers(sb('color', { color: { r: 0, g: 0, b: 0, a: 1 } }), modifiers);\n const video = videoElement(player, { ...state, url: state.url }, { gravity: own.gravity, controls: own.controls ?? true });\n if (own.videoOverlay === undefined) return applyModifiers(video, modifiers);\n return applyModifiers(\n sb('zstack', { alignment: 'center' }, undefined, [<Fragment key=\"video\">{video}</Fragment>, <Fragment key=\"overlay\">{own.videoOverlay}</Fragment>]),\n modifiers,\n );\n}\n\nconst NO_SUBSCRIBE = (): (() => void) => () => {};\n\n/**\n * A player that plays with no view: the element at no size and out of the\n * way of taps, so an audio player (a playlist, a podcast)\n * keeps playing wherever the app's screens go. Put one anywhere in the\n * tree that stays mounted (the root), since a player shown by no\n * `VideoPlayer` or `AudioPlayer` plays nothing. iOS plays a player's sound\n * with no layer the same way.\n */\nexport function AudioPlayer({ player }: { player: AVPlayer | null }): ReactNode {\n const state = useSyncExternalStore(\n player?.subscribe ?? NO_SUBSCRIBE,\n () => player?.snapshot ?? null,\n () => player?.snapshot ?? null,\n );\n if (!player || !state || !state.url) return null;\n return applyModifiers(videoElement(player, { ...state, url: state.url }, { gravity: 'resizeAspect', controls: false }), [\n ['frame', { width: 0, height: 0 }],\n ['clipped', true],\n ['opacity', 0],\n ['allowsHitTesting', false],\n ]);\n}\n","/**\n * `PhaseAnimator` and `KeyframeAnimator`. A phase animator moves its content\n * through phases, each change in one animated pass that the renderer tweens\n * (as the shim does); a keyframe animator computes its values frame by frame\n * along tracks of keyframes and renders them, as SwiftUI evaluates its\n * content per frame.\n */\n\nimport type { Animation } from '@swiftbrowser/web/src/protocol';\nimport { timingFor } from '@swiftbrowser/web/src/animation';\nimport { useEffect, useRef, useState, type ReactNode } from 'react';\nimport { withAnimation } from '../host/root';\n\n// ---------------------------------------------------------------------------\n// PhaseAnimator\n// ---------------------------------------------------------------------------\n\nexport interface PhaseAnimatorProps<Phase> {\n phases: readonly Phase[];\n /** Each change runs through the phases once, back to the first; without one the phases cycle while shown. */\n trigger?: unknown;\n /** The animation into a phase (`default` by default). */\n animation?: (phase: Phase) => Animation;\n children: (phase: Phase) => ReactNode;\n}\n\nexport function PhaseAnimator<Phase>({ phases, trigger, animation, children }: PhaseAnimatorProps<Phase>): ReactNode {\n const [index, setIndex] = useState(0);\n const hasTrigger = trigger !== undefined;\n const latest = useRef({ phases, animation });\n latest.current = { phases, animation };\n const first = useRef(true);\n\n useEffect(() => {\n if (hasTrigger && first.current) {\n first.current = false;\n return;\n }\n first.current = false;\n let cancelled = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let step = 0;\n const count = latest.current.phases.length;\n if (count < 2) return;\n const advance = (): void => {\n if (cancelled) return;\n step += 1;\n const next = step % count;\n const { phases: current, animation: animationFor } = latest.current;\n const into = animationFor?.(current[next] as Phase) ?? { type: 'default' };\n withAnimation(into, () => setIndex(next));\n // A trigger runs through the phases once, ending on the first.\n if (hasTrigger && next === 0) return;\n const timing = timingFor(into);\n timer = setTimeout(advance, timing.duration + timing.delay);\n };\n // The first phase holds for a moment before the cycle starts, as the first change waits for a render.\n timer = setTimeout(advance, 0);\n return () => {\n cancelled = true;\n if (timer) clearTimeout(timer);\n };\n }, [hasTrigger, trigger]);\n\n return children(phases[index % Math.max(phases.length, 1)] as Phase);\n}\n\n// ---------------------------------------------------------------------------\n// KeyframeAnimator\n// ---------------------------------------------------------------------------\n\nexport type KeyframeCurve = 'linear' | 'cubic' | 'spring' | 'move';\n\n/** One keyframe of a track: the value it reaches, in how long (seconds), along which curve. */\nexport interface Keyframe {\n to: number;\n duration: number;\n curve?: KeyframeCurve;\n}\n\nexport type KeyframeTracks<Value extends Record<string, number>> = { [K in keyof Value]?: readonly Keyframe[] };\n\nexport interface KeyframeAnimatorProps<Value extends Record<string, number>> {\n initialValue: Value;\n keyframes: KeyframeTracks<Value>;\n /** Each change plays the keyframes once; without one they repeat while shown (`repeating`). */\n trigger?: unknown;\n repeating?: boolean;\n children: (value: Value) => ReactNode;\n}\n\nfunction ease(curve: KeyframeCurve, t: number): number {\n switch (curve) {\n case 'move':\n return 1;\n case 'cubic':\n return t * t * (3 - 2 * t);\n case 'spring': {\n // A critically damped spring that settles within the keyframe.\n const omega = 7;\n return 1 - (1 + omega * t) * Math.exp(-omega * t);\n }\n default:\n return t;\n }\n}\n\n/** The tracks' values `elapsed` seconds in (each track from the initial value through its keyframes). */\nexport function keyframeValues<Value extends Record<string, number>>(initial: Value, tracks: KeyframeTracks<Value>, elapsed: number): Value {\n const value: Record<string, number> = { ...initial };\n for (const key of Object.keys(tracks) as (keyof Value & string)[]) {\n const frames = tracks[key] ?? [];\n let from = initial[key] as number;\n let start = 0;\n let current: number = from;\n for (const frame of frames) {\n const end = start + frame.duration;\n if (elapsed >= end) {\n current = frame.to;\n } else {\n const t = frame.duration > 0 ? Math.max(0, (elapsed - start) / frame.duration) : 1;\n current = from + (frame.to - from) * ease(frame.curve ?? 'spring', t);\n break;\n }\n from = frame.to;\n start = end;\n }\n value[key] = current;\n }\n return value as Value;\n}\n\nfunction totalDuration(tracks: Record<string, readonly Keyframe[] | undefined>): number {\n return Math.max(0, ...Object.values(tracks).map((frames) => (frames ?? []).reduce((sum, frame) => sum + frame.duration, 0)));\n}\n\nexport function KeyframeAnimator<Value extends Record<string, number>>({\n initialValue,\n keyframes,\n trigger,\n repeating,\n children,\n}: KeyframeAnimatorProps<Value>): ReactNode {\n const [value, setValue] = useState<Value>(initialValue);\n const latest = useRef({ initialValue, keyframes });\n latest.current = { initialValue, keyframes };\n const first = useRef(true);\n const hasTrigger = trigger !== undefined;\n\n useEffect(() => {\n if (hasTrigger && first.current) {\n first.current = false;\n return;\n }\n first.current = false;\n if (!hasTrigger && !repeating) return;\n let frame = 0;\n let start: number | null = null;\n const tick = (now: number): void => {\n start ??= now;\n const { initialValue: initial, keyframes: tracks } = latest.current;\n const total = totalDuration(tracks as Record<string, readonly Keyframe[] | undefined>);\n let elapsed = (now - start) / 1000;\n if (!hasTrigger && repeating && total > 0) elapsed %= total;\n setValue(keyframeValues(initial, tracks, elapsed));\n if (hasTrigger && elapsed >= total) return;\n frame = requestAnimationFrame(tick);\n };\n frame = requestAnimationFrame(tick);\n return () => cancelAnimationFrame(frame);\n }, [hasTrigger, trigger, repeating]);\n\n return children(value);\n}\n"],"names":["r","detach","notify","keyOf","document","stops","wrap","runFont","Image","imageProps","plain","Fragment","clear","active","frame","size","round","IDENTITY","opacity","command","perform","font","fontOf","width","insets","host","exports","nextId","hostNow","roots","height","clamp","watching","value","placeholder","stride","styleOf","row","every"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAwDO,MAAM,yBAAyB,cAA+B,EAAE;AAEhE,SAAS,qBAAsC;AACpD,SAAO,WAAW,sBAAsB;AAC1C;AAGO,SAAS,gBAAgB,QAAyB,UAAgC;AACvF,SAAO,cAAc,qBAAqB,EAAE,OAAA,GAAU,QAAQ;AAChE;AAEA,SAAS,oBAAoB,EAAE,QAAQ,YAA0E;AAC/G,QAAM,SAAS,WAAW,sBAAsB;AAChD,SAAO,cAAc,uBAAuB,UAAU,EAAE,OAAO,EAAE,GAAG,QAAQ,GAAG,SAAO,GAAK,QAAQ;AACrG;AA6BO,MAAM,qBAAqB,cAA2B;AAAA,EAC3D,aAAa;AAAA,EACb,iBAAiB;AAAA,EACjB,qBAAqB;AAAA,EACrB,YAAY;AAAA,EACZ,UAAU;AACZ,CAAC;AAEM,SAAS,oBAAoB,EAAE,OAAO,YAAqE;AAChH,SAAO,cAAc,mBAAmB,UAAU,EAAE,MAAA,GAAS,QAAQ;AACvE;AAGO,SAAS,iBAA8B;AAC5C,SAAO,WAAW,kBAAkB,EAAE;AACxC;AAGO,SAAS,qBAAsC;AACpD,SAAO,WAAW,kBAAkB,EAAE;AACxC;AAGO,MAAM,iBAAiB,cAAmC,IAAI;AAE9D,SAAS,aAAyB;AACvC,QAAM,UAAU,WAAW,cAAc;AACzC,SAAO,YAAY,MAAM;AAAA,EAAC;AAC5B;AAGO,SAAS,yBAA8C;AAC5D,SAAO,WAAW,kBAAkB,EAAE;AACxC;AAOO,SAAS,gBAA4B;AAC1C,SAAO,WAAW,kBAAkB,EAAE;AACxC;AAQO,SAAS,cAAwB;AACtC,SAAO,WAAW,kBAAkB,EAAE;AACxC;AAGO,SAAS,cAAuB;AACrC,SAAO,WAAW,sBAAsB,EAAE,aAAa;AACzD;ACjHA,MAAM,+BAAe,IAAA;AAErB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AG,OAAO,OAAO,MAAM,EAAE,IAAI,CAAC,YAAY,UAAU,CAAA,GAAI,OAAO,CAAC,KAAKA,WAAU,MAAMA,OAAM,UAAU,CAAC,CAAC,CAAC;AAC7H;AAEO,SAAS,iBAAuD;AAAA,EACrE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAA4C;AAC1C,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAgB,YAAY;AACtD,QAAM,SAAS,OAAO,EAAE,cAAc,WAAW;AACjD,SAAO,UAAU,EAAE,cAAc,UAAA;AACjC,QAAM,QAAQ,OAAO,IAAI;AACzB,QAAM,aAAa,YAAY;AAE/B,YAAU,MAAM;AACd,QAAI,cAAc,MAAM,SAAS;AAC/B,YAAM,UAAU;AAChB;AAAA,IACF;AACA,UAAM,UAAU;AAChB,QAAI,CAAC,cAAc,CAAC,UAAW;AAC/B,QAAIA,SAAQ;AACZ,QAAI,QAAuB;AAC3B,UAAM,OAAO,CAAC,QAAsB;AAClC,gBAAU;AACV,YAAM,EAAE,cAAc,SAAS,WAAW,OAAA,IAAW,OAAO;AAC5D,YAAM,QAAQ,cAAc,MAAyD;AACrF,UAAI,WAAW,MAAM,SAAS;AAC9B,UAAI,CAAC,cAAc,aAAa,QAAQ,EAAG,YAAW;AACtD,eAAS,eAAe,SAAS,QAAQ,OAAO,CAAC;AACjD,UAAI,cAAc,WAAW,MAAO;AACpC,MAAAA,SAAQ,sBAAsB,IAAI;AAAA,IACpC;AACA,IAAAA,SAAQ,sBAAsB,IAAI;AAClC,WAAO,MAAM,qBAAqBA,MAAK;AAAA,EACzC,GAAG,CAAC,YAAY,SAAS,SAAS,CAAC;AAEnC,SAAO,SAAS,KAAK;AACvB;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/environment.ts","../src/bitmaps.ts","../src/host/instance.ts","../src/host/tree.ts","../src/host/reconciler.ts","../src/host/root.ts","../src/host/remote.ts","../src/host/sb.ts","../src/inheritedStyle.ts","../src/navigation-context.ts","../src/components/remoteTree.tsx","../src/binding.ts","../src/dragDrop.tsx","../src/fileImporter.tsx","../src/fileExporter.tsx","../src/components/row.tsx","../src/values.ts","../src/scrollReader.tsx","../src/scrollEnvironment.tsx","../src/lazy.tsx","../src/components/stacks.tsx","../src/components/text.tsx","../src/components/navigation.tsx","../src/components/split.tsx","../src/presentation.tsx","../src/inspector.tsx","../src/lifecycle.tsx","../src/coordinateSpace.tsx","../src/components/geometry.tsx","../src/visualEffect.tsx","../src/pointer.tsx","../src/modifiers.tsx","../src/components/hostElement.tsx","../src/measureText.ts","../src/mount.ts","../src/undo.ts","../src/bridge.ts","../src/island.tsx","../src/path.ts","../src/attributedText.ts","../src/audioRecorder.ts","../src/avAsset.ts","../src/videoRecorder.tsx","../src/audioEngine.ts","../src/languageModel.ts","../src/wakeLock.ts","../src/components/controls.tsx","../src/components/shapes.tsx","../src/appleSignIn.tsx","../src/geolocation.ts","../src/speech.ts","../src/appStorage.ts","../src/fileManager.ts","../src/fileStorage.ts","../src/components/lists.tsx","../src/components/tabs.tsx","../src/components/host.tsx","../src/components/registered.tsx","../src/components/menus.tsx","../src/components/images.tsx","../src/components/charts.tsx","../src/components/containers.tsx","../src/components/table.tsx","../src/components/system.tsx","../src/components/canvas.tsx","../src/components/media.tsx","../src/components/animators.tsx"],"sourcesContent":["/**\n * Environment values: what a modifier on a container passes to the views\n * below it (`.buttonStyle`, `.controlSize`…), and the device environment the\n * page sets (color scheme, Dynamic Type size, size class, scene phase).\n */\n\nimport type { ButtonStyle, ColorScheme, DynamicTypeSize, PickerStyle, Platform, ScenePhase, ToggleStyle } from '@swiftbrowser/web/src/protocol';\nimport { createContext, createElement, useContext, type ReactNode } from 'react';\n\nexport type ControlSize = 'mini' | 'small' | 'regular' | 'large' | 'extraLarge';\n\n/** `.symbolRenderingMode(_:)`: `palette` draws a symbol's layers in the foreground styles' levels. */\nexport type SymbolRenderingMode = 'monochrome' | 'multicolor' | 'hierarchical' | 'palette';\n\n/** The text input hints a text field carries (the `textfield` element's props of the same names). */\nexport interface TextInputHints {\n keyboard?: KeyboardType | undefined;\n contentType?: TextContentType | undefined;\n autocapitalization?: 'never' | 'words' | 'sentences' | 'characters' | undefined;\n autocorrectionDisabled?: boolean | undefined;\n}\n\n/** `UIKeyboardType`'s cases. */\nexport type KeyboardType =\n | 'default' | 'asciiCapable' | 'numbersAndPunctuation' | 'URL' | 'numberPad' | 'phonePad' | 'namePhonePad'\n | 'emailAddress' | 'decimalPad' | 'twitter' | 'webSearch' | 'asciiCapableNumberPad';\n\n/** `UITextContentType`'s names. */\nexport type TextContentType =\n | 'name' | 'givenName' | 'familyName' | 'emailAddress' | 'telephoneNumber' | 'username' | 'password' | 'newPassword'\n | 'oneTimeCode' | 'URL' | 'fullStreetAddress' | 'postalCode' | 'creditCardNumber';\n\nexport interface ViewEnvironment {\n buttonStyle?: ButtonStyle;\n controlSize?: ControlSize;\n pickerStyle?: PickerStyle;\n toggleStyle?: ToggleStyle;\n labelsHidden?: boolean;\n /** `.refreshable`: the nearest `List` or `ScrollView` below runs it on a pull. */\n refresh?: () => unknown;\n /** `.submitLabel`: the return key's label of the text fields below. */\n submitLabel?: string;\n /** `.keyboardType`, `.textContentType`, `.textInputAutocapitalization`, `.autocorrectionDisabled` for the text fields below. */\n textInputHints?: TextInputHints;\n /** `.labelStyle`: how the `Label`s below draw. */\n labelStyle?: 'automatic' | 'titleAndIcon' | 'titleOnly' | 'iconOnly' | undefined;\n /** `.redacted(reason: .placeholder)`: text and images below draw as placeholder shapes. */\n redacted?: boolean;\n /** `.textCase(_:)` for the texts below. */\n textCase?: 'uppercase' | 'lowercase' | null;\n /** `.symbolRenderingMode(_:)` for the images below. */\n symbolRenderingMode?: SymbolRenderingMode;\n /** Inside an alert's actions: tapping a button also dismisses the alert. */\n dismissAlert?: () => void;\n}\n\nexport const ViewEnvironmentContext = createContext<ViewEnvironment>({});\n\nexport function useViewEnvironment(): ViewEnvironment {\n return useContext(ViewEnvironmentContext);\n}\n\n/** Wrap `children` in an environment with `values` added. */\nexport function withEnvironment(values: ViewEnvironment, children: ReactNode): ReactNode {\n return createElement(EnvironmentExtender, { values }, children);\n}\n\nfunction EnvironmentExtender({ values, children }: { values: ViewEnvironment; children?: ReactNode }): ReactNode {\n const parent = useContext(ViewEnvironmentContext);\n return createElement(ViewEnvironmentContext.Provider, { value: { ...parent, ...values } }, children);\n}\n\nexport type HorizontalSizeClass = 'compact' | 'regular';\n\nexport type { Platform };\n\nexport interface Environment {\n colorScheme: ColorScheme;\n dynamicTypeSize: DynamicTypeSize;\n /** `compact` below 700 points of width (an iPhone), `regular` from it (an iPad, a desktop window). */\n horizontalSizeClass: HorizontalSizeClass;\n /**\n * `active` while the app is in front and takes input, `inactive` while it\n * shows but does not (the app switcher, a system sheet over it, a page\n * whose window lost focus), `background` while it is not shown (a hidden\n * tab, an app the viewer left). `active` where nothing says otherwise.\n */\n scenePhase: ScenePhase;\n /**\n * The platform the app is drawn as (docs/notes/macos.md): `ios` (the\n * default) or `macos`. The renderer draws that platform's idiom; a page\n * decides it from the browser (`mount`'s `platform`), a native app from\n * the OS it runs on. Fixed for the app's life.\n */\n platform: Platform;\n}\n\nexport type { ScenePhase };\n\nexport const EnvironmentContext = createContext<Environment>({\n colorScheme: 'light',\n dynamicTypeSize: 'large',\n horizontalSizeClass: 'compact',\n scenePhase: 'active',\n platform: 'ios',\n});\n\nexport function EnvironmentProvider({ value, children }: { value: Environment; children?: ReactNode }): ReactNode {\n return createElement(EnvironmentContext.Provider, { value }, children);\n}\n\n/** `@Environment(\\.colorScheme)` */\nexport function useColorScheme(): ColorScheme {\n return useContext(EnvironmentContext).colorScheme;\n}\n\n/** `@Environment(\\.dynamicTypeSize)` */\nexport function useDynamicTypeSize(): DynamicTypeSize {\n return useContext(EnvironmentContext).dynamicTypeSize;\n}\n\n/** `@Environment(\\.dismiss)`: set by sheets and pushed screens. */\nexport const DismissContext = createContext<(() => void) | null>(null);\n\nexport function useDismiss(): () => void {\n const dismiss = useContext(DismissContext);\n return dismiss ?? (() => {});\n}\n\n/** `@Environment(\\.horizontalSizeClass)` */\nexport function useHorizontalSizeClass(): HorizontalSizeClass {\n return useContext(EnvironmentContext).horizontalSizeClass;\n}\n\n/**\n * `@Environment(\\.scenePhase)`: `active`, `inactive` or `background`. A\n * page follows the document's visibility and the window's focus; the native\n * app follows its scene. Refresh what time moved on when it turns `active`.\n */\nexport function useScenePhase(): ScenePhase {\n return useContext(EnvironmentContext).scenePhase;\n}\n\n/**\n * The platform the app is drawn as, `ios` or `macos` (docs/notes/macos.md):\n * for a layout that differs between a phone and a Mac beyond what the size\n * class says (a toolbar's placement, a window's columns). The views adapt\n * on their own, as SwiftUI's do.\n */\nexport function usePlatform(): Platform {\n return useContext(EnvironmentContext).platform;\n}\n\n/** `@Environment(\\.redactionReasons)`: whether the views below are placeholders. */\nexport function useRedacted(): boolean {\n return useContext(ViewEnvironmentContext).redacted === true;\n}\n","/**\n * Bitmaps: a picture's bytes as a Core Image source, and the recipes the\n * renderer draws over one (docs/ops-protocol.md, \"Bitmaps and Core Image\").\n * `bitmapSource` registers a file (a PNG, JPEG, GIF or WebP, as bytes or a\n * data URL) and reads its size from the header; `<Image bitmap={...} />`\n * draws it with Core Image steps applied: crops, turns, adjustments, photo\n * effects, blurs. The pixels never pass through JavaScript: the page runs\n * the steps on a canvas (Web/src/imageOps.ts), a native app with Core Image.\n * The host tree sends each source once, as an `imagedata` op before the\n * first element that draws it (host/tree.ts).\n */\n\nimport { base64Decode, base64Encode } from '@swiftbrowser/web/src/base64';\nimport { addLiveBitmap, forgetLiveBitmap } from '@swiftbrowser/web/src/bitmaps';\nimport type { BitmapStep, ImageDataOp } from '@swiftbrowser/web/src/protocol';\n\nexport type { BitmapPoint, BitmapStep, BitmapVector, PhotoEffect } from '@swiftbrowser/web/src/protocol';\n\n/** A registered picture: the key the renderer knows it by, and its size in pixels as drawn (a JPEG's EXIF rotation applied). */\nexport interface BitmapSource {\n readonly key: string;\n readonly width: number;\n readonly height: number;\n readonly mime: string;\n}\n\n/** What `<Image bitmap>` draws: `source` (null: an empty image) with `steps` applied in order, in Core Image's space (source pixels, origin at the bottom left, y up). */\nexport interface Bitmap {\n source: BitmapSource | null;\n steps?: readonly BitmapStep[];\n /** For a live source (`liveBitmapSource`): a count raised each time the pixels changed in place, which draws them again. */\n version?: number;\n}\n\n/** A rectangle in Core Image's space; infinite sides for a clamped image. */\nexport interface BitmapRect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/** The sources registered in this realm, by key, as their ops. */\nconst registry = new Map<string, ImageDataOp>();\n/** Data URLs already registered, so a render does not decode one again. */\nconst byURL = new Map<string, BitmapSource | null>();\n\n/**\n * Registers a picture file and returns it as a source, or null when the bytes\n * are not a PNG, JPEG, GIF or WebP file whose size the header gives (pass\n * `width` and `height` to register one anyway). The same bytes give the same\n * key, however often they are registered.\n */\nexport function bitmapSource(file: Uint8Array | string, options: { mime?: string; width?: number; height?: number } = {}): BitmapSource | null {\n if (typeof file === 'string') {\n const known = byURL.get(file);\n if (known !== undefined) return known;\n const match = /^data:([^;,]*)(?:;[^,]*)?;base64,(.*)$/s.exec(file);\n const source = match ? register(base64Decode(match[2]!), match[2]!, { mime: match[1] || undefined, ...options }) : null;\n byURL.set(file, source);\n return source;\n }\n return register(file, null, options);\n}\n\nfunction register(bytes: Uint8Array, base64: string | null, options: { mime?: string | undefined; width?: number | undefined; height?: number | undefined }): BitmapSource | null {\n const header = imageHeader(bytes);\n const width = options.width ?? header?.width;\n const height = options.height ?? header?.height;\n const mime = header?.mime ?? options.mime ?? '';\n if (width === undefined || height === undefined) return null;\n const key = `f${fnv1a64(bytes)}`;\n if (!registry.has(key)) registry.set(key, { op: 'imagedata', key, width, height, mime, data: base64 ?? base64Encode(bytes) });\n return { key, width, height, mime };\n}\n\n/**\n * Pixels the page holds as a source: RGBA (straight alpha, rows from the\n * top), `width` × `height`, in memory the app changes in place, a frame at a\n * time, and draws with `<Image bitmap={{ source, version }} />`, raising\n * `version` after each change. Over a `SharedArrayBuffer` (a worker's\n * output, a WebAssembly module's memory) the drawing reads the bytes as\n * they are; over plain memory each version is copied once to the drawing\n * worker. Null in a native app, whose renderer draws no pixels the app\n * holds yet. `releaseBitmapSource` lets the pixels go once nothing shows\n * them.\n */\nexport function liveBitmapSource(pixels: Uint8Array, width: number, height: number): BitmapSource | null {\n if ((globalThis as { __sbNative?: unknown }).__sbNative !== undefined) return null;\n return { key: addLiveBitmap(pixels, width, height), width, height, mime: '' };\n}\n\nexport function releaseBitmapSource(source: BitmapSource): void {\n if (source.key.startsWith('l')) forgetLiveBitmap(source.key);\n}\n\n/** A source's `imagedata` op, when it was registered here. */\nexport function bitmapSourceOp(key: string): ImageDataOp | undefined {\n return registry.get(key);\n}\n\n/** Keeps an `imagedata` op another tree sent (a remote tree's, host/remote.ts), so this realm's tree can send it on. */\nexport function registerBitmapSourceOp(op: ImageDataOp): void {\n if (!registry.has(op.key)) registry.set(op.key, op);\n}\n\n/** FNV-1a, 64 bits, as 16 hex digits: the protocol's content hash. */\nfunction fnv1a64(bytes: Uint8Array): string {\n // Two 32-bit halves: the prime is 2^40 + 0x1b3.\n let hi = 0xcbf29ce4;\n let lo = 0x84222325;\n for (let i = 0; i < bytes.length; i++) {\n lo = (lo ^ bytes[i]!) >>> 0;\n // (hi, lo) × 0x100000001b3 = (hi, lo) × 0x1b3 + (lo << 40)\n const loMul = lo * 0x1b3;\n const carry = Math.floor(loMul / 0x100000000);\n const newLo = loMul >>> 0;\n const newHi = (Math.imul(hi, 0x1b3) + carry + ((lo << 8) >>> 0)) >>> 0;\n hi = newHi;\n lo = newLo;\n }\n return hi.toString(16).padStart(8, '0') + lo.toString(16).padStart(8, '0');\n}\n\n// ---------------------------------------------------------------------------\n// Headers\n// ---------------------------------------------------------------------------\n\n/** A file's type and size in pixels as drawn, from its header: PNG, JPEG (EXIF orientation 5–8 swaps the sides), GIF and WebP. */\nexport function imageHeader(b: Uint8Array): { mime: string; width: number; height: number } | null {\n const u16 = (i: number, little = false): number => (little ? b[i]! | (b[i + 1]! << 8) : (b[i]! << 8) | b[i + 1]!);\n const u32 = (i: number): number => ((b[i]! << 24) | (b[i + 1]! << 16) | (b[i + 2]! << 8) | b[i + 3]!) >>> 0;\n if (b.length >= 24 && b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47) {\n return { mime: 'image/png', width: u32(16), height: u32(20) };\n }\n if (b.length >= 10 && b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46) {\n return { mime: 'image/gif', width: u16(6, true), height: u16(8, true) };\n }\n if (b.length >= 30 && b[0] === 0x52 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x46 && b[8] === 0x57 && b[9] === 0x45 && b[10] === 0x42 && b[11] === 0x50) {\n const chunk = String.fromCharCode(b[12]!, b[13]!, b[14]!, b[15]!);\n if (chunk === 'VP8 ') return { mime: 'image/webp', width: u16(26, true) & 0x3fff, height: u16(28, true) & 0x3fff };\n if (chunk === 'VP8L') {\n const bits = (b[21]! | (b[22]! << 8) | (b[23]! << 16) | (b[24]! << 24)) >>> 0;\n return { mime: 'image/webp', width: (bits & 0x3fff) + 1, height: ((bits >>> 14) & 0x3fff) + 1 };\n }\n if (chunk === 'VP8X') return { mime: 'image/webp', width: 1 + (b[24]! | (b[25]! << 8) | (b[26]! << 16)), height: 1 + (b[27]! | (b[28]! << 8) | (b[29]! << 16)) };\n return null;\n }\n if (b.length >= 4 && b[0] === 0xff && b[1] === 0xd8) {\n let orientation = 1;\n let i = 2;\n while (i + 4 <= b.length) {\n if (b[i] !== 0xff) return null;\n const marker = b[i + 1]!;\n if (marker === 0xd8 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {\n i += 2;\n continue;\n }\n const length = u16(i + 2);\n if (marker === 0xe1 && length >= 16) orientation = exifOrientation(b, i + 4, length - 2) ?? orientation;\n // Start of frame (baseline, progressive, …), not DHT (c4), JPG (c8) or DAC (cc).\n if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {\n if (i + 9 > b.length) return null;\n const height = u16(i + 5);\n const width = u16(i + 7);\n return orientation >= 5 && orientation <= 8 ? { mime: 'image/jpeg', width: height, height: width } : { mime: 'image/jpeg', width, height };\n }\n i += 2 + length;\n }\n }\n return null;\n}\n\n/** The orientation tag (0x0112) of an APP1 segment's EXIF data, if any. */\nfunction exifOrientation(b: Uint8Array, start: number, length: number): number | null {\n // \"Exif\\0\\0\", then a TIFF header.\n if (b[start] !== 0x45 || b[start + 1] !== 0x78 || b[start + 2] !== 0x69 || b[start + 3] !== 0x66) return null;\n const tiff = start + 6;\n const end = Math.min(b.length, start + length);\n const little = b[tiff] === 0x49;\n const u16 = (i: number): number => (little ? b[i]! | (b[i + 1]! << 8) : (b[i]! << 8) | b[i + 1]!);\n const u32 = (i: number): number => (little ? (b[i]! | (b[i + 1]! << 8) | (b[i + 2]! << 16) | (b[i + 3]! << 24)) >>> 0 : ((b[i]! << 24) | (b[i + 1]! << 16) | (b[i + 2]! << 8) | b[i + 3]!) >>> 0);\n if (tiff + 8 > end) return null;\n const ifd = tiff + u32(tiff + 4);\n if (ifd + 2 > end) return null;\n const count = u16(ifd);\n for (let n = 0; n < count; n++) {\n const entry = ifd + 2 + n * 12;\n if (entry + 12 > end) return null;\n if (u16(entry) === 0x0112) return u16(entry + 8);\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Extents\n// ---------------------------------------------------------------------------\n\n/**\n * Where a recipe's output lies, in Core Image's space: the source's\n * rectangle carried through the steps as Core Image's `extent` is (a crop\n * keeps the overlap, a blur grows by three radii, a transform takes the\n * moved rectangle's bounds, `clamp` makes it infinite). What `<Image\n * bitmap>` sizes itself by.\n */\nexport function bitmapExtent(source: { width: number; height: number } | null, steps: readonly BitmapStep[] = []): BitmapRect {\n let r: BitmapRect = source ? { x: 0, y: 0, width: source.width, height: source.height } : { x: 0, y: 0, width: 0, height: 0 };\n const infinite = (): boolean => !Number.isFinite(r.width) || !Number.isFinite(r.height);\n for (const step of steps) {\n switch (step.op) {\n case 'crop': {\n if (infinite()) {\n r = { x: step.x, y: step.y, width: step.width, height: step.height };\n break;\n }\n const x0 = Math.max(r.x, step.x);\n const y0 = Math.max(r.y, step.y);\n const x1 = Math.min(r.x + r.width, step.x + step.width);\n const y1 = Math.min(r.y + r.height, step.y + step.height);\n r = { x: x0, y: y0, width: Math.max(0, x1 - x0), height: Math.max(0, y1 - y0) };\n break;\n }\n case 'render':\n r = { x: 0, y: 0, width: step.width, height: step.height };\n break;\n case 'clamp':\n r = { x: -Infinity, y: -Infinity, width: Infinity, height: Infinity };\n break;\n case 'gaussianBlur': {\n if (infinite()) break;\n const grow = Math.ceil(3 * step.radius);\n r = { x: r.x - grow, y: r.y - grow, width: r.width + 2 * grow, height: r.height + 2 * grow };\n break;\n }\n case 'place':\n if (!(step.sx > 0) || !(step.sy > 0)) r = { x: step.tx, y: step.ty, width: 0, height: 0 };\n else if (!infinite()) r = { x: r.x * step.sx + step.tx, y: r.y * step.sy + step.ty, width: r.width * step.sx, height: r.height * step.sy };\n break;\n case 'transform': {\n if (infinite()) break;\n const { a, b, c, d, tx, ty } = step;\n if (!(Math.abs(a * d - b * c) > 1e-12)) {\n r = { x: tx, y: ty, width: 0, height: 0 };\n break;\n }\n const xs: number[] = [];\n const ys: number[] = [];\n for (const [x, y] of [\n [r.x, r.y],\n [r.x + r.width, r.y],\n [r.x, r.y + r.height],\n [r.x + r.width, r.y + r.height],\n ] as const) {\n xs.push(a * x + c * y + tx);\n ys.push(b * x + d * y + ty);\n }\n const x0 = Math.min(...xs);\n const y0 = Math.min(...ys);\n r = { x: x0, y: y0, width: Math.max(...xs) - x0, height: Math.max(...ys) - y0 };\n break;\n }\n default:\n break;\n }\n }\n return r;\n}\n","/**\n * The host tree the reconciler mutates: one `Instance` per host element. A\n * host element is always the intrinsic type `sb` with a `kind` (an element\n * kind of the ops protocol, or one of the two virtual kinds below) and the\n * element's `props`; the React components in ../components render nothing\n * else.\n */\n\nimport type { RendererEvent } from '@swiftbrowser/web/src/protocol';\nimport type { ReactNode } from 'react';\nimport type { Effective } from './tree';\n\nexport type EventType = RendererEvent['type'];\nexport type EventOf<K extends EventType> = Extract<RendererEvent, { type: K }>;\n/**\n * The renderer's events an element answers, by type. `'*'` takes every\n * event addressed to the element that no typed handler took: a mirrored\n * element (`RemoteTree`) forwards them all to the root that drew it.\n */\nexport type EventHandlers = { [K in EventType]?: (event: EventOf<K>) => void } & { '*'?: (event: AddressedEvent) => void };\n\n/** An event the renderer addresses to one element. */\nexport type AddressedEvent = Extract<RendererEvent, { id: number }>;\n\n/**\n * Where a virtual element acts: the nearest enclosing `navscreen` or `sheet`\n * element, or the root container.\n */\nexport type HoistTarget = 'navscreen' | 'sheet' | 'root';\n\n/**\n * A preference: not an element itself; its `props` are merged into the\n * target's props (`.navigationTitle` sets the enclosing screen's `title`,\n * `.presentationDetents` the enclosing sheet's `detents`).\n */\nexport const PREF_KIND = '$pref';\n/**\n * A hoist: not an element itself; its children become children of the target\n * after the target's own (`.toolbar` items join the screen, `.sheet` content\n * becomes a root-level `sheet` element).\n */\nexport const HOIST_KIND = '$hoist';\n\nexport interface HostProps {\n kind: string;\n props?: Record<string, unknown>;\n on?: EventHandlers;\n target?: HoistTarget;\n children?: ReactNode;\n}\n\nexport interface Instance {\n /** The element id in the ops protocol; stable for the instance's life. */\n id: number;\n kind: string;\n props: Record<string, unknown>;\n on: EventHandlers | undefined;\n target: HoistTarget | undefined;\n /** The children as React currently has them (virtual kinds included). */\n children: Instance[];\n /** Hidden by Suspense: left out of the emitted tree. */\n hidden: boolean;\n /** Whether a `create` op was emitted for the current id. */\n created: boolean;\n committedProps: Record<string, unknown> | null;\n committedParent: TreeNode | null;\n committedChildren: Instance[];\n /** The element React has it under (virtual kinds included); null while detached. */\n parent: TreeNode | null;\n /** Changed since the last flush (itself, a child, its visibility), or under something that has: resolved again at the next. */\n stale: boolean;\n /** How it was last emitted (tree.ts `Effective`); null before its first flush. */\n entry: Effective | null;\n /** Whether it is in the emitted tree as of the last flush. */\n shown: boolean;\n /** The element it is a child of as emitted: its React parent, or the target it was hoisted to. */\n effectiveParent: TreeNode | null;\n /** The flush that last resolved it (tree.ts `generation`); a reused subtree keeps an older one. */\n resolvedIn: number;\n}\n\n/** The root container, element id 0. */\nexport interface RootNode {\n id: 0;\n kind: 'root';\n children: Instance[];\n committedChildren: Instance[];\n parent: null;\n stale: boolean;\n entry: Effective | null;\n}\n\nexport type TreeNode = Instance | RootNode;\n","/**\n * Turns the host tree into ops. The reconciler mutates `Instance.children`\n * freely during a React commit; `flush` then resolves the virtual kinds\n * (preferences and hoists), diffs the result against what was emitted last\n * time and produces one render pass: creates and updates, inserts (parents\n * before children, as the Swift core orders them), removes, `commit`.\n *\n * The flush is incremental: every mutation the reconciler makes marks the\n * instance and its ancestors stale (`markStale`), and a flush resolves and\n * diffs only the stale subtrees, reusing each clean subtree's effective\n * entry from the last flush, what it hoisted and the preferences it sent\n * up replayed into the ancestors resolved again. A knob dragged in a tree\n * of three thousand elements then costs the knob's path, not the tree.\n */\n\nimport type { Animation, CommitOp, Op, RendererEvent } from '@swiftbrowser/web/src/protocol';\nimport { bitmapSourceOp } from '../bitmaps';\nimport { HOIST_KIND, PREF_KIND, type HoistTarget, type HostProps, type Instance, type RootNode, type TreeNode } from './instance';\n\nexport type OpsSink = (ops: Op[]) => void;\n\nexport interface HostTreeOptions {\n /**\n * The tree is drawn by another root (`RemoteTree`), not a renderer: a\n * preference with no screen to take it goes to the root instead of being\n * dropped, and the root's props are sent whole as `update` of element 0\n * (a renderer takes only `colorScheme` there), so the host can lift them\n * to the screen it draws the tree in.\n */\n remote?: boolean;\n}\n\n/**\n * What a subtree sends past its top to the ancestors that take it: a\n * preference's props for the nearest element of its target kind, or an\n * element hoisted after that target's own children. Kept with the subtree's\n * entry and replayed when the subtree is reused, resolved against the\n * ancestors it then has.\n */\ntype Contribution = { kind: 'pref'; target: HoistTarget | undefined; props: Record<string, unknown> } | { kind: 'hoist'; target: HoistTarget | undefined; node: Instance };\n\n/** An element as emitted: its props with the preferences merged in, its children (own, then hoisted), what left it. */\nexport interface Effective {\n /** The props as sent: the element's own object until a preference or an inherited title mode writes, then a copy. */\n props: Record<string, unknown>;\n /** The props before the title mode inherited from the screen below (a stack's screens), to derive it from again. */\n base: Record<string, unknown>;\n children: Instance[];\n /** Children hoisted here from inside the subtree, appended after `children` once the whole tree is visited. */\n hoisted: Instance[];\n /** What this subtree sent to the ancestors above it, in visit order. */\n escaping: Contribution[];\n}\n\ninterface Context {\n navscreen?: Instance;\n sheet?: Instance;\n}\n\n/**\n * A pushed screen whose title display mode is `automatic` takes the mode of\n * the screen below it, as on iOS (a navigation item's `.automatic` inherits\n * the previous item's): a stack whose root has a large title shows large\n * titles on the screens it pushes, until one says `.inline`. The root's own\n * `automatic` is left for the page (large). As the Swift core does\n * (`_inheritingTitleModes`), once `.navigationBarTitleDisplayMode` is merged in.\n */\nfunction inheritTitleModes(screens: readonly Instance[]): void {\n let below = 'large';\n for (const screen of screens) {\n const entry = screen.kind === 'navscreen' ? screen.entry : null;\n if (!entry) continue;\n const base = entry.base;\n const depth = typeof base['depth'] === 'number' ? base['depth'] : 0;\n let mode = typeof base['displayMode'] === 'string' ? base['displayMode'] : 'automatic';\n if (mode === 'automatic') {\n if (depth > 0) {\n // Written into a copy, never the element's own props; the same value as last time leaves the entry as it is.\n if (entry.props['displayMode'] !== below) entry.props = { ...base, displayMode: below };\n } else if (entry.props !== base) entry.props = base;\n mode = depth > 0 ? below : 'large';\n } else if (entry.props !== base) entry.props = base;\n below = mode === 'inline' ? 'inline' : 'large';\n }\n}\n\n/** `node` changed (its props, its children, its visibility): it and every ancestor are resolved and diffed again at the next flush. */\nexport function markStale(node: TreeNode): void {\n for (let current: TreeNode | null = node; current && !current.stale; current = current.kind === 'root' ? null : current.parent) current.stale = true;\n}\n\n/** Puts `child` under `parent` at `index` (the end when absent), as the reconciler asks. */\nexport function attach(parent: TreeNode, child: Instance, index?: number): void {\n detach(parent, child);\n if (index === undefined || index < 0 || index > parent.children.length) parent.children.push(child);\n else parent.children.splice(index, 0, child);\n child.parent = parent;\n markStale(parent);\n}\n\n/** Takes `child` out of `parent`, if it is there. */\nexport function detach(parent: TreeNode, child: Instance): void {\n const at = parent.children.indexOf(child);\n if (at >= 0) parent.children.splice(at, 1);\n if (child.parent === parent) child.parent = null;\n markStale(parent);\n}\n\nexport class HostTree {\n readonly root: RootNode = { id: 0, kind: 'root', children: [], committedChildren: [], parent: null, stale: true, entry: null };\n private nextId = 1;\n /** Emitted elements by id, for event dispatch. */\n private readonly live = new Map<number, Instance>();\n /** Ids whose element changed kind: removed at the end of the next flush. */\n private retired: number[] = [];\n /** Which flush is under way; an instance resolved in it carries the number. */\n private generation = 0;\n /** `withAnimation`: stamped on the next `commit`. */\n pendingAnimation: Animation | undefined;\n /** `withAnimation(_:completionCriteria:_:completion:)`: stamped on the next `commit` with its serial; the callback waits in `completions`. */\n pendingCompletion: { serial: number; criteria: 'logicallyComplete' | 'removed'; callback: () => void; whenNothingDrawn?: boolean } | undefined;\n private readonly completions = new Map<number, () => void>();\n /** The root's `colorScheme` last sent (`.preferredColorScheme`); undefined while none was. */\n private committedColorScheme: 'light' | 'dark' | null | undefined;\n /** Remote: the root's props last sent. */\n private committedRootProps: Record<string, unknown> = {};\n /** The bitmap sources (`imagedata` keys) this tree has sent: each goes once, before the first image that draws it. */\n private readonly sentSources = new Set<string>();\n\n constructor(\n private readonly sink: OpsSink,\n private readonly options: HostTreeOptions = {},\n ) {}\n\n /** Whether another tree draws this one (`createSwiftUIRoot(sink, { remote: true })`, for a `RemoteTree`). */\n get remote(): boolean {\n return this.options.remote === true;\n }\n\n createInstance(props: HostProps): Instance {\n return {\n id: this.nextId++,\n kind: props.kind,\n props: props.props ?? {},\n on: props.on,\n target: props.target,\n children: [],\n hidden: false,\n created: false,\n committedProps: null,\n committedParent: null,\n committedChildren: [],\n parent: null,\n stale: true,\n entry: null,\n shown: false,\n effectiveParent: null,\n resolvedIn: 0,\n };\n }\n\n updateInstance(instance: Instance, next: HostProps): void {\n if (next.kind !== instance.kind) {\n // An element cannot change kind: the old one goes, a new id takes its\n // place and the children move over.\n if (instance.created) {\n this.retired.push(instance.id);\n this.live.delete(instance.id);\n }\n instance.id = this.nextId++;\n instance.kind = next.kind;\n instance.created = false;\n instance.committedProps = null;\n instance.committedParent = null;\n instance.committedChildren = [];\n }\n instance.props = next.props ?? {};\n instance.on = next.on;\n instance.target = next.target;\n markStale(instance);\n }\n\n /** `node` is hidden or shown again (Suspense): it leaves or rejoins the emitted tree. */\n setHidden(instance: Instance, hidden: boolean): void {\n instance.hidden = hidden;\n markStale(instance);\n }\n\n /** Emit the ops for everything that changed since the last commit. */\n commit(): void {\n const ops = this.flush();\n if (ops.length > 0) this.sink(ops);\n }\n\n flush(): Op[] {\n const animation = this.pendingAnimation;\n this.pendingAnimation = undefined;\n const completion = this.pendingCompletion;\n this.pendingCompletion = undefined;\n const generation = ++this.generation;\n const root = this.root;\n\n // Phase 1: the effective tree, resolved again only where something changed.\n const rootEntry: Effective = { props: {}, base: {}, children: [], hoisted: [], escaping: [] };\n const previousRoot = root.entry;\n root.entry = rootEntry;\n /** The elements resolved this flush, with their last entry (to find what left them). */\n const resolved: [Instance, Effective | null][] = [];\n /** The elements resolved this flush whose own children are under way, nearest last (a contribution is kept by those below its target). */\n const path: Instance[] = [];\n const targetOf = (target: HoistTarget | undefined, ctx: Context, hoist: boolean): TreeNode | undefined => {\n if (target === 'root' || target === undefined) return root;\n return ctx[target] ?? (hoist || this.options.remote ? root : undefined);\n };\n /** Keeps `contribution` with every element on the path below `target`, so a reuse of any of them replays it. */\n const keep = (contribution: Contribution, target: TreeNode | undefined): void => {\n for (let i = path.length - 1; i >= 0; i--) {\n const node = path[i]!;\n if (node === target) return;\n node.entry!.escaping.push(contribution);\n }\n };\n const assign = (target: TreeNode, props: Record<string, unknown>): void => {\n const entry = target.entry!;\n // The element's own props object is never written: the first preference takes a copy.\n if (target.kind !== 'root' && entry.props === (target as Instance).props) {\n entry.props = { ...entry.props };\n entry.base = entry.props;\n }\n Object.assign(entry.props, props);\n if (entry.base !== entry.props) Object.assign(entry.base, props);\n };\n const contribute = (contribution: Contribution, ctx: Context): void => {\n if (contribution.kind === 'pref') {\n const target = targetOf(contribution.target, ctx, false);\n if (target) assign(target, contribution.props);\n keep(contribution, target);\n } else {\n const target = targetOf(contribution.target, ctx, true)!;\n target.entry!.hoisted.push(contribution.node);\n contribution.node.effectiveParent = target;\n keep(contribution, target);\n }\n };\n const visit = (child: Instance, sink: Instance[], owner: TreeNode, ctx: Context, hoistedTo: HoistTarget | null | undefined): void => {\n if (child.hidden) return;\n // A preference or a hoist is resolved into its target, never kept as an entry: it is clean once visited, so a\n // change below it marks its ancestors stale again (`markStale` stops at the first stale element it meets).\n if (child.kind === PREF_KIND || child.kind === HOIST_KIND) child.stale = false;\n if (child.kind === PREF_KIND) {\n contribute({ kind: 'pref', target: child.target, props: child.props }, ctx);\n return;\n }\n if (child.kind === HOIST_KIND) {\n const target = targetOf(child.target, ctx, true)!;\n for (const grandchild of child.children) visit(grandchild, target.entry!.hoisted, target, ctx, child.target ?? 'root');\n return;\n }\n if (hoistedTo !== undefined) {\n // A hoisted element: kept by the path below its target, with the target as its effective parent.\n child.effectiveParent = owner;\n keep({ kind: 'hoist', target: hoistedTo ?? undefined, node: child }, owner);\n }\n sink.push(child);\n if (!child.stale && child.entry) {\n // Nothing under it changed: last flush's entry stands, and what it sent up goes up again.\n child.effectiveParent = owner;\n child.shown = true;\n for (const contribution of child.entry.escaping) contribute(contribution, ctx);\n return;\n }\n const entry: Effective = { props: child.props, base: child.props, children: [], hoisted: [], escaping: [] };\n resolved.push([child, child.entry]);\n child.entry = entry;\n child.stale = false;\n child.shown = true;\n child.effectiveParent = owner;\n child.resolvedIn = generation;\n const next: Context = child.kind === 'navscreen' ? { ...ctx, navscreen: child } : child.kind === 'sheet' ? { ...ctx, sheet: child } : ctx;\n path.push(child);\n for (const grandchild of child.children) visit(grandchild, entry.children, child, next, undefined);\n path.pop();\n };\n for (const child of root.children) visit(child, rootEntry.children, root, {}, undefined);\n root.stale = false;\n if (rootEntry.hoisted.length > 0) rootEntry.children.push(...rootEntry.hoisted);\n for (const [node] of resolved) {\n const entry = node.entry!;\n if (entry.hoisted.length > 0) entry.children.push(...entry.hoisted);\n }\n for (const [node] of resolved) {\n if (node.kind === 'navstack') inheritTitleModes(node.entry!.children);\n }\n\n // Phase 2: what left the tree. An element shown last flush and not now sits in the old children of an element\n // resolved now (its parent, or the target it was hoisted to), unless it moved to another.\n const ops: Op[] = [];\n const left: Instance[] = [];\n const arrived = new Set<Instance>();\n const compare = (before: Instance[] | undefined, after: Instance[]): void => {\n if (!before) {\n for (const child of after) arrived.add(child);\n return;\n }\n let same = before.length === after.length;\n for (let i = 0; same && i < after.length; i++) if (before[i] !== after[i]) same = false;\n if (same) return;\n const now = new Set(after);\n for (const child of before) if (!now.has(child)) left.push(child);\n const then = new Set(before);\n for (const child of after) if (!then.has(child)) arrived.add(child);\n };\n compare(previousRoot?.children, rootEntry.children);\n for (const [node, previous] of resolved) compare(previous?.children, node.entry!.children);\n const gone = (instance: Instance): void => {\n this.live.delete(instance.id);\n instance.shown = false;\n instance.created = false;\n instance.committedProps = null;\n instance.committedParent = null;\n instance.committedChildren = [];\n // Resolved afresh if it ever comes back.\n instance.stale = true;\n const entry = instance.entry;\n if (entry) for (const child of entry.children) if (child.effectiveParent === instance) gone(child);\n };\n for (const instance of left) {\n if (!instance.shown || arrived.has(instance)) continue;\n // The top of a removed subtree only: removing it removes the rest.\n ops.push({ op: 'remove', id: instance.id });\n gone(instance);\n }\n\n // Phase 3: the diff, into the elements resolved this flush; a reused subtree is as it was committed.\n const emit = (parent: TreeNode, entry: Effective): void => {\n const current = parent.committedChildren.filter((child) => child.shown && child.effectiveParent === parent);\n entry.children.forEach((child, index) => {\n const childEntry = child.entry!;\n if (child.kind === 'image') this.sendBitmapSource(childEntry.props, ops);\n if (!child.created) {\n ops.push({ op: 'create', id: child.id, kind: child.kind, props: childEntry.props } as Op);\n child.created = true;\n this.live.set(child.id, child);\n } else if (childEntry.props !== child.committedProps && !deepEqual(childEntry.props, child.committedProps)) {\n ops.push({ op: 'update', id: child.id, props: childEntry.props } as Op);\n }\n child.committedProps = childEntry.props;\n // A child that changed kind is the same instance under a new id: it\n // must be inserted again even where it already sits.\n if (current[index] !== child || child.committedParent !== parent) {\n ops.push({ op: 'insert', parent: parent.id, id: child.id, index });\n const at = current.indexOf(child);\n if (at >= 0) current.splice(at, 1);\n current.splice(index, 0, child);\n }\n child.committedParent = parent;\n if (child.resolvedIn === generation) emit(child, childEntry);\n });\n parent.committedChildren = entry.children;\n };\n emit(root, rootEntry);\n\n for (const id of this.retired) ops.push({ op: 'remove', id });\n this.retired = [];\n\n if (this.options.remote) {\n // Everything the preferences left on the root (a title with no screen of its own, a color scheme) goes whole to the host.\n if (!deepEqual(rootEntry.props, this.committedRootProps)) {\n ops.push({ op: 'update', id: 0, props: rootEntry.props } as Op);\n this.committedRootProps = rootEntry.props;\n }\n } else {\n // `.preferredColorScheme`: the only prop the root takes; `null` hands the\n // appearance back to the page once a preference is gone.\n const scheme = rootEntry.props['colorScheme'] as 'light' | 'dark' | null | undefined;\n const next = scheme === undefined ? (this.committedColorScheme === undefined ? undefined : null) : scheme;\n if (next !== undefined && next !== this.committedColorScheme) {\n ops.push({ op: 'update', id: 0, props: { colorScheme: next } } as Op);\n this.committedColorScheme = next === null ? undefined : next;\n }\n }\n\n if (ops.length === 0) {\n // A stamp with no body of its own (`stampNextCommit`): nothing will animate, so its completion runs now.\n if (completion?.whenNothingDrawn) completion.callback();\n return ops;\n }\n const commit: CommitOp = { op: 'commit' };\n if (animation) commit.animation = animation;\n if (completion) {\n // The renderer answers `animationcomplete` with the serial once the pass has finished animating.\n commit.completion = completion.serial;\n if (completion.criteria === 'removed') commit.completionCriteria = 'removed';\n this.completions.set(completion.serial, completion.callback);\n }\n ops.push(commit);\n return ops;\n }\n\n /** An `imagedata` op ahead of an image whose recipe's source this tree has not sent yet (bitmaps.ts). */\n private sendBitmapSource(props: Record<string, unknown>, ops: Op[]): void {\n const key = (props['bitmap'] as { source?: unknown } | undefined)?.source;\n if (typeof key !== 'string' || this.sentSources.has(key)) return;\n const op = bitmapSourceOp(key);\n if (!op) return;\n this.sentSources.add(key);\n ops.push(op);\n }\n\n /** Whether a pass is still animating with this completion serial. */\n awaitsCompletion(serial: number): boolean {\n return this.completions.has(serial);\n }\n\n /** Hand a renderer event to the element's handler for its type. */\n dispatch(event: RendererEvent): void {\n if (event.type === 'batch') {\n for (const each of event.events) this.dispatch(each);\n return;\n }\n if (event.type === 'animationcomplete') {\n const callback = this.completions.get(event.serial);\n this.completions.delete(event.serial);\n callback?.();\n return;\n }\n if (!('id' in event)) return;\n const instance = this.live.get(event.id);\n const handler = (instance?.on?.[event.type] ?? instance?.on?.['*']) as ((event: RendererEvent) => void) | undefined;\n handler?.(event);\n }\n}\n\n/** Structural equality of JSON-like values. */\nexport function deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n if (Array.isArray(a)) {\n const other = b as unknown[];\n return a.length === other.length && a.every((value, index) => deepEqual(value, other[index]));\n }\n const left = a as Record<string, unknown>;\n const right = b as Record<string, unknown>;\n const keys = Object.keys(left);\n if (keys.length !== Object.keys(right).length) return false;\n return keys.every((key) => key in right && deepEqual(left[key], right[key]));\n}\n\n","/**\n * The react-reconciler host config: React mutates `Instance` trees, and\n * `resetAfterCommit` asks the `HostTree` for the ops of the pass.\n */\n\nimport { createContext } from 'react';\nimport Reconciler from 'react-reconciler';\nimport { DefaultEventPriority } from 'react-reconciler/constants';\nimport type { HostProps, Instance } from './instance';\nimport { attach, detach, markStale, type HostTree } from './tree';\n\ntype HostContext = Record<string, never>;\n\nlet currentUpdatePriority = 0;\n\ntype Config = Reconciler.HostConfig<\n string, // Type\n HostProps, // Props\n HostTree, // Container\n Instance, // Instance\n never, // TextInstance\n never, // ActivityInstance\n never, // SuspenseInstance\n never, // HydratableInstance\n never, // FormInstance\n Instance, // PublicInstance\n HostContext, // HostContext\n never, // ChildSet\n ReturnType<typeof setTimeout>, // TimeoutHandle\n -1, // NoTimeout\n null, // TransitionStatus\n null, // SuspendedState\n null, // RendererInspectionConfig\n never, // FormStateMarkerInstance\n never, // HoistableRoot\n never // Resource\n>;\n\nconst hostConfig: Config = {\n supportsMutation: true,\n supportsPersistence: false,\n supportsHydration: false,\n isPrimaryRenderer: true,\n noTimeout: -1,\n scheduleTimeout: setTimeout,\n cancelTimeout: clearTimeout,\n supportsMicrotasks: true,\n scheduleMicrotask: queueMicrotask,\n\n getRootHostContext: () => ({}),\n getChildHostContext: (parent) => parent,\n getPublicInstance: (instance) => instance,\n prepareForCommit: () => null,\n resetAfterCommit: (tree) => tree.commit(),\n preparePortalMount: () => {},\n shouldSetTextContent: () => false,\n\n createInstance: (type, props, tree) => {\n if (type !== 'sb') throw new Error(`Unknown host element <${type}>: only SwiftUI components render here.`);\n return tree.createInstance(props);\n },\n createTextInstance: (text) => {\n throw new Error(`Text strings must be rendered within a <Text> component (got ${JSON.stringify(text)}).`);\n },\n appendInitialChild: (parent, child) => attach(parent, child),\n finalizeInitialChildren: () => false,\n commitMount: () => {},\n commitUpdate: (instance, _type, _prev, next, handle) => {\n const tree = treeOf(handle);\n if (tree) tree.updateInstance(instance, next);\n else {\n instance.props = next.props ?? {};\n instance.on = next.on;\n instance.target = next.target;\n markStale(instance);\n }\n },\n\n appendChild: (parent, child) => attach(parent, child),\n appendChildToContainer: (tree, child) => attach(tree.root, child),\n insertBefore: (parent, child, before) => {\n detach(parent, child);\n const at = parent.children.indexOf(before);\n attach(parent, child, at < 0 ? parent.children.length : at);\n },\n insertInContainerBefore: (tree, child, before) => {\n detach(tree.root, child);\n const at = tree.root.children.indexOf(before);\n attach(tree.root, child, at < 0 ? tree.root.children.length : at);\n },\n removeChild: (parent, child) => detach(parent, child),\n removeChildFromContainer: (tree, child) => detach(tree.root, child),\n clearContainer: (tree) => {\n for (const child of tree.root.children) child.parent = null;\n tree.root.children = [];\n markStale(tree.root);\n },\n resetTextContent: () => {},\n commitTextUpdate: () => {},\n hideInstance: (instance) => {\n instance.hidden = true;\n markStale(instance);\n },\n unhideInstance: (instance) => {\n instance.hidden = false;\n markStale(instance);\n },\n hideTextInstance: () => {},\n unhideTextInstance: () => {},\n detachDeletedInstance: () => {},\n\n getInstanceFromNode: () => null,\n beforeActiveInstanceBlur: () => {},\n afterActiveInstanceBlur: () => {},\n prepareScopeUpdate: () => {},\n getInstanceFromScope: () => null,\n setCurrentUpdatePriority: (priority) => {\n currentUpdatePriority = priority;\n },\n getCurrentUpdatePriority: () => currentUpdatePriority,\n resolveUpdatePriority: () => (currentUpdatePriority !== 0 ? currentUpdatePriority : DefaultEventPriority),\n resetFormInstance: () => {},\n requestPostPaintCallback: () => {},\n shouldAttemptEagerTransition: () => false,\n trackSchedulerEvent: () => {},\n resolveEventType: () => null,\n resolveEventTimeStamp: () => -1.1,\n maySuspendCommit: () => false,\n maySuspendCommitOnUpdate: () => false,\n maySuspendCommitInSyncRender: () => false,\n suspendOnActiveViewTransition: () => {},\n getSuspendedCommitReason: () => null,\n bindToConsole: (methodName, args) => () => (console as unknown as Record<string, (...a: unknown[]) => unknown>)[methodName]?.(...args),\n preloadInstance: () => true,\n startSuspendingCommit: () => null,\n suspendInstance: () => {},\n waitForCommitToBeReady: () => null,\n NotPendingTransition: null,\n HostTransitionContext: createContext<null>(null) as unknown as Config['HostTransitionContext'],\n rendererVersion: '0.3.1',\n rendererPackageName: '@swiftbrowser/react',\n extraDevToolsConfig: null,\n};\n\n/**\n * The fiber's root container: `commitUpdate` needs the tree to retire an\n * element whose kind changed. React hands the fiber as the opaque handle.\n */\nfunction treeOf(handle: unknown): HostTree | null {\n let fiber = handle as { return: unknown; stateNode: unknown; tag: number } | null;\n while (fiber) {\n // HostRoot fibers (tag 3) hold the FiberRoot, whose containerInfo is our tree.\n if (fiber.tag === 3) return (fiber.stateNode as { containerInfo: HostTree }).containerInfo;\n fiber = fiber.return as typeof fiber;\n }\n return null;\n}\n\nexport const reconciler = Reconciler(hostConfig);\n","/**\n * A SwiftUI root: renders a React element tree into a stream of render ops.\n * The page gives the ops to a `Renderer` (@swiftbrowser/web) and feeds the\n * renderer's events back through `dispatch`; headless code (tests) records\n * the ops instead.\n */\n\nimport type { Animation, ColorScheme, DynamicTypeSize, Op, RendererEvent } from '@swiftbrowser/web/src/protocol';\nimport { createContext, createElement, type ReactNode } from 'react';\nimport { ConcurrentRoot } from 'react-reconciler/constants';\nimport { EnvironmentProvider, type Environment } from '../environment';\nimport { reconciler } from './reconciler';\nimport { HostTree, type HostTreeOptions, type OpsSink } from './tree';\n\nexport interface SwiftUIRoot {\n /** Render (or re-render) the tree; the ops of the pass reach the sink before this returns. */\n render(element: ReactNode): void;\n unmount(): void;\n /** A renderer event (a tap, a toggle…) for the element it names. */\n dispatch(event: RendererEvent): void;\n /** The device environment the tree reads through `useColorScheme` and friends. */\n setEnvironment(environment: Partial<Environment>): void;\n}\n\nconst DEFAULT_ENVIRONMENT: Environment = { colorScheme: 'light', dynamicTypeSize: 'large', horizontalSizeClass: 'compact', scenePhase: 'active', platform: 'ios' };\n\nconst roots = new Set<HostTree>();\n\n/** The tree a component renders into (`RemoteTree` stamps a child's animation on it). */\nexport const HostTreeContext = createContext<HostTree | null>(null);\n\nexport type SwiftUIRootOptions = HostTreeOptions;\n\n/**\n * A root whose ops reach `sink`. `remote: true` for a tree another root\n * draws through `RemoteTree` (`createRemoteRoot`), rather than a renderer.\n */\nexport function createSwiftUIRoot(sink: OpsSink, options: SwiftUIRootOptions = {}): SwiftUIRoot {\n const tree = new HostTree(sink, options);\n roots.add(tree);\n // The tenth argument is `onDefaultTransitionIndicator` from react-reconciler\n // 0.33 (React 19.2) and `transitionCallbacks` before it (an object the\n // stable build never reads): a no-op function serves both, and the\n // eleventh is ignored by every version the package supports.\n const container = reconciler.createContainer(\n tree,\n ConcurrentRoot,\n null,\n false,\n null,\n '',\n (error) => {\n throw error;\n },\n (error) => console.error(error),\n (error) => console.warn(error),\n () => {},\n null,\n );\n let environment = DEFAULT_ENVIRONMENT;\n let current: ReactNode = null;\n const update = (): void => {\n reconciler.updateContainerSync(createElement(HostTreeContext.Provider, { value: tree }, createElement(EnvironmentProvider, { value: environment }, current)), container, null, null);\n reconciler.flushSyncWork();\n };\n return {\n render(element) {\n current = element;\n update();\n },\n unmount() {\n reconciler.updateContainerSync(null, container, null, null);\n reconciler.flushSyncWork();\n roots.delete(tree);\n },\n dispatch(event) {\n // Updates the handler makes flush before this returns, like the Swift\n // core answers an event with the ops of its render pass.\n reconciler.flushSyncFromReconciler(() => tree.dispatch(event));\n },\n setEnvironment(next) {\n environment = { ...environment, ...next };\n update();\n },\n };\n}\n\nexport type { ColorScheme, DynamicTypeSize, Op };\n\n/**\n * Registers the reconciler with the React DevTools hook (`__REACT_DEVTOOLS_GLOBAL_HOOK__`)\n * when the page has one: DevTools then sees the SwiftUI tree, and React Fast\n * Refresh (whose runtime installs that hook) can refresh its components in\n * place. Call it before the first root; `react-dom` does the same for itself.\n */\nexport function injectIntoDevTools(): boolean {\n return reconciler.injectIntoDevTools() === true;\n}\n\n/** `AnimationCompletionCriteria`: when a `withAnimation` completion runs. */\nexport type AnimationCompletionCriteria = 'logicallyComplete' | 'removed';\n\nexport interface WithAnimationOptions {\n /**\n * `logicallyComplete` (the default) calls the completion when the\n * animation's duration has passed; `removed` once every effect of it is\n * gone (a spring's last settling included).\n */\n completionCriteria?: AnimationCompletionCriteria;\n}\n\nlet nextCompletionSerial = 1;\n\n/**\n * Stamps one tree's next `commit` with an animation (and a completion, whose\n * serial is answered), without a body: for a pass another root animated,\n * drawn here by `RemoteTree`. The stamp waits for the tree's next flush,\n * however late React runs it; `withAnimation` clears its stamps as its body\n * returns.\n */\nexport function stampNextCommit(tree: HostTree, animation: Animation, completion?: { criteria: AnimationCompletionCriteria; callback: () => void }): number {\n tree.pendingAnimation = animation;\n if (!completion) return 0;\n const serial = nextCompletionSerial++;\n tree.pendingCompletion = { serial, criteria: completion.criteria, callback: completion.callback, whenNothingDrawn: true };\n return serial;\n}\n\n/**\n * `withAnimation { }`: the state changes `body` makes render in one pass whose\n * `commit` carries the animation, so the renderer animates every frame and\n * style change of the pass. With a `completion`\n * (`withAnimation(_:completionCriteria:_:completion:)`) the renderer answers\n * once the pass has finished animating and the completion runs then; a body\n * that changes nothing to render runs it at once.\n */\nexport function withAnimation<T>(animation: Animation | undefined, body: () => T, completion?: () => void): T;\nexport function withAnimation<T>(animation: Animation | undefined, options: WithAnimationOptions, body: () => T, completion?: () => void): T;\nexport function withAnimation<T>(body: () => T): T;\nexport function withAnimation<T>(\n first: Animation | undefined | (() => T),\n second?: (() => T) | WithAnimationOptions,\n third?: (() => T) | (() => void),\n fourth?: () => void,\n): T {\n const animation: Animation = typeof first === 'function' ? { type: 'default' } : (first ?? { type: 'default' });\n let body: () => T;\n let completion: (() => void) | undefined;\n let criteria: AnimationCompletionCriteria = 'logicallyComplete';\n if (typeof first === 'function') {\n body = first;\n } else if (typeof second === 'function') {\n body = second;\n completion = third as (() => void) | undefined;\n } else {\n criteria = second?.completionCriteria ?? 'logicallyComplete';\n body = third as () => T;\n completion = fourth;\n }\n const serial = completion ? nextCompletionSerial++ : 0;\n for (const tree of roots) {\n tree.pendingAnimation = animation;\n if (completion) tree.pendingCompletion = { serial, criteria, callback: completion };\n }\n try {\n return reconciler.flushSyncFromReconciler(body);\n } finally {\n let committed = false;\n for (const tree of roots) {\n tree.pendingAnimation = undefined;\n tree.pendingCompletion = undefined;\n if (completion && tree.awaitsCompletion(serial)) committed = true;\n }\n // Nothing rendered, so nothing will animate: the completion runs now, as SwiftUI's does.\n if (completion && !committed) completion();\n }\n}\n","/**\n * A tree drawn by another root. `createRemoteRoot` keeps a mirror of the\n * elements a second SwiftUI root emits (one in a sandbox, a worker, another\n * runtime: anything that produces the ops protocol), and `RemoteTree` draws\n * the mirror as host elements inside a host tree, forwarding the events the\n * renderer sends those elements back to the root that owns them. Everything\n * stays synchronous: a tap mirrored to the child runs its handler, the\n * child's pass re-enters `applyOps`, and the host's own pass draws the result\n * before the tap returns.\n */\n\nimport type { Animation, Op, RendererEvent } from '@swiftbrowser/web/src/protocol';\nimport type { Environment } from '../environment';\nimport type { AddressedEvent, EventHandlers } from './instance';\nimport { stampNextCommit } from './root';\nimport type { HostTree } from './tree';\nimport { registerBitmapSourceOp } from '../bitmaps';\n\n/** An element of the child's tree as the mirror holds it. */\nexport interface MirrorNode {\n id: number;\n kind: string;\n props: Record<string, unknown>;\n children: MirrorNode[];\n parent: MirrorNode | null;\n}\n\nexport interface RemoteRoot {\n /** The child root's ops, one pass at a time (each ending in `commit`). */\n applyOps(ops: readonly Op[]): void;\n /** Where the events for the child's elements go: its root's `dispatch`. */\n onEvent(handler: (event: RendererEvent) => void): void;\n /** Where the host's environment goes: its root's `setEnvironment`. */\n onEnvironment(handler: (environment: Environment) => void): void;\n /** An event for the child (by the child's element id, or unaddressed). */\n dispatch(event: RendererEvent): void;\n setEnvironment(environment: Environment): void;\n /** For `useSyncExternalStore`: the version moves on every `commit`. */\n subscribe(listener: () => void): () => void;\n getVersion(): number;\n /** The mirror: element 0, whose children are the child's top-level elements (hoisted sheets and alerts last). */\n readonly root: MirrorNode;\n /** The mirrored element with that id (the child's own id), if it is there. */\n node(id: number): MirrorNode | undefined;\n /** What the child's root carries (a title with no screen of its own, a color scheme); `update` of element 0. */\n readonly rootProps: Record<string, unknown>;\n /** The handlers a mirrored element gets: every event forwarded to the child under the child's id. */\n handlersFor(id: number): EventHandlers;\n /** `RemoteTree` names the tree it draws into, so a child's animated pass animates that tree's. */\n attach(tree: HostTree | null): void;\n /** Forget the mirror and the handlers; the child root is the caller's to unmount. */\n dispose(): void;\n}\n\nexport function createRemoteRoot(): RemoteRoot {\n const root: MirrorNode = { id: 0, kind: 'root', props: {}, children: [], parent: null };\n const nodes = new Map<number, MirrorNode>([[0, root]]);\n const handlers = new Map<number, EventHandlers>();\n const listeners = new Set<() => void>();\n let version = 0;\n let rootProps: Record<string, unknown> = {};\n let eventHandler: ((event: RendererEvent) => void) | undefined;\n let environmentHandler: ((environment: Environment) => void) | undefined;\n let lastEnvironment: Environment | undefined;\n let hostTree: HostTree | null = null;\n\n const detach = (node: MirrorNode): void => {\n if (!node.parent) return;\n const siblings = node.parent.children;\n const at = siblings.indexOf(node);\n if (at >= 0) siblings.splice(at, 1);\n node.parent = null;\n };\n const forget = (node: MirrorNode): void => {\n nodes.delete(node.id);\n handlers.delete(node.id);\n for (const child of node.children) forget(child);\n };\n const notify = (): void => {\n version += 1;\n for (const listener of listeners) listener();\n };\n\n const remote: RemoteRoot = {\n applyOps(ops) {\n let commit: { animation?: Animation; completion?: number; completionCriteria?: 'logicallyComplete' | 'removed' } | null = null;\n for (const op of ops) {\n switch (op.op) {\n case 'create': {\n if (nodes.has(op.id)) throw new Error(`remote tree: element ${op.id} created twice`);\n nodes.set(op.id, { id: op.id, kind: op.kind, props: op.props as Record<string, unknown>, children: [], parent: null });\n break;\n }\n case 'update': {\n if (op.id === 0) {\n rootProps = op.props as Record<string, unknown>;\n break;\n }\n const node = nodes.get(op.id);\n if (!node) throw new Error(`remote tree: update of unknown element ${op.id}`);\n node.props = op.props as Record<string, unknown>;\n break;\n }\n case 'insert': {\n const node = nodes.get(op.id);\n const parent = nodes.get(op.parent);\n if (!node || !parent) throw new Error(`remote tree: insert of ${op.id} into ${op.parent}: unknown element`);\n detach(node);\n parent.children.splice(op.index, 0, node);\n node.parent = parent;\n break;\n }\n case 'remove': {\n const node = nodes.get(op.id);\n if (!node) break;\n detach(node);\n forget(node);\n break;\n }\n case 'commit':\n commit = op;\n break;\n case 'imagedata':\n // A bitmap source: kept here, so the host's tree sends it before the first image that draws it.\n registerBitmapSourceOp(op);\n break;\n default:\n // `defaults`, `request`, `swiftdata`: the child has no loader here.\n break;\n }\n }\n if (!commit) return;\n const { animation, completion, completionCriteria } = commit;\n const answer = completion === undefined ? undefined : (): void => remote.dispatch({ type: 'animationcomplete', serial: completion });\n if (animation && hostTree) {\n // The host's pass carries the child's animation; the renderer's `animationcomplete` for it answers the child's serial.\n stampNextCommit(hostTree, animation, answer && { criteria: completionCriteria ?? 'logicallyComplete', callback: answer });\n notify();\n return;\n }\n notify();\n answer?.();\n },\n node(id) {\n return nodes.get(id);\n },\n onEvent(handler) {\n eventHandler = handler;\n },\n onEnvironment(handler) {\n environmentHandler = handler;\n if (lastEnvironment) handler(lastEnvironment);\n },\n dispatch(event) {\n eventHandler?.(event);\n },\n setEnvironment(environment) {\n if (\n lastEnvironment &&\n lastEnvironment.colorScheme === environment.colorScheme &&\n lastEnvironment.dynamicTypeSize === environment.dynamicTypeSize &&\n lastEnvironment.horizontalSizeClass === environment.horizontalSizeClass &&\n lastEnvironment.scenePhase === environment.scenePhase &&\n lastEnvironment.platform === environment.platform\n )\n return;\n lastEnvironment = environment;\n environmentHandler?.(environment);\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n getVersion: () => version,\n get root() {\n return root;\n },\n get rootProps() {\n return rootProps;\n },\n attach(tree) {\n hostTree = tree;\n },\n handlersFor(id) {\n let on = handlers.get(id);\n if (!on) {\n on = { '*': (event: AddressedEvent) => remote.dispatch({ ...event, id } as RendererEvent) };\n handlers.set(id, on);\n }\n return on;\n },\n dispose() {\n root.children = [];\n nodes.clear();\n nodes.set(0, root);\n handlers.clear();\n listeners.clear();\n eventHandler = undefined;\n environmentHandler = undefined;\n hostTree = null;\n },\n };\n return remote;\n}\n","import { createElement, type ReactElement, type ReactNode } from 'react';\nimport type { EventHandlers, HoistTarget, HostProps } from './instance';\n\n/** A host element: the intrinsic `sb` with a protocol kind and props. */\nexport function sb(\n kind: string,\n props?: Record<string, unknown>,\n on?: EventHandlers,\n children?: ReactNode,\n target?: HoistTarget,\n): ReactElement {\n const hostProps: HostProps = { kind };\n if (props) hostProps.props = props;\n if (on) hostProps.on = on;\n if (target) hostProps.target = target;\n return children === undefined ? createElement('sb', hostProps) : createElement('sb', hostProps, children);\n}\n","/**\n * The environment a presentation carries. SwiftUI's sheets, full-screen\n * covers and popovers inherit the environment of the view that presents\n * them: a `.defaultMinListRowHeight`, `.font` or `.tint` set around it\n * reaches the lists and text inside the sheet. Here a presentation is drawn\n * at the root, away from the `styled` wrappers around its presenter, so the\n * modifiers that set such values also record them in a React context\n * (outermost first), and a presentation replays them around its content.\n */\n\nimport type { Style } from '@swiftbrowser/web/src/protocol';\nimport { createContext, createElement, isValidElement, useContext, useMemo, type ReactElement, type ReactNode } from 'react';\nimport { sb } from './host/sb';\n\n/** The `styled` modifiers whose values are environment values a presentation inherits. */\nexport const INHERITED_STYLE_KEYS: ReadonlySet<string> = new Set([\n 'font',\n 'fontWeight',\n 'bold',\n 'monospacedDigit',\n 'tint',\n 'lineLimit',\n 'multilineTextAlignment',\n 'imageScale',\n 'defaultMinListRowHeight',\n]);\n\n/** The modifiers that present their content at the root (and so take the inherited styles with them). */\nexport const PRESENTATION_KEYS: ReadonlySet<string> = new Set(['sheet', 'fullScreenCover', 'popover']);\n\n/** The inherited styles set around this point, outermost first. */\nexport const InheritedStylesContext = createContext<readonly Style[]>([]);\n\nexport function useInheritedStyles(): readonly Style[] {\n return useContext(InheritedStylesContext);\n}\n\n/** The style of a `styled` element (`{}` for anything else). */\nexport function styleOf(node: ReactNode): Style {\n if (!isValidElement<{ kind?: unknown; props?: { style?: Style } }>(node) || node.props.kind !== 'styled') return {};\n return node.props.props?.style ?? {};\n}\n\n/** `children`, with `style` added to the inherited styles below it (an empty style adds nothing). */\nexport function InheritStyle({ style, children }: { style: Style; children?: ReactNode }): ReactNode {\n const parent = useContext(InheritedStylesContext);\n // A new style object each render with the same values keeps the list, so the views below that read it don't render again.\n const key = JSON.stringify(style);\n const value = useMemo(() => (key === '{}' ? parent : [...parent, style]), [parent, key]);\n return createElement(InheritedStylesContext.Provider, { value }, children);\n}\n\n/**\n * `content` inside `styles` (outermost first), as `styled` wrappers, and\n * with them as its inherited styles; `content` itself when there are none.\n */\nexport function replayStyles(styles: readonly Style[], content: ReactNode): ReactNode {\n if (styles.length === 0) return content;\n const provided = createElement(InheritedStylesContext.Provider, { value: styles }, content);\n return styles.reduceRight<ReactNode>((child, style): ReactElement => sb('styled', { style }, undefined, child), provided);\n}\n","import { createContext, useContext, type ReactNode } from 'react';\n\n/** What a `NavigationStack` offers the views inside it. */\nexport interface NavigationContextValue {\n push(value: unknown): void;\n pop(): void;\n /** The pushed values, and replacing them whole: how a `RemoteTree` keeps another root's stack in step with this one. */\n path: readonly unknown[];\n setPath(path: readonly unknown[]): void;\n /** `.navigationDestination(for:)`: how a pushed value becomes a screen. */\n registerDestination(destination: (value: unknown) => ReactNode): void;\n}\n\nexport const NavigationContext = createContext<NavigationContextValue | null>(null);\n\n/** The depth of the stack screen a view is in: 0 for the root screen, 1 for the first pushed one. */\nexport const ScreenDepthContext = createContext(0);\n\nexport function useScreenDepth(): number {\n return useContext(ScreenDepthContext);\n}\n\nexport function useNavigation(): NavigationContextValue | null {\n return useContext(NavigationContext);\n}\n\n/** Rendered by the `navigationDestination` modifier: registers the builder with the enclosing stack. */\nexport function RegisterDestination({ destination }: { destination: (value: never) => ReactNode }): null {\n const navigation = useContext(NavigationContext);\n navigation?.registerDestination(destination as (value: unknown) => ReactNode);\n return null;\n}\n","/**\n * `RemoteTree`: another root's tree drawn here. The child root (made with\n * `createSwiftUIRoot(sink, { remote: true })` wherever it runs) sends its\n * ops to a `RemoteRoot`'s `applyOps`; this component draws the mirror as\n * host elements, so the child's views take part in this tree's layout, its\n * screen and its renderer, web or native alike. What a child hoists to its\n * root for lack of a screen of its own joins this tree's enclosing screen\n * (a title, a toolbar, a search field) or root (a sheet, an alert).\n *\n * A child's `NavigationStack` becomes this tree's: inside a host stack, the\n * child's root screen is drawn in place (its title and toolbar on the host's\n * screen) and each screen the child pushes is pushed onto the host's stack,\n * so the child's screens slide in, get the host's back button and swipe,\n * and show in its bar like the host's own. The child's path stays the\n * truth: a push or pop in the child pushes or pops the host's screens, and\n * a pop in the host (back, swipe, a tap on an earlier screen) is sent to the\n * child as the renderer would send it (a `tap` on the popped screen), which\n * pops the child's path.\n *\n * A child's `NavigationSplitView` (a `navsplit` at its root, in a regular\n * width) belongs to the host's two stacks: its detail stack becomes the\n * host's as above, and its sidebar stack is the host's sidebar's to push\n * (`useRemoteSidebar`), so the host's own sidebar drills into the child's,\n * as iPadOS's sidebars drill, with a back button to the host's. In a compact\n * width the child's split view is a stack rooted at its sidebar, mapped as\n * any stack.\n */\n\nimport type { RendererEvent, Style } from '@swiftbrowser/web/src/protocol';\nimport { createElement, Fragment, useContext, useLayoutEffect, useRef, useSyncExternalStore, type ReactNode } from 'react';\nimport { EnvironmentContext } from '../environment';\nimport { HOIST_KIND, PREF_KIND } from '../host/instance';\nimport type { MirrorNode, RemoteRoot } from '../host/remote';\nimport { HostTreeContext } from '../host/root';\nimport { sb } from '../host/sb';\nimport { replayStyles, useInheritedStyles } from '../inheritedStyle';\nimport { useNavigation, useScreenDepth } from '../navigation-context';\n\n/** The host's view for an element kind of the child's own: its props as the child set them, and its children drawn as usual. */\nexport type HostElementRenderer = (props: Readonly<Record<string, unknown>>, children: ReactNode) => ReactNode;\n\nexport interface RemoteTreeProps {\n root: RemoteRoot;\n /**\n * The host's own views for element kinds the child makes up (a\n * `HostElement`'s `kind`, `'app:preview'` say), by kind: the host draws\n * each as it likes where the child put it, with the props the child gave\n * it. A kind no host draws is left to the renderer, which draws nothing\n * for it.\n */\n elements?: Readonly<Record<string, HostElementRenderer>>;\n /**\n * The child's stack's path to open with, as its screens' `route`s name it\n * (a link to one of the child's screens): set once, when the child's stack\n * first shows, so the child's destinations build the screens.\n */\n initialPath?: readonly unknown[];\n}\n\n/** The props a child's `navigationTitle` and friends leave on its root or its screens, lifted to this tree's screen. */\nconst SCREEN_PROPS = ['title', 'subtitle', 'displayMode', 'toolbarRole', 'navigationBarHidden', 'bottomBarHidden', 'statusBarHidden'];\n\n/** What the child left on a root or a screen for the host's screen: a screen's defaults (no title, `automatic`) are not choices. */\nfunction screenPrefs(props: Record<string, unknown>, key: string): ReactNode {\n const picked: Record<string, unknown> = {};\n for (const name of SCREEN_PROPS) if (name in props) picked[name] = props[name];\n if (picked['title'] === '') delete picked['title'];\n if (picked['displayMode'] === 'automatic') delete picked['displayMode'];\n return Object.keys(picked).length ? createElement(Fragment, { key }, sb(PREF_KIND, picked, undefined, undefined, 'navscreen')) : null;\n}\n\n/** The child's stack that becomes the host's: its first, outside sheets and alerts (which present their own); a split view's detail stack. */\nfunction findStack(node: MirrorNode): MirrorNode | null {\n for (const child of node.children) {\n if (child.kind === 'sheet' || child.kind === 'alert') continue;\n if (child.kind === 'navstack') return child;\n if (child.kind === 'navsplit') return splitDetailStack(child);\n const found = findStack(child);\n if (found) return found;\n }\n return null;\n}\n\n/** The child's split view (its `NavigationSplitView` in a regular width): the first `navsplit`, outside sheets, alerts and stacks. */\nfunction findSplit(node: MirrorNode): MirrorNode | null {\n for (const child of node.children) {\n if (child.kind === 'sheet' || child.kind === 'alert' || child.kind === 'navstack') continue;\n if (child.kind === 'navsplit') return child;\n const found = findSplit(child);\n if (found) return found;\n }\n return null;\n}\n\n/** A split view's columns, `[sidebar, detail]`, each a `navstack` (the shim wraps a bare detail in one). */\nconst splitSidebarStack = (split: MirrorNode): MirrorNode | null => (split.children[0]?.kind === 'navstack' ? split.children[0] : null);\nconst splitDetailStack = (split: MirrorNode): MirrorNode | null => (split.children[1]?.kind === 'navstack' ? split.children[1] : null);\n\nconst screensOf = (stack: MirrorNode | null): MirrorNode[] => (stack ? stack.children.filter((child) => child.kind === 'navscreen') : []);\n\ntype Elements = Readonly<Record<string, HostElementRenderer>> | undefined;\n\nfunction renderNode(root: RemoteRoot, node: MirrorNode, stack: MirrorNode | null, elements: Elements): ReactNode {\n // A `host` element's DOM lives in the child's page, which has none here.\n if (node.kind === 'host') return null;\n if (node === stack) {\n const first = screensOf(stack)[0];\n return createElement(Fragment, { key: node.id }, first ? renderScreen(root, first, stack, elements) : null);\n }\n // The child's split view inside a host stack: its detail column is drawn here (its stack the host's); its\n // sidebar column is the host's sidebar's to push (`useRemoteSidebar`).\n if (node.kind === 'navsplit' && stack && splitDetailStack(node) === stack) return createElement(Fragment, { key: node.id }, renderNode(root, stack, stack, elements));\n const children = node.children.length ? node.children.map((child) => renderNode(root, child, stack, elements)) : undefined;\n // A kind of the child's own, drawn by the host.\n const own = elements && Object.prototype.hasOwnProperty.call(elements, node.kind) ? elements[node.kind] : undefined;\n if (own) return createElement(Fragment, { key: node.id }, own(node.props, children));\n return createElement(Fragment, { key: node.id }, sb(node.kind, node.props, root.handlersFor(node.id), children));\n}\n\n/** A child's sheet, its content inside the host's inherited styles (`inheritedStyle.ts`). */\nfunction renderSheet(root: RemoteRoot, node: MirrorNode, stack: MirrorNode | null, inherited: readonly Style[], elements: Elements): ReactNode {\n const children = node.children.map((child) => renderNode(root, child, stack, elements));\n return createElement(Fragment, { key: node.id }, sb(node.kind, node.props, root.handlersFor(node.id), replayStyles(inherited, children)));\n}\n\n/** A child's screen drawn in the host's: its views in place, its title on the host's screen, its toolbar and search field in the host's bar. */\nfunction renderScreen(root: RemoteRoot, screen: MirrorNode, stack: MirrorNode | null, elements: Elements): ReactNode {\n const out: ReactNode[] = [screenPrefs(screen.props, '$screen')];\n for (const child of screen.children) {\n const drawn = renderNode(root, child, stack, elements);\n if (child.kind === 'toolbar' || child.kind === 'searchfield') out.push(createElement(Fragment, { key: child.id }, sb(HOIST_KIND, undefined, undefined, drawn, 'navscreen')));\n else out.push(drawn);\n }\n return createElement(Fragment, null, ...out);\n}\n\n/** A screen the child pushed (on its stack, or on its split view's sidebar stack), as a host stack shows it. */\nfunction RemoteScreen({ root, id, elements }: { root: RemoteRoot; id: number; elements: Elements }): ReactNode {\n useSyncExternalStore(root.subscribe, root.getVersion, root.getVersion);\n const screen = root.node(id);\n // Popped in the child: the host pops it next.\n if (!screen?.parent) return null;\n return renderScreen(root, screen, findStack(root.root), elements);\n}\n\n/**\n * A value on the host's path standing for one of the child's screens (a\n * pushed view, as `NavigationLink(destination:)` pushes), with the child's\n * value for it as plain data when it has one (`route`): what the host's\n * URL can name it by, and `initialPath` takes back.\n */\nexport interface PushedScreen {\n view: ReactNode;\n route?: unknown;\n}\n\n/** The host path values standing for a child's screens: one per screen, kept while it is the same screen with the same route. */\nfunction useScreenValues(root: RemoteRoot, elements: Elements): { valueFor(screen: MirrorNode): PushedScreen; keyOf(screen: MirrorNode): string; isOurs(value: unknown): boolean; forget(keys: readonly string[]): void } {\n // A screen is the same value while it is the same element with the same route; a new route (a screen\n // replaced in place) is a new value, so the host's path (its URL) follows.\n const values = useRef(new Map<string, PushedScreen>());\n const ours = useRef(new WeakSet<object>());\n const keyOf = (screen: MirrorNode): string => `${screen.id}:${JSON.stringify(screen.props['route'] ?? null)}`;\n const valueFor = (screen: MirrorNode): PushedScreen => {\n const key = keyOf(screen);\n let value = values.current.get(key);\n if (!value) {\n value = 'route' in screen.props ? { view: <RemoteScreen root={root} id={screen.id} elements={elements} />, route: screen.props['route'] } : { view: <RemoteScreen root={root} id={screen.id} elements={elements} /> };\n values.current.set(key, value);\n ours.current.add(value);\n }\n return value;\n };\n const isOurs = (value: unknown): boolean => typeof value === 'object' && value !== null && ours.current.has(value);\n const forget = (keys: readonly string[]): void => {\n for (const key of values.current.keys()) if (!keys.includes(key)) values.current.delete(key);\n };\n return { valueFor, keyOf, isOurs, forget };\n}\n\nexport interface RemoteSidebarOptions {\n /** Whether the child's sidebar is wanted on the host's sidebar now (the app is the one showing); false takes it off. */\n shown?: boolean;\n /** A value that changes when the app is chosen again: the child's sidebar comes back after a back past its root. */\n generation?: unknown;\n /** As `RemoteTree`'s `elements`: the host's views for the child's own element kinds. */\n elements?: Readonly<Record<string, HostElementRenderer>>;\n}\n\n/**\n * The child's sidebar, pushed on the host's own sidebar stack: the screens\n * of the child's `NavigationSplitView`'s sidebar column (its root first,\n * then what it pushed) kept on `path`, the bound path of the host's sidebar\n * `NavigationStack`, after whatever the host put there itself. The host's\n * sidebar then drills into the child's, with a back button to the host's\n * own, as iPadOS's Settings and Files drill their sidebars. A back past the\n * child's root screen shows the host's sidebar again until `shown` is set\n * anew (the app chosen again); a back out of a screen the child pushed in\n * its sidebar pops the child's sidebar stack, as a pop in the host's stack\n * pops the child's. Nothing while the child has no split view (a compact\n * width, where its sidebar is the root screen of the stack `RemoteTree`\n * maps), or while `root` is null.\n */\nexport function useRemoteSidebar(root: RemoteRoot | null, path: readonly unknown[], setPath: (path: readonly unknown[]) => void, options: RemoteSidebarOptions = {}): void {\n const shown = options.shown ?? true;\n useSyncExternalStore(root ? root.subscribe : noSubscribe, root ? root.getVersion : zero, root ? root.getVersion : zero);\n const { valueFor, keyOf, isOurs, forget } = useScreenValues(root ?? NO_ROOT, options.elements);\n const split = root ? findSplit(root.root) : null;\n const screens = split ? screensOf(splitSidebarStack(split)) : [];\n const dismissed = useRef(false);\n const lastKeys = useRef<string[]>([]);\n /** How many of the child's screens the host's path held after the last pass: fewer now means the host popped. */\n const lastMine = useRef(0);\n const last = useRef<{ root: RemoteRoot | null; shown: boolean; generation: unknown }>({ root: null, shown: false, generation: undefined });\n useLayoutEffect(() => {\n if (last.current.root !== root || (!last.current.shown && shown) || last.current.generation !== options.generation) dismissed.current = false;\n last.current = { root, shown, generation: options.generation };\n const keys = screens.map(keyOf);\n const wanted = shown && !dismissed.current ? screens.map(valueFor) : [];\n forget(keys);\n const hosts = path.filter((value) => !isOurs(value));\n const mine = path.filter(isOurs);\n const childMoved = keys.length !== lastKeys.current.length || keys.some((key, i) => key !== lastKeys.current[i]);\n lastKeys.current = keys;\n const popped = mine.length < lastMine.current;\n lastMine.current = mine.length;\n if (root && wanted.length > 0 && !childMoved && popped && mine.length < wanted.length && mine.every((value, i) => value === wanted[i])) {\n if (mine.length === 0) {\n // The host popped the child's sidebar root: the host's own sidebar shows until the child is shown anew.\n dismissed.current = true;\n return;\n }\n // The host popped a screen the child pushed in its sidebar: the child pops to the same place.\n root.dispatch({ type: 'tap', id: screens[mine.length]!.id } as RendererEvent);\n return;\n }\n if (mine.length === wanted.length && mine.every((value, i) => value === wanted[i])) return;\n lastMine.current = wanted.length;\n setPath([...hosts, ...wanted]);\n });\n}\n\nconst noSubscribe = (): (() => void) => () => {};\nconst zero = (): number => 0;\n/** A stand-in while there is no child, so `useScreenValues` keeps its hooks in order. */\nconst NO_ROOT: RemoteRoot = {\n applyOps() {},\n onEvent() {},\n onEnvironment() {},\n dispatch() {},\n setEnvironment() {},\n subscribe: noSubscribe,\n getVersion: zero,\n root: { id: 0, kind: 'root', props: {}, children: [], parent: null },\n node: () => undefined,\n rootProps: {},\n handlersFor: () => ({}),\n attach() {},\n dispose() {},\n};\n\nexport function RemoteTree({ root, initialPath, elements }: RemoteTreeProps): ReactNode {\n useSyncExternalStore(root.subscribe, root.getVersion, root.getVersion);\n const environment = useContext(EnvironmentContext);\n // The host's environment around this tree, which the child's sheets inherit as the child's own views do.\n const inherited = useInheritedStyles();\n const tree = useContext(HostTreeContext);\n const navigation = useNavigation();\n const depth = useScreenDepth();\n useLayoutEffect(() => {\n root.attach(tree);\n return () => root.attach(null);\n }, [root, tree]);\n useLayoutEffect(() => {\n root.setEnvironment(environment);\n }, [root, environment]);\n\n // Only inside a host stack does the child's become the host's (a split view's detail stack); elsewhere it is drawn as it is.\n const stack = navigation ? findStack(root.root) : null;\n const pushed = screensOf(stack).slice(1);\n const { valueFor, keyOf, isOurs, forget } = useScreenValues(root, elements);\n const lastPushed = useRef<string[]>([]);\n\n // A link's path, given to the child's stack once it shows (and before it has pushed anything of its own).\n const restored = useRef(false);\n useLayoutEffect(() => {\n if (restored.current) return;\n const childStack = findStack(root.root);\n if (!childStack) return;\n restored.current = true;\n if (initialPath?.length && screensOf(childStack).length === 1) root.dispatch({ type: 'setpath', id: childStack.id, path: [...initialPath] });\n });\n\n useLayoutEffect(() => {\n if (!navigation) return;\n const keys = pushed.map(keyOf);\n const wanted = pushed.map(valueFor);\n forget(keys);\n // The host's path from this screen on: the child's screens first, then whatever the host pushed over them.\n const tail = navigation.path.slice(depth);\n let shown = 0;\n while (shown < tail.length && isOurs(tail[shown])) shown += 1;\n const childMoved = keys.length !== lastPushed.current.length || keys.some((key, i) => key !== lastPushed.current[i]);\n lastPushed.current = keys;\n if (!childMoved && shown < wanted.length && tail.slice(0, shown).every((value, i) => value === wanted[i])) {\n // The host popped some of the child's screens (back, swipe): the child pops to the same place.\n root.dispatch({ type: 'tap', id: pushed[shown]!.id });\n return;\n }\n if (shown === wanted.length && wanted.every((value, i) => tail[i] === value)) return;\n // The child pushed or popped: the host's path follows. Screens the host pushed over the child's stay while the child's are unchanged.\n navigation.setPath([...navigation.path.slice(0, depth), ...wanted]);\n });\n\n const out: ReactNode[] = [screenPrefs(root.rootProps, '$root')];\n if ('colorScheme' in root.rootProps)\n out.push(createElement(Fragment, { key: '$scheme' }, sb(PREF_KIND, { colorScheme: root.rootProps['colorScheme'] }, undefined, undefined, 'root')));\n for (const child of root.root.children) {\n const drawn = child.kind === 'sheet' && inherited.length > 0 ? renderSheet(root, child, stack, inherited, elements) : renderNode(root, child, stack, elements);\n if (child.kind === 'sheet' || child.kind === 'alert') out.push(createElement(Fragment, { key: child.id }, sb(HOIST_KIND, undefined, undefined, drawn, 'root')));\n else if (child.kind === 'toolbar' || child.kind === 'searchfield') out.push(createElement(Fragment, { key: child.id }, sb(HOIST_KIND, undefined, undefined, drawn, 'navscreen')));\n else out.push(drawn);\n }\n return createElement(Fragment, null, ...out);\n}\n","/**\n * A `Binding<T>`: a `useState` pair, so `isOn={[downloads, setDownloads]}`\n * reads like `isOn: $downloads`. A plain value with an `onChange` handler is\n * accepted everywhere a binding is.\n */\nexport type Binding<T> = readonly [T, (value: T) => void];\n\nexport type BindingValue<T> = Binding<T> | T;\n\nexport function readBinding<T>(value: BindingValue<T>, onChange?: (value: T) => void): [T, (next: T) => void] {\n if (Array.isArray(value) && value.length === 2 && typeof value[1] === 'function') {\n const [current, set] = value as Binding<T>;\n return [current, set];\n }\n return [value as T, onChange ?? (() => {})];\n}\n","/**\n * `.draggable` and `.dropDestination`. What is dragged stays in React: a\n * lift (`dragstart`) remembers the payload, a drop naming its source hands\n * it to the destination, and `dragend` forgets it. Drops from outside the\n * page arrive as text and files.\n */\n\nimport { browserEnvironment } from '@swiftbrowser/web/src/hostRequests';\nimport type { DropItem } from '@swiftbrowser/web/src/protocol';\nimport type { ReactNode } from 'react';\nimport { sb } from './host/sb';\nimport type { DropDestinationModifier } from './modifiers';\n\nlet active: { id: number; payload: unknown } | null = null;\n\nexport function Draggable({ payload, children }: { payload: unknown; children?: ReactNode }): ReactNode {\n return sb(\n 'draggable',\n {},\n {\n dragstart: (event) => {\n active = { id: event.id, payload };\n },\n dragend: (event) => {\n if (active?.id === event.id) active = null;\n },\n },\n children,\n );\n}\n\n/**\n * Text as a string, a link as a `URL`, a file as a `File`: the browser's own\n * (a page's drops carry it by reference), one the native host left on disk\n * (read on demand), or one built from the bytes the event carried. A file\n * from a dropped folder is named by its path in it, the folder's name first\n * (`Photos/2025/a.jpg`), as `fileImporter` names a picked folder's files.\n */\nfunction itemValue(item: DropItem): unknown {\n if (item.text !== undefined) {\n if (item.type === 'text/uri-list') {\n try {\n return new URL(item.text.split(/\\r?\\n/)[0]!.trim());\n } catch {\n return item.text;\n }\n }\n return item.text;\n }\n const name = item.path ?? item.name ?? 'file';\n if (item.file) {\n const file = item.file;\n return item.path !== undefined && item.path !== file.name ? new File([file], item.path, { type: file.type, lastModified: file.lastModified }) : file;\n }\n if (item.url !== undefined && item.data === undefined) {\n const fromReference = browserEnvironment.fileFromReference;\n if (fromReference) {\n return fromReference({ type: item.type, name, url: item.url, ...(item.path !== undefined ? { path: item.path } : {}), ...(item.size !== undefined ? { size: item.size } : {}) });\n }\n }\n const binary = atob(item.data ?? '');\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return typeof File !== 'undefined' ? new File([bytes], name, { type: item.type }) : bytes;\n}\n\nexport function DropDestination({ action, isTargeted, accepts, children }: DropDestinationModifier & { children?: ReactNode }): ReactNode {\n return sb(\n 'dropdestination',\n { accepts: accepts ?? [] },\n {\n drop: (event) => {\n if (event.phase === 'entered') {\n isTargeted?.(true);\n return;\n }\n isTargeted?.(false);\n if (event.phase !== 'performed') return;\n let items: unknown[];\n if (event.source !== undefined) items = active && active.id === event.source ? [active.payload] : [];\n else items = (event.items ?? []).map(itemValue);\n if (items.length > 0) action(items, { x: event.x, y: event.y });\n },\n },\n children,\n );\n}\n","/**\n * `.fileImporter(isPresented:allowedContentTypes:…)`: the browser's file\n * chooser in place of the Files app. A browser opens a chooser only within a\n * tap; a tap's state changes render before its event returns (host/root.ts),\n * so the layout effect that sees `isPresented` turn true opens it in time.\n * Set `isPresented` from a button's action. `onCompletion` gets the chosen\n * `File`s; a dismissed chooser calls `onCancellation` instead, as on iOS.\n */\n\nimport { browserEnvironment } from '@swiftbrowser/web/src/hostRequests';\nimport { useLayoutEffect, useRef, type ReactNode } from 'react';\nimport { readBinding, type BindingValue } from './binding';\n\nexport interface FileImporterModifier {\n isPresented: BindingValue<boolean>;\n /**\n * What the chooser offers (its `accept`): MIME types, patterns (`image/*`) or extensions (`.svg`); any file when\n * empty. `'public.folder'` (SwiftUI's `.folder`) makes it a folder chooser: `onCompletion` then gets the folder's\n * files, at any depth, that the other types allow, each named by its path from the folder, the folder's name first\n * (`Bank/Leads/Saw.fxp`).\n */\n allowedContentTypes: string[];\n allowsMultipleSelection?: boolean;\n onCompletion: (files: File[]) => void;\n onCancellation?: () => void;\n}\n\nexport function FileImporterPresenter(spec: FileImporterModifier): ReactNode {\n const [presented, setPresented] = readBinding(spec.isPresented);\n const latest = useRef(spec);\n latest.current = spec;\n const choosing = useRef(false);\n useLayoutEffect(() => {\n if (!presented || choosing.current) return;\n const { allowedContentTypes, allowsMultipleSelection } = latest.current;\n const pick = browserEnvironment.pickFiles;\n if (!pick) {\n setPresented(false);\n latest.current.onCancellation?.();\n return;\n }\n choosing.current = true;\n void pick({ accept: allowedContentTypes.join(','), multiple: allowsMultipleSelection === true }).then((files) => {\n choosing.current = false;\n setPresented(false);\n if (files.length > 0) latest.current.onCompletion(files);\n else latest.current.onCancellation?.();\n });\n }, [presented, setPresented]);\n return null;\n}\n","/**\n * `.fileExporter(isPresented:document:contentType:defaultFilename:…)`: the\n * document goes where the viewer chooses. A page shows a save dialog where\n * the browser has one (the File System Access API) and downloads the file\n * elsewhere; the native app shows the document picker (the Files app). Set\n * `isPresented` from a button's action, as a dialog opens only within a tap.\n * `onCompletion` gets where it went (`saved` or `downloaded`, with the\n * host's URLs where it knows them); a dismissed dialog calls `onCancellation`.\n */\n\nimport { exportFiles, type ExportFilesResult } from '@swiftbrowser/web/src/hostRequests';\nimport { useLayoutEffect, useRef, type ReactNode } from 'react';\nimport { readBinding, type BindingValue } from './binding';\n\nexport type { ExportFilesResult };\n\n/** What a `fileExporter` writes: text, bytes or a Blob; a `File` brings its own name and type. */\nexport type ExportDocument = string | Uint8Array | ArrayBuffer | Blob;\n\nexport interface FileExporterModifier {\n isPresented: BindingValue<boolean>;\n /** The document, or several; `null` presents nothing (the exporter closes at once). */\n document: ExportDocument | ExportDocument[] | null;\n /** The MIME type (`text/plain`), for a document that is not a typed Blob. */\n contentType?: string;\n /** The name offered (`Notes.txt`); the type's extension is added when the name has none. `Untitled` by default. */\n defaultFilename?: string;\n onCompletion?: (result: ExportFilesResult) => void;\n onCancellation?: () => void;\n onError?: (error: unknown) => void;\n}\n\nconst EXTENSIONS: Record<string, string> = {\n 'text/plain': 'txt',\n 'text/csv': 'csv',\n 'text/markdown': 'md',\n 'text/html': 'html',\n 'application/json': 'json',\n 'application/pdf': 'pdf',\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/svg+xml': 'svg',\n 'audio/mp4': 'm4a',\n 'video/mp4': 'mp4',\n};\n\n/** The file a document is exported as: named, typed, with the type's extension when the name has none. */\nexport function exportFile(document: ExportDocument, contentType: string | undefined, defaultFilename: string | undefined, index = 0): File {\n const type = (document instanceof Blob && document.type) || contentType || 'application/octet-stream';\n let name = defaultFilename ?? (document instanceof File ? document.name : index === 0 ? 'Untitled' : `Untitled ${index + 1}`);\n name = name.replace(/[\\\\/:*?\"<>|]+/g, '-').trim() || 'Untitled';\n const extension = EXTENSIONS[type.split(';')[0]!.trim()];\n if (extension && !/\\.[A-Za-z0-9]{1,8}$/.test(name)) name = `${name}.${extension}`;\n if (document instanceof File && document.name === name && document.type === type) return document;\n const bytes = typeof document === 'string' ? new TextEncoder().encode(document) : document;\n return new File([bytes as BlobPart], name, { type });\n}\n\nexport function FileExporterPresenter(spec: FileExporterModifier): ReactNode {\n const [presented, setPresented] = readBinding(spec.isPresented);\n const latest = useRef(spec);\n latest.current = spec;\n const exporting = useRef(false);\n useLayoutEffect(() => {\n if (!presented || exporting.current) return;\n const { document, contentType, defaultFilename } = latest.current;\n const documents = document === null ? [] : Array.isArray(document) ? document : [document];\n if (documents.length === 0) {\n setPresented(false);\n latest.current.onCancellation?.();\n return;\n }\n exporting.current = true;\n const files = documents.map((item, index) => exportFile(item, contentType, defaultFilename, index));\n exportFiles(files).then(\n (result) => {\n exporting.current = false;\n setPresented(false);\n if (result.outcome === 'cancelled') latest.current.onCancellation?.();\n else latest.current.onCompletion?.(result);\n },\n (error: unknown) => {\n exporting.current = false;\n setPresented(false);\n latest.current.onError?.(error);\n },\n );\n }, [presented, setPresented]);\n return null;\n}\n","/**\n * List rows that can be selected or deleted are wrapped in a `listrow`\n * (docs/ops-protocol.md, \"Edit mode and list selection\"). `ForEach`'s\n * `onDelete` and a `List`'s `selection` both end in this component; a row\n * that is neither selectable nor deletable renders bare.\n */\n\nimport { createContext, useContext, type ReactNode } from 'react';\nimport { sb } from '../host/sb';\n\nexport interface ListSelection {\n isSelected(tag: unknown): boolean;\n select(tag: unknown): void;\n editing: boolean;\n}\n\nexport const ListSelectionContext = createContext<ListSelection | null>(null);\n\nexport interface RowProps {\n /** The row's tag (`.tag`, a `NavigationLink` value or a `ForEach` id). */\n tag?: unknown;\n /** `ForEach` with `onDelete`: what a swipe or the edit-mode minus does. */\n onDelete?: () => void;\n deletable?: boolean;\n /**\n * `ForEach` with `onMove`: called with the destination offset in the\n * `ForEach`'s data (as `move(fromOffsets:toOffset:)` takes it) when the\n * row was dragged to a new place.\n */\n onMove?: (to: number) => void;\n movable?: boolean;\n /** The row's offset in its `ForEach`. */\n index?: number;\n /** The row's index among its container's children (set by `List` / `Section`), for mapping `move`. */\n containerIndex?: number;\n children?: ReactNode;\n}\n\nexport function Row({ tag, onDelete, deletable, onMove, movable, index, containerIndex, children }: RowProps): ReactNode {\n const selection = useContext(ListSelectionContext);\n const selectable = selection !== null && tag !== undefined;\n const canDelete = onDelete !== undefined && deletable !== false;\n const canMove = onMove !== undefined && movable !== false;\n if (!selectable && !canDelete && !canMove) return children;\n const props: Record<string, unknown> = {};\n if (selectable) {\n props['selectable'] = true;\n props['selected'] = selection.isSelected(tag);\n }\n if (canDelete) props['deletable'] = true;\n if (canMove) props['movable'] = true;\n return sb(\n 'listrow',\n props,\n {\n tap: () => selectable && selection.select(tag),\n delete: () => onDelete?.(),\n move: (event) => {\n // `to` counts the container's children; the ForEach's first row is\n // `containerIndex - index` children in.\n const start = (containerIndex ?? index ?? 0) - (index ?? 0);\n onMove?.(Math.max(0, event.to - start));\n },\n },\n children,\n );\n}\n","/**\n * Value types of the SwiftUI API as plain data: colors and shape styles,\n * fonts, frames, insets and gradients, encoded as the ops protocol wants them.\n */\n\nimport type {\n Color as ProtocolColor,\n EdgeInsets,\n Font as ProtocolFont,\n FontDesign,\n FontWeight,\n Frame,\n FrameAlignment,\n GradientStop,\n NamedColor,\n RGBAColor,\n SemanticColorName,\n ShapeStyle,\n TextStyle,\n UnitPoint,\n} from '@swiftbrowser/web/src/protocol';\n\nexport type { EdgeInsets, FontDesign, FontWeight, Frame, FrameAlignment, ShapeStyle, TextStyle, UnitPoint };\n/** The protocol's color value (the `Color` export is the view, with the color helpers as members). */\nexport type ColorType = ProtocolColor;\n/** The protocol's font value (the `Font` export is the helper object). */\nexport type FontType = ProtocolFont;\n\n// ---------------------------------------------------------------------------\n// Colors and shape styles\n// ---------------------------------------------------------------------------\n\n/** `.primary` … `.quaternary` as foreground styles (the label colors) or fills. */\nexport type HierarchyName = 'primary' | 'secondary' | 'tertiary' | 'quaternary';\n\n/**\n * A style as a prop: a protocol value, or a name. A hierarchy name\n * (`\"secondary\"`) is the hierarchical style, as `.foregroundStyle(.secondary)`\n * is; a palette or UIKit name (`\"red\"`, `\"secondarySystemBackground\"`) is that\n * semantic color; `\"white\"`, `\"black\"` and `\"#rrggbb[aa]\"` are explicit colors.\n */\nexport type StyleValue = ShapeStyle | HierarchyName | SemanticColorName | 'white' | 'black' | `#${string}`;\n\nconst HIERARCHY: Record<HierarchyName, 1 | 2 | 3 | 4> = { primary: 1, secondary: 2, tertiary: 3, quaternary: 4 };\n\nexport function rgb(r: number, g: number, b: number, a = 1): RGBAColor {\n return { r, g, b, a };\n}\n\nexport function hex(value: string): RGBAColor {\n const digits = value.replace('#', '');\n const wide = digits.length === 3 || digits.length === 4 ? [...digits].map((d) => d + d).join('') : digits;\n const n = (at: number): number => parseInt(wide.slice(at, at + 2), 16) / 255;\n return { r: n(0), g: n(2), b: n(4), a: wide.length >= 8 ? n(6) : 1 };\n}\n\nexport function shapeStyle(value: StyleValue): ShapeStyle {\n if (typeof value !== 'string') return value;\n if (value in HIERARCHY) return { hierarchical: HIERARCHY[value as HierarchyName] };\n if (value === 'white') return rgb(1, 1, 1);\n if (value === 'black') return rgb(0, 0, 0);\n if (value.startsWith('#')) return hex(value);\n return { name: value as SemanticColorName };\n}\n\n/** A color as a prop: a protocol color or a name (hierarchy names are not colors). */\nexport type ColorValue = ProtocolColor | SemanticColorName | 'white' | 'black' | `#${string}`;\n\nexport function color(value: ColorValue): ProtocolColor {\n return shapeStyle(value as StyleValue) as ProtocolColor;\n}\n\n/** `color.opacity(a)` */\nexport function opacity(value: ColorValue, a: number): ProtocolColor;\nexport function opacity(value: StyleValue, a: number): ShapeStyle;\nexport function opacity(value: StyleValue, a: number): ShapeStyle {\n const style = shapeStyle(value);\n if ('r' in style) return { ...style, a: style.a * a };\n if ('name' in style) return { ...style, a: ((style as NamedColor).a ?? 1) * a };\n if ('named' in style) return { ...style, opacity: style.opacity * a };\n return { ...style, opacity: ((style as { opacity?: number }).opacity ?? 1) * a };\n}\n\n/** `color.gradient`: the subtle vertical gradient iOS derives from a color. */\nexport function gradient(value: ColorValue): ShapeStyle {\n return { colorGradient: color(value) };\n}\n\n/** `Color.red`, `Color.white`, `Color(.secondarySystemBackground)`… (`Color` itself, a view, carries these as members). */\nexport const ColorValues = {\n red: { name: 'red' } as ProtocolColor,\n orange: { name: 'orange' } as ProtocolColor,\n yellow: { name: 'yellow' } as ProtocolColor,\n green: { name: 'green' } as ProtocolColor,\n mint: { name: 'mint' } as ProtocolColor,\n teal: { name: 'teal' } as ProtocolColor,\n cyan: { name: 'cyan' } as ProtocolColor,\n blue: { name: 'blue' } as ProtocolColor,\n indigo: { name: 'indigo' } as ProtocolColor,\n purple: { name: 'purple' } as ProtocolColor,\n pink: { name: 'pink' } as ProtocolColor,\n brown: { name: 'brown' } as ProtocolColor,\n gray: { name: 'gray' } as ProtocolColor,\n white: rgb(1, 1, 1) as ProtocolColor,\n black: rgb(0, 0, 0) as ProtocolColor,\n clear: { name: 'clear' } as ProtocolColor,\n primary: { name: 'primary' } as ProtocolColor,\n secondary: { name: 'secondary' } as ProtocolColor,\n accent: { name: 'accent' } as ProtocolColor,\n /** `Color(uiColor:)` / `Color(.name)`: a UIKit semantic color by its iOS name. */\n system: (name: SemanticColorName): ProtocolColor => ({ name }),\n rgb,\n hex,\n opacity,\n gradient,\n};\n\n// ---------------------------------------------------------------------------\n// Unit points and gradients\n// ---------------------------------------------------------------------------\n\nexport type UnitPointName =\n | 'center'\n | 'top'\n | 'bottom'\n | 'leading'\n | 'trailing'\n | 'topLeading'\n | 'topTrailing'\n | 'bottomLeading'\n | 'bottomTrailing';\nexport type UnitPointValue = UnitPoint | UnitPointName;\n\nconst UNIT_POINTS: Record<UnitPointName, UnitPoint> = {\n center: { x: 0.5, y: 0.5 },\n top: { x: 0.5, y: 0 },\n bottom: { x: 0.5, y: 1 },\n leading: { x: 0, y: 0.5 },\n trailing: { x: 1, y: 0.5 },\n topLeading: { x: 0, y: 0 },\n topTrailing: { x: 1, y: 0 },\n bottomLeading: { x: 0, y: 1 },\n bottomTrailing: { x: 1, y: 1 },\n};\n\nexport function unitPoint(value: UnitPointValue): UnitPoint {\n return typeof value === 'string' ? UNIT_POINTS[value] : value;\n}\n\nexport interface GradientColors {\n /** Evenly spaced colors, or explicit stops. */\n colors?: ColorValue[];\n stops?: { color: ColorValue; location: number }[];\n}\n\nfunction stops(spec: GradientColors): GradientStop[] {\n if (spec.stops) return spec.stops.map((stop) => ({ color: color(stop.color), location: stop.location }));\n const colors = spec.colors ?? [];\n const last = Math.max(colors.length - 1, 1);\n return colors.map((value, index) => ({ color: color(value), location: index / last }));\n}\n\nexport function LinearGradient(spec: GradientColors & { startPoint: UnitPointValue; endPoint: UnitPointValue }): ShapeStyle {\n return { linearGradient: { stops: stops(spec), start: unitPoint(spec.startPoint), end: unitPoint(spec.endPoint) } };\n}\n\nexport function RadialGradient(\n spec: GradientColors & { center: UnitPointValue; startRadius: number; endRadius: number },\n): ShapeStyle {\n return {\n radialGradient: { stops: stops(spec), center: unitPoint(spec.center), startRadius: spec.startRadius, endRadius: spec.endRadius },\n };\n}\n\nexport function AngularGradient(\n spec: GradientColors & { center: UnitPointValue; startAngle?: number; endAngle?: number },\n): ShapeStyle {\n return {\n angularGradient: {\n stops: stops(spec),\n center: unitPoint(spec.center),\n startAngle: spec.startAngle ?? 0,\n endAngle: spec.endAngle ?? 360,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Fonts\n// ---------------------------------------------------------------------------\n\n/** A font as a prop: a text style name (`\"headline\"`) or a `Font` object. */\nexport type FontValue = TextStyle | ProtocolFont;\n\nexport function font(value: FontValue): ProtocolFont {\n return typeof value === 'string' ? { textStyle: value } : value;\n}\n\n/** `Font.system(size:weight:design:)` */\nexport function system(size: number, weight?: FontWeight, design?: FontDesign): ProtocolFont;\n/** `Font.system(.body, design:weight:)` */\nexport function system(textStyle: TextStyle, design?: FontDesign, weight?: FontWeight): ProtocolFont;\nexport function system(first: number | TextStyle, second?: FontWeight | FontDesign, third?: FontDesign | FontWeight): ProtocolFont {\n const result: ProtocolFont = typeof first === 'number' ? { size: first } : { textStyle: first };\n const weight = typeof first === 'number' ? (second as FontWeight | undefined) : (third as FontWeight | undefined);\n const design = typeof first === 'number' ? (third as FontDesign | undefined) : (second as FontDesign | undefined);\n if (weight) result.weight = weight;\n if (design) result.design = design;\n return result;\n}\n\n/** `.font(.title2.bold())`, `.font(.subheadline.weight(.semibold))` */\nexport function weighted(value: FontValue, weight: FontWeight): ProtocolFont {\n return { ...font(value), weight };\n}\n\nexport const Font = { system, weighted, bold: (value: FontValue): ProtocolFont => weighted(value, 'bold') };\n\n// ---------------------------------------------------------------------------\n// Frames and insets\n// ---------------------------------------------------------------------------\n\n/** `Infinity` stands for `.infinity`. */\nexport interface FrameValue {\n width?: number;\n height?: number;\n minWidth?: number;\n maxWidth?: number;\n minHeight?: number;\n maxHeight?: number;\n alignment?: FrameAlignment;\n}\n\nexport function frame(value: FrameValue): Frame {\n const dimension = (n: number | undefined): number | 'infinity' | undefined =>\n n === undefined ? undefined : n === Infinity ? 'infinity' : n;\n const result: Frame = { alignment: value.alignment ?? 'center' };\n if (value.width !== undefined) result.width = value.width;\n if (value.height !== undefined) result.height = value.height;\n const minWidth = dimension(value.minWidth);\n const maxWidth = dimension(value.maxWidth);\n const minHeight = dimension(value.minHeight);\n const maxHeight = dimension(value.maxHeight);\n if (minWidth !== undefined) result.minWidth = minWidth;\n if (maxWidth !== undefined) result.maxWidth = maxWidth;\n if (minHeight !== undefined) result.minHeight = minHeight;\n if (maxHeight !== undefined) result.maxHeight = maxHeight;\n return result;\n}\n\nexport type EdgeName = 'top' | 'bottom' | 'leading' | 'trailing' | 'horizontal' | 'vertical' | 'all';\n/**\n * `.padding()` (`true`), `.padding(12)`, `.padding(.vertical, 6)` (`[\"vertical\", 6]`),\n * `.padding([.top, .leading], 8)`, or explicit insets.\n */\nexport type PaddingValue = true | number | EdgeInsets | [EdgeName | EdgeName[], number?];\n\nexport const DEFAULT_PADDING = 16;\n\nexport function padding(value: PaddingValue): EdgeInsets {\n if (value === true) return insets(['all'], DEFAULT_PADDING);\n if (typeof value === 'number') return insets(['all'], value);\n if (Array.isArray(value)) {\n const [edges, amount] = value;\n return insets(Array.isArray(edges) ? edges : [edges], amount ?? DEFAULT_PADDING);\n }\n return value;\n}\n\nexport function insets(edges: EdgeName[], amount: number): EdgeInsets {\n const result: EdgeInsets = {};\n for (const edge of edges) {\n if (edge === 'all' || edge === 'vertical' || edge === 'top') result.top = amount;\n if (edge === 'all' || edge === 'vertical' || edge === 'bottom') result.bottom = amount;\n if (edge === 'all' || edge === 'horizontal' || edge === 'leading') result.leading = amount;\n if (edge === 'all' || edge === 'horizontal' || edge === 'trailing') result.trailing = amount;\n }\n return result;\n}\n","/**\n * `ScrollViewReader` and `.id` (the `scrollID` modifier): `proxy.scrollTo(id)`\n * marks the view with that id with a `scrollTo` command whose serial is new,\n * and the page scrolls every scrolling ancestor to it after the pass.\n * `proxy.scrollTo({ x, y })` (SwiftUI's `ScrollPosition.scrollTo(x:y:)`)\n * puts a `scrollOffset` command on the scroll views inside the reader\n * instead, as does a `scrollPosition` binding set to a point.\n */\n\nimport type { ScrollAxes, ScrollOffsetCommand, UnitPoint } from '@swiftbrowser/web/src/protocol';\nimport { createContext, useContext, useRef, useState, type ReactNode } from 'react';\nimport { readBinding, type BindingValue } from './binding';\nimport type { EventHandlers } from './host/instance';\nimport { sb } from './host/sb';\nimport { styled } from './modifiers';\nimport { unitPoint, type UnitPointValue } from './values';\n\n/** A target to scroll to, or (`point`) an offset for the scroll views inside the reader. */\ntype ScrollRequest = TargetRequest | PointRequest;\n\ninterface TargetRequest {\n id: string | number;\n anchor: UnitPoint | null;\n serial: number;\n /** The axes to scroll on; both when absent. */\n axes?: ScrollAxes;\n}\n\ninterface PointRequest {\n point: ScrollPoint;\n serial: number;\n}\n\n/** A content offset; an axis left out keeps its offset. */\nexport interface ScrollPoint {\n x?: number;\n y?: number;\n}\n\nconst isPoint = (value: unknown): value is ScrollPoint => typeof value === 'object' && value !== null && ('x' in value || 'y' in value);\n\n/** The `scrollTo` style a request becomes on its target. */\nfunction command(request: TargetRequest): { anchor: UnitPoint | null; serial: number; axes?: ScrollAxes } {\n return request.axes ? { anchor: request.anchor, serial: request.serial, axes: request.axes } : { anchor: request.anchor, serial: request.serial };\n}\n\n/** The `scrollOffset` prop a point request becomes on a scroll view. */\nfunction offsetCommand(request: PointRequest): ScrollOffsetCommand {\n const out: ScrollOffsetCommand = { serial: request.serial };\n if (typeof request.point.x === 'number') out.x = request.point.x;\n if (typeof request.point.y === 'number') out.y = request.point.y;\n return out;\n}\n\nexport const ScrollRequestContext = createContext<ScrollRequest | null>(null);\nlet nextSerial = 1;\n\nexport interface ScrollViewProxy {\n /**\n * Scroll so `anchor` of the view with that `scrollID` meets the same point\n * of the visible area; no anchor: as little as shows it. Every scrolling\n * ancestor moves on its axes, or only on `axes` when given (a horizontal\n * pager inside a list: `{ axes: 'horizontal' }` leaves the list where it is).\n */\n scrollTo(id: string | number, anchor?: UnitPointValue, options?: { axes?: ScrollAxes }): void;\n /**\n * `ScrollPosition.scrollTo(x:y:)`: scroll the scroll views inside the\n * reader to a content offset (an axis left out keeps its offset),\n * smoothly inside `withAnimation`.\n */\n scrollTo(point: ScrollPoint): void;\n}\n\nexport function ScrollViewReader({ children }: { children: (proxy: ScrollViewProxy) => ReactNode }): ReactNode {\n const [request, setRequest] = useState<ScrollRequest | null>(null);\n const proxy: ScrollViewProxy = {\n scrollTo: (target: string | number | ScrollPoint, anchor?: UnitPointValue, options?: { axes?: ScrollAxes }) => {\n if (isPoint(target)) setRequest({ point: target, serial: nextSerial++ });\n else setRequest({ id: target, anchor: anchor === undefined ? null : unitPoint(anchor), serial: nextSerial++, ...(options?.axes ? { axes: options.axes } : {}) });\n },\n };\n return <ScrollRequestContext.Provider value={request}>{children(proxy)}</ScrollRequestContext.Provider>;\n}\n\nexport function ScrollTarget({ id, children }: { id: string | number; children?: ReactNode }): ReactNode {\n const request = useContext(ScrollRequestContext);\n const position = useContext(ScrollPositionContext);\n // Inside a `scrollPosition` scroll view the page tells the target at the anchor it is there.\n const on: EventHandlers | undefined = position ? { scrollposition: () => position.report(id) } : undefined;\n if (request && 'id' in request && request.id === id) return sb('styled', { style: { scrollID: true, scrollTo: command(request) } }, on, children);\n if (on) return sb('styled', { style: { scrollID: true } }, on, children);\n return styled({ scrollID: true }, children);\n}\n\n/** What a `scrollPosition` scroll view hands the targets inside it: where to say they came to the anchor. */\nexport const ScrollPositionContext = createContext<{ report: (id: string | number) => void } | null>(null);\n\n/** A `scrollID` (`ScrollPosition(idType:)`), a content offset (`ScrollPosition(point:)`), or nothing. */\nexport type ScrollPositionValue = string | number | ScrollPoint | null;\n\n/** A `scrollPosition` binding; its setter only ever hears ids, so a `useState` of ids serves. */\nexport type ScrollPositionBinding = readonly [ScrollPositionValue, (value: string | number | null) => void] | ScrollPositionValue;\n\n/**\n * `scrollPosition={[position, setPosition]}` on a `ScrollView`\n * (`.scrollPosition(id:anchor:)`, `.scrollPosition(_:)`): the scroll view\n * reports the target at its anchor when scrolling settles\n * (`reportsPosition`), and a value the app sets, the first included, scrolls\n * there: to that target, as `proxy.scrollTo` would, or to a point\n * (`{ x, y }`, `ScrollPosition.scrollTo(x:y:)`), as a `scrollOffset`\n * command. A value the page just reported scrolls nowhere. The position\n * reads back as ids (the target at the anchor), never as a point: an app\n * that wants the offset reads it with `onScrollGeometryChange`.\n */\nexport function useScrollPosition(binding: ScrollPositionBinding | undefined, anchor: UnitPointValue | undefined, axes: ScrollAxes): { props: Record<string, unknown>; provide(children: ReactNode): ReactNode } | null {\n const bound = binding !== undefined;\n const [value, set] = bound ? readBinding(binding as BindingValue<ScrollPositionValue>) : [null, (): void => undefined];\n const last = useRef<ScrollPositionValue | undefined>(undefined);\n const reported = useRef<ScrollPositionValue | undefined>(undefined);\n const request = useRef<ScrollRequest | null>(null);\n const outer = useContext(ScrollRequestContext);\n const point = anchor === undefined ? null : unitPoint(anchor);\n if (value !== last.current) {\n last.current = value;\n if (isPoint(value)) request.current = { point: value, serial: nextSerial++ };\n // Its own scroll view's axes only: a list the view sits in stays where it is.\n else if (value !== null && value !== reported.current) request.current = { id: value, anchor: point, serial: nextSerial++, axes };\n reported.current = undefined;\n }\n // The offset the view is asked for: its own binding's or the reader's above, whichever is newer.\n const own = request.current;\n const current = own && (!outer || own.serial > outer.serial) ? own : outer;\n const offset = useOffsetCommand(bound ? current : outer);\n if (!bound) return offset ? { props: offset, provide: (children) => children } : null;\n const props: Record<string, unknown> = { reportsPosition: true, ...offset };\n if (point) props['positionAnchor'] = point;\n const context = {\n report: (id: string | number) => {\n reported.current = id;\n set(id);\n },\n };\n // A reader above keeps its say for the targets inside: a point request is this view's alone.\n const inner = current && 'point' in current ? outer && 'id' in outer ? outer : null : current;\n return {\n props,\n provide: (children) => (\n <ScrollPositionContext.Provider value={context}>\n <ScrollRequestContext.Provider value={inner}>{children}</ScrollRequestContext.Provider>\n </ScrollPositionContext.Provider>\n ),\n };\n}\n\n/**\n * The `scrollOffset` prop for the newest point request the scroll view has\n * seen: kept on the element after the pass that brought it (the page carries\n * each serial out once), so the prop is stable until the next request.\n */\nfunction useOffsetCommand(request: ScrollRequest | null): { scrollOffset: ScrollOffsetCommand } | null {\n const seen = useRef<ScrollOffsetCommand | null>(null);\n if (request && 'point' in request && (!seen.current || request.serial > seen.current.serial)) seen.current = offsetCommand(request);\n return seen.current ? { scrollOffset: seen.current } : null;\n}\n","/**\n * The scroll modifiers that pass down to the scroll views below, as SwiftUI's\n * environment does: `.scrollEdgeEffectStyle(_:for:)`,\n * `.scrollEdgeEffectHidden(_:for:)` and `.contentMargins(_:_:for:)`. A\n * `ScrollView` or `List` reads them from above and from its own props, the\n * closer setting winning edge by edge.\n */\n\nimport type { EdgeEffectProps, EdgeInsets } from '@swiftbrowser/web/src/protocol';\nimport { Children, createContext, createElement, useContext, type ReactNode } from 'react';\nimport { sb } from './host/sb';\nimport { padding, type PaddingValue } from './values';\n\nexport type ScrollEdgeEffectStyle = 'automatic' | 'hard' | 'soft';\n/** The vertical edges a scroll edge effect sits on. */\nexport type ScrollEdges = 'top' | 'bottom' | 'all' | 'vertical' | ('top' | 'bottom')[];\n\n/**\n * `.scrollEdgeEffectStyle(.hard, for: .top)` is `[\"hard\", \"top\"]`; a bare\n * style applies to both edges.\n */\nexport type ScrollEdgeEffectStyleValue = ScrollEdgeEffectStyle | [ScrollEdgeEffectStyle, ScrollEdges];\n/** `.scrollEdgeEffectHidden()` is `true`; `.scrollEdgeEffectHidden(true, for: .bottom)` is `[true, \"bottom\"]`. */\nexport type ScrollEdgeEffectHiddenValue = boolean | [boolean, ScrollEdges];\n\n/** The scroll settings in force at a point of the tree. */\nexport interface ScrollSettings {\n /** Per edge: a style (`hard`, `soft`; absent or undefined is automatic, an undefined key clearing an outer one) or hidden. */\n topStyle?: 'hard' | 'soft' | undefined;\n bottomStyle?: 'hard' | 'soft' | undefined;\n topHidden?: boolean;\n bottomHidden?: boolean;\n /** `.contentMargins`: padding inside the scroll views below. */\n margins?: EdgeInsets;\n}\n\nconst ScrollSettingsContext = createContext<ScrollSettings>({});\n\nfunction edgesOf(edges: ScrollEdges): { top: boolean; bottom: boolean } {\n const list = Array.isArray(edges) ? edges : [edges];\n const all = list.some((edge) => edge === 'all' || edge === 'vertical');\n return { top: all || list.includes('top'), bottom: all || list.includes('bottom') };\n}\n\n/** The settings one modifier adds. */\nexport function edgeStyleSettings(value: ScrollEdgeEffectStyleValue): ScrollSettings {\n const [style, edges] = Array.isArray(value) ? value : [value, 'all' as const];\n const on = edgesOf(edges);\n const name = style === 'automatic' ? undefined : style;\n const result: ScrollSettings = {};\n // `automatic` clears what an outer modifier set, so the key is kept.\n if (on.top) result.topStyle = name;\n if (on.bottom) result.bottomStyle = name;\n return result;\n}\n\nexport function edgeHiddenSettings(value: ScrollEdgeEffectHiddenValue): ScrollSettings {\n const [hidden, edges] = Array.isArray(value) ? value : [value, 'all' as const];\n const on = edgesOf(edges);\n const result: ScrollSettings = {};\n if (on.top) result.topHidden = hidden;\n if (on.bottom) result.bottomHidden = hidden;\n return result;\n}\n\n/** `contentMargins={12}`, `{[\"horizontal\", 20]}` or insets; `true` is the default 16. */\nexport type ContentMarginsValue = PaddingValue;\n\nexport function marginSettings(value: ContentMarginsValue): ScrollSettings {\n return { margins: padding(value) };\n}\n\n/** `inner` over `outer`, edge by edge. */\nexport function mergeScrollSettings(outer: ScrollSettings, inner: ScrollSettings): ScrollSettings {\n const result: ScrollSettings = { ...outer };\n for (const key of ['topStyle', 'bottomStyle', 'topHidden', 'bottomHidden'] as const) {\n if (key in inner) (result as Record<string, unknown>)[key] = inner[key];\n }\n if (inner.margins) result.margins = { ...outer.margins, ...inner.margins };\n return result;\n}\n\n/** The views below see `settings` added to the ones around them. */\nexport function withScrollSettings(settings: ScrollSettings, children: ReactNode): ReactNode {\n return createElement(ScrollSettingsExtender, { settings }, children);\n}\n\nfunction ScrollSettingsExtender({ settings, children }: { settings: ScrollSettings; children?: ReactNode }): ReactNode {\n const outer = useContext(ScrollSettingsContext);\n return createElement(ScrollSettingsContext.Provider, { value: mergeScrollSettings(outer, settings) }, children);\n}\n\n/** The settings in force here, with a scroll view's own modifiers applied over them. */\nexport function useScrollSettings(own: ScrollSettings): ScrollSettings {\n return mergeScrollSettings(useContext(ScrollSettingsContext), own);\n}\n\n/** The `edgeEffect` prop of a `list` or `scrollview`, absent when both edges are automatic. */\nexport function edgeEffectProp(settings: ScrollSettings): EdgeEffectProps | undefined {\n const edges: EdgeEffectProps = {};\n const top = settings.topHidden ? 'hidden' : settings.topStyle;\n const bottom = settings.bottomHidden ? 'hidden' : settings.bottomStyle;\n if (top) edges.top = top;\n if (bottom) edges.bottom = bottom;\n return top || bottom ? edges : undefined;\n}\n\n/**\n * A scroll view's content with its content margins as padding inside it\n * (several children first become the stack the scroll view would make).\n */\nexport function marginedContent(children: ReactNode, margins: EdgeInsets | undefined, axis: 'horizontal' | 'vertical'): ReactNode {\n if (!margins || Object.values(margins).every((value) => !value)) return children;\n const list = Children.toArray(children);\n const content = list.length === 1 ? list[0] : sb(axis === 'horizontal' ? 'hstack' : 'vstack', { spacing: null, alignment: 'center' }, undefined, children);\n return sb('styled', { style: { padding: margins } }, undefined, content);\n}\n\n","/**\n * Lazy rows (docs/ops-protocol.md, \"Lazy rows\"): inside a `List`,\n * `LazyVStack`, `LazyHStack`, `LazyVGrid` or `LazyHGrid`, a `ForEach` of\n * more rows (a grid's: cells) than a batch mounts the first batch and a\n * `lazyspacer`; the page reports the spacer when it nears the visible area\n * (`lazy`), and the next batch mounts, with a new spacer after it.\n *\n * In a lazy stack on the page (`LazyWindowContext`, `LazyStackContext`), the\n * rows far from the visible area are unbuilt again, as SwiftUI's are: a\n * leading `lazyspacer` stands for those before the built ones, as long as\n * they were, and the page says which to drop and when to build them back.\n */\n\nimport { createContext, createElement, isValidElement, useContext, useEffect, useState, type ReactElement, type ReactNode } from 'react';\nimport { ScrollRequestContext } from './scrollReader';\nimport { sb } from './host/sb';\n\nexport const LAZY_BATCH = 12;\n\nexport const LazyContext = createContext<'vertical' | 'horizontal' | null>(null);\n\n/** How many rows a lazy container builds at a time: `LAZY_BATCH`, a grid's cells `LAZY_GRID_BATCH` (a few rows of them). */\nexport const LazyBatchContext = createContext(LAZY_BATCH);\nexport const LAZY_GRID_BATCH = 48;\n\n/** Whether the renderer unbuilds a lazy stack's far rows (the page's does: `mount`). */\nexport const LazyWindowContext = createContext(false);\n/** Whether the lazy container is a stack (`LazyVStack`, `LazyHStack`), whose rows a leading spacer can stand for. */\nexport const LazyStackContext = createContext(false);\n\n/** What the page asks of a lazy group's spacer (`LazyEvent`'s). */\ninterface LazyAsk {\n drop?: number;\n extents?: number[];\n dropEnd?: number;\n}\n\nexport interface LazyGroupProps {\n rows: ReactElement[];\n /** Set by a list: the group's first row's index among the container's children. */\n start?: number;\n /** Set by a list: wraps each row (selection tags) given its index among the container's children. */\n wrap?: (row: ReactElement, containerIndex: number) => ReactNode;\n}\n\nexport function LazyGroup({ rows, start = 0, wrap }: LazyGroupProps): ReactNode {\n const axis = useContext(LazyContext);\n const batch = useContext(LazyBatchContext);\n const request = useContext(ScrollRequestContext);\n const windowed = useContext(LazyWindowContext) && useContext(LazyStackContext) && axis !== null;\n const [count, setCount] = useState(batch);\n // The rows unbuilt before the built ones (a lazy stack on the page), and what each batch of them took.\n const [front, setFront] = useState<{ from: number; extents: number[] }>({ from: 0, extents: [] });\n // A `scrollTo` whose target is a row not built yet builds the rows up to it\n // first, as SwiftUI does, so the target is on the page when it scrolls.\n const target = request && 'id' in request ? rows.findIndex((row) => rowMatches(row, request.id)) : -1;\n const needed = target >= 0 ? Math.ceil((target + 1) / batch) * batch : 0;\n useEffect(() => {\n if (needed > count) setCount(needed);\n // A target unbuilt before the built rows: every row back from it (what they took is no longer stood for).\n if (target >= 0 && target < front.from) setFront({ from: Math.floor(target / batch) * batch, extents: front.extents.slice(0, Math.floor(target / batch)) });\n }, [needed, count, target, front, batch]);\n const visible = Math.max(count, needed);\n const from = windowed ? Math.min(front.from, Math.max(0, visible - batch)) : 0;\n const shown = axis === null ? rows : rows.slice(from, visible);\n const built = shown.map((row, index) => (wrap ? wrap(row, start + from + index) : row));\n if (axis === null || (!windowed && shown.length >= rows.length)) return built;\n const ask = (event: LazyAsk): void => {\n if (event.drop && event.drop > 0) {\n const drop = Math.min(event.drop, shown.length - batch);\n if (drop > 0) setFront({ from: from + drop, extents: [...front.extents, ...(event.extents ?? []).slice(0, Math.ceil(drop / batch))] });\n } else if (event.dropEnd && event.dropEnd > 0) {\n setCount(Math.max(from + batch, visible - event.dropEnd));\n } else if (from > 0) {\n // Near the visible area again: the last batch unbuilt before the built rows back.\n setFront({ from: Math.max(0, from - batch), extents: front.extents.slice(0, -1) });\n }\n };\n const leading = windowed\n ? [createElement(LazySpacer, { key: `lazy-lead-${from}`, axis, remaining: from, edge: 'leading' as const, extent: front.extents.reduce((a, b) => a + b, 0), built: shown.length, batch, ask })]\n : [];\n const trailing =\n visible < rows.length ? [createElement(LazySpacer, { key: `lazy-${visible}`, axis, remaining: rows.length - visible, ask: () => setCount(visible + batch) })] : [];\n return [...leading, ...built, ...trailing];\n}\n\nfunction LazySpacer({\n axis,\n remaining,\n ask,\n ...leading\n}: {\n axis: 'vertical' | 'horizontal';\n remaining: number;\n ask: (event: LazyAsk) => void;\n edge?: 'leading';\n extent?: number;\n built?: number;\n batch?: number;\n}): ReactNode {\n return sb('lazyspacer', { axis, remaining, ...leading }, { lazy: ask });\n}\n\n/** Whether a row is a scroll target's: its key (a `ForEach` id), or a `scrollID` on the row's view. */\nfunction rowMatches(row: ReactElement, id: string | number): boolean {\n if (row.key !== null && row.key === String(id)) return true;\n let element: ReactElement | null = row;\n for (let depth = 0; element && depth < 3; depth++) {\n const props = element.props as { scrollID?: unknown; children?: unknown };\n if (props.scrollID === id) return true;\n element = isValidElement(props.children) ? (props.children as ReactElement) : null;\n }\n return false;\n}\n","import type { FrameAlignment, GridItem as GridItemProps, GridRowAlignment, HStackAlignment, PinnedView, ScrollAxes, ScrollGeometryEvent, VStackAlignment } from '@swiftbrowser/web/src/protocol';\nimport { Children, Fragment, createContext, createElement, isValidElement, useRef, useState, type Key, type ReactElement, type ReactNode } from 'react';\nimport { useViewEnvironment } from '../environment';\nimport type { EventHandlers } from '../host/instance';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, takeModifier, type ModifierEntry, type ViewModifiers } from '../modifiers';\nimport { unitPoint, type UnitPointValue } from '../values';\nimport { useScrollPosition, type ScrollPositionBinding } from '../scrollReader';\nimport {\n edgeEffectProp,\n edgeHiddenSettings,\n edgeStyleSettings,\n marginSettings,\n marginedContent,\n mergeScrollSettings,\n useScrollSettings,\n withScrollSettings,\n type ContentMarginsValue,\n type ScrollEdgeEffectHiddenValue,\n type ScrollEdgeEffectStyleValue,\n type ScrollSettings,\n} from '../scrollEnvironment';\nimport { Row, type RowProps } from './row';\nimport { LAZY_BATCH, LAZY_GRID_BATCH, LazyBatchContext, LazyContext, LazyGroup, type LazyGroupProps, LazyStackContext } from '../lazy';\n\n/**\n * `PinnedScrollableViews`: what a lazy stack or grid keeps in view\n * (`pinnedViews: [.sectionHeaders]`): each `Section`'s header stays at the\n * scroll view's leading edge while its section passes, pushed out by the\n * next section's; a footer stays at the trailing edge the same way.\n */\nexport type PinnedViews = PinnedView[];\n\n/** The pinned views of the lazy stack or grid around a `Section` (its string header then becomes a view, so it can pin). */\nexport const PinnedContext = createContext<PinnedViews | null>(null);\n\n/** `children` under the stack's pinned views, when it has any. */\nfunction pinning(pinnedViews: PinnedViews | undefined, children: ReactNode): ReactNode {\n return pinnedViews && pinnedViews.length > 0 ? <PinnedContext.Provider value={pinnedViews}>{children}</PinnedContext.Provider> : children;\n}\n\nexport interface VStackProps extends ViewModifiers {\n alignment?: VStackAlignment;\n spacing?: number | null;\n /** `.scrollTargetLayout()`: the children are the enclosing scroll view's snap points. */\n scrollTargetLayout?: boolean;\n /** `LazyVStack(pinnedViews:)` (a `LazyVStack`'s; see `PinnedViews`). */\n pinnedViews?: PinnedViews;\n children?: ReactNode;\n}\n\nexport function VStack(props: VStackProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const stack: Record<string, unknown> = { spacing: own.spacing ?? null, alignment: own.alignment ?? 'center' };\n if (own.scrollTargetLayout) stack['scrollTarget'] = true;\n if (own.pinnedViews && own.pinnedViews.length > 0) stack['pinned'] = own.pinnedViews;\n return applyModifiers(sb('vstack', stack, undefined, pinning(own.pinnedViews, own.children)), modifiers);\n}\n\nexport interface HStackProps extends ViewModifiers {\n alignment?: HStackAlignment | 'firstTextBaseline' | 'lastTextBaseline';\n spacing?: number | null;\n scrollTargetLayout?: boolean;\n /** `LazyHStack(pinnedViews:)` (a `LazyHStack`'s; see `PinnedViews`). */\n pinnedViews?: PinnedViews;\n children?: ReactNode;\n}\n\nexport function HStack(props: HStackProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const stack: Record<string, unknown> = { spacing: own.spacing ?? null, alignment: own.alignment ?? 'center' };\n if (own.scrollTargetLayout) stack['scrollTarget'] = true;\n if (own.pinnedViews && own.pinnedViews.length > 0) stack['pinned'] = own.pinnedViews;\n return applyModifiers(sb('hstack', stack, undefined, pinning(own.pinnedViews, own.children)), modifiers);\n}\n\nexport interface FlowStackProps extends ViewModifiers {\n /** A child's place in its line: `top`, `center` (the default) or `bottom`. */\n alignment?: HStackAlignment;\n /** Between the children on a line (default 8). */\n spacing?: number | null;\n /** Between the lines (default the spacing). */\n lineSpacing?: number | null;\n children?: ReactNode;\n}\n\n/**\n * `FlowStack`, SwiftBrowser's own (SwiftUI has none built in; an app writes\n * one with `Layout`): its children at their ideal sizes, leading to trailing,\n * in as many lines as the width it is given needs, a new line where the next\n * child would pass it. Its size is its widest line by its lines.\n */\nexport function FlowStack(props: FlowStackProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const stack = { spacing: own.spacing ?? null, lineSpacing: own.lineSpacing ?? null, alignment: own.alignment ?? 'center' };\n return applyModifiers(sb('flowstack', stack, undefined, own.children), modifiers);\n}\n\nexport interface ZStackProps extends ViewModifiers {\n alignment?: FrameAlignment;\n children?: ReactNode;\n}\n\nexport function ZStack(props: ZStackProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n return applyModifiers(sb('zstack', { alignment: own.alignment ?? 'center' }, undefined, own.children), modifiers);\n}\n\nexport interface SpacerProps extends ViewModifiers {\n minLength?: number | null;\n}\n\nexport function Spacer(props: SpacerProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n return applyModifiers(sb('spacer', { minLength: own.minLength ?? null }), modifiers);\n}\n\nexport function Divider(props: ViewModifiers): ReactNode {\n const { modifiers } = splitProps(props);\n return applyModifiers(sb('divider', {}), modifiers);\n}\n\nexport interface ScrollViewProps extends ViewModifiers {\n axes?: ScrollAxes;\n /** `.scrollTargetBehavior(_:)`: snap to the `scrollTargetLayout` children, or a page at a time. */\n scrollTargetBehavior?: 'viewAligned' | 'paging';\n /**\n * `.scrollDismissesKeyboard(_:)`: `true` or `immediately` dismisses the\n * keyboard as scrolling starts; `interactively` lets it follow the finger\n * down and back up, as Messages does (natively; a page dismisses it at once).\n */\n scrollDismissesKeyboard?: boolean | 'immediately' | 'interactively' | 'never';\n /** `.scrollIndicators(_:)`: `hidden` draws no scroll bars (a pager's). */\n scrollIndicators?: 'automatic' | 'visible' | 'hidden';\n /**\n * `.defaultScrollAnchor(_:)`: where the content starts (`\"bottom\"`: its end\n * in view, as a chat) and stays when it grows while the viewer is there;\n * a viewer who scrolled away is left where they are.\n */\n defaultScrollAnchor?: UnitPointValue;\n /**\n * `.scrollPosition(id:anchor:)`: the `scrollID` of the view at the anchor\n * (the leading edge unless `scrollPositionAnchor` says otherwise), set\n * when scrolling settles; setting it scrolls there.\n */\n scrollPosition?: ScrollPositionBinding;\n scrollPositionAnchor?: UnitPointValue;\n /**\n * `.onScrollGeometryChange(for:of:action:)`: hears the scroll view's\n * geometry (its content offset and size, its own size, the visible\n * rectangle) as it scrolls and lays out. A function is called on every\n * change; `{ of, action }` calls `action(value, oldValue)` only when `of`\n * (the `for:` transform) answers differently, so an app that watches the\n * content size alone is not rendered per frame of a scroll.\n */\n onScrollGeometryChange?: ScrollGeometryChangeHandler;\n children?: ReactNode;\n}\n\n/** SwiftUI's `ScrollGeometry`. */\nexport interface ScrollGeometry {\n /** The visible area's origin in the content. */\n contentOffset: { x: number; y: number };\n contentSize: { width: number; height: number };\n /** The scroll view's own size. */\n containerSize: { width: number; height: number };\n /** Space the view scrolls into past its content (under a bar covering its bottom). */\n contentInsets: { top: number; leading: number; bottom: number; trailing: number };\n /** The content's part in view: `contentOffset` and `containerSize`. */\n visibleRect: { x: number; y: number; width: number; height: number };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- the spec's value type is the transform's to infer\nexport type ScrollGeometryChangeHandler = ((geometry: ScrollGeometry) => void) | ScrollGeometryChangeSpec<any>;\n\nexport interface ScrollGeometryChangeSpec<T> {\n /** The `for:` transform: what of the geometry the action watches. */\n of: (geometry: ScrollGeometry) => T;\n action: (value: T, oldValue: T) => void;\n}\n\n/** The geometry a `scrollgeometry` event reports. */\nexport function scrollGeometryOf(event: ScrollGeometryEvent): ScrollGeometry {\n return {\n contentOffset: { x: event.offset.x, y: event.offset.y },\n contentSize: { width: event.contentSize.width, height: event.contentSize.height },\n containerSize: { width: event.containerSize.width, height: event.containerSize.height },\n contentInsets: { ...event.contentInsets },\n visibleRect: { x: event.offset.x, y: event.offset.y, width: event.containerSize.width, height: event.containerSize.height },\n };\n}\n\n/**\n * The `reportsGeometry` prop and `scrollgeometry` handler for an\n * `onScrollGeometryChange`: the `of` transform's last answer is kept so the\n * action hears a change once.\n */\nfunction useScrollGeometryChange(handler: ScrollGeometryChangeHandler | undefined): { props: Record<string, unknown>; handlers?: EventHandlers } {\n const last = useRef<{ value: unknown } | null>(null);\n if (!handler) return { props: {} };\n return {\n props: { reportsGeometry: true },\n handlers: {\n scrollgeometry: (event) => {\n const geometry = scrollGeometryOf(event);\n if (typeof handler === 'function') return handler(geometry);\n const value = handler.of(geometry);\n const previous = last.current;\n if (previous && JSON.stringify(previous.value) === JSON.stringify(value)) return;\n last.current = { value };\n handler.action(value, previous ? previous.value : value);\n },\n },\n };\n}\n\nexport function ScrollView(props: ScrollViewProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const refresh = useRefreshable(takeModifier(modifiers, 'refreshable'));\n const ownSettings = takeScrollSettings(modifiers);\n const settings = useScrollSettings(ownSettings);\n const axes = own.axes ?? 'vertical';\n const geometry = useScrollGeometryChange(own.onScrollGeometryChange);\n const scroll: Record<string, unknown> = { axes, ...refresh.props, ...geometry.props };\n const handlers: EventHandlers | undefined = refresh.handlers || geometry.handlers ? { ...refresh.handlers, ...geometry.handlers } : undefined;\n if (own.scrollTargetBehavior) scroll['snap'] = own.scrollTargetBehavior;\n if (own.scrollDismissesKeyboard === true || own.scrollDismissesKeyboard === 'immediately') scroll['dismissesKeyboard'] = true;\n else if (own.scrollDismissesKeyboard === 'interactively') scroll['dismissesKeyboard'] = 'interactively';\n if (own.scrollIndicators === 'hidden') scroll['showsIndicators'] = false;\n if (own.defaultScrollAnchor !== undefined) scroll['defaultScrollAnchor'] = unitPoint(own.defaultScrollAnchor);\n const edgeEffect = edgeEffectProp(settings);\n if (edgeEffect) scroll['edgeEffect'] = edgeEffect;\n const position = useScrollPosition(own.scrollPosition, own.scrollPositionAnchor, axes);\n if (position) Object.assign(scroll, position.props);\n const content = marginedContent(own.children, settings.margins, axes === 'horizontal' ? 'horizontal' : 'vertical');\n const inner = providingScrollSettings(ownSettings, content);\n return applyModifiers(sb('scrollview', scroll, handlers, position ? position.provide(inner) : inner), modifiers);\n}\n\n/**\n * The scroll modifiers written on a `ScrollView` or `List` itself: they apply\n * to it, and pass on to the scroll views inside as from above.\n */\nexport function takeScrollSettings(modifiers: ModifierEntry[]): ScrollSettings {\n let settings: ScrollSettings = {};\n // Each sets different fields, so their order does not matter.\n const own: ScrollSettings[] = [];\n for (const key of ['scrollEdgeEffectStyle', 'scrollEdgeEffectHidden', 'contentMargins'] as const) {\n const value = takeModifier(modifiers, key);\n if (value === undefined) continue;\n if (key === 'scrollEdgeEffectStyle') own.push(edgeStyleSettings(value as ScrollEdgeEffectStyleValue));\n else if (key === 'scrollEdgeEffectHidden') own.push(edgeHiddenSettings(value as ScrollEdgeEffectHiddenValue));\n else own.push(marginSettings(value as ContentMarginsValue));\n }\n for (const each of own) settings = mergeScrollSettings(settings, each);\n return settings;\n}\n\n/** `children` under the settings a scroll view was given itself (when there are any). */\nexport function providingScrollSettings(settings: ScrollSettings, children: ReactNode): ReactNode {\n return Object.keys(settings).length > 0 ? withScrollSettings(settings, children) : children;\n}\n\n/**\n * `.refreshable` above a `List` or `ScrollView`: its props (`refreshable`,\n * `refreshing` while the action runs) and the `refresh` handler.\n */\nexport function useRefreshable(own?: () => unknown): { props: Record<string, unknown>; handlers?: EventHandlers } {\n // `.refreshable` on the list or scroll view itself, else from above it.\n const environment = useViewEnvironment();\n const refresh = own ?? environment.refresh;\n const [refreshing, setRefreshing] = useState(false);\n if (!refresh) return { props: {} };\n return {\n props: { refreshable: true, refreshing },\n handlers: {\n refresh: () => {\n if (refreshing) return;\n setRefreshing(true);\n Promise.resolve()\n .then(refresh)\n .catch((error: unknown) => console.error(error))\n .finally(() => setRefreshing(false));\n },\n },\n };\n}\n\nexport interface GroupProps extends ViewModifiers {\n children?: ReactNode;\n}\n\n/** `Group { }`: the modifiers apply to each child. */\nexport function Group(props: GroupProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n if (modifiers.length === 0) return own.children;\n return Children.map(own.children, (child) => applyModifiers(child, modifiers));\n}\n\nexport interface ForEachProps<T> extends ViewModifiers {\n data: readonly T[];\n /** The identity of each element (`id: \\.self` by default, or `.id` when the element has one). */\n id?: (element: T, index: number) => Key;\n /** `.onDelete`: the rows become deletable (a swipe, or edit mode's minus); called with the offsets to remove. */\n onDelete?: (offsets: number[]) => void;\n /** `.deleteDisabled`, per element. */\n deleteDisabled?: (element: T, index: number) => boolean;\n /**\n * `.onMove`: the rows become movable (a grip in edit mode, a long press\n * otherwise); called like `move(fromOffsets:toOffset:)`, with the offsets\n * moved and the offset they go before, counted before the move\n * (`moveItems` applies it to an array).\n */\n onMove?: (offsets: number[], to: number) => void;\n /** `.moveDisabled`, per element. */\n moveDisabled?: (element: T, index: number) => boolean;\n children: (element: T, index: number) => ReactNode;\n}\n\n/** `Array.move(fromOffsets:toOffset:)`: the array with `offsets` moved before `to` (counted before the move). */\nexport function moveItems<T>(items: readonly T[], offsets: readonly number[], to: number): T[] {\n const moving = new Set(offsets);\n const picked = items.filter((_, index) => moving.has(index));\n const rest = items.filter((_, index) => !moving.has(index));\n const before = offsets.filter((offset) => offset < to).length;\n const at = to - before;\n return [...rest.slice(0, at), ...picked, ...rest.slice(at)];\n}\n\n/** `ForEach(data, id:) { }`: one keyed child per element. */\nexport function ForEach<T>(props: ForEachProps<T>): ReactNode {\n const { own, modifiers } = splitProps(props);\n const rows = own.data.map((element, index): ReactElement => {\n const key = own.id ? own.id(element, index) : keyOf(element, index);\n const content = applyModifiers(own.children(element, index), modifiers);\n if (!own.onDelete && !own.onMove) return createElement(Fragment, { key }, content);\n const { onDelete, onMove } = own;\n const row: RowProps = { tag: key, index };\n if (onDelete) {\n row.onDelete = () => onDelete([index]);\n row.deletable = !own.deleteDisabled?.(element, index);\n }\n if (onMove) {\n row.onMove = (to) => onMove([index], to);\n row.movable = !own.moveDisabled?.(element, index);\n }\n return createElement(Row, { key, ...row }, content);\n });\n // A long group builds its rows lazily inside a list or a lazy stack.\n return rows.length > LAZY_BATCH ? createElement(LazyGroup, { rows }) : rows;\n}\n\nfunction keyOf(element: unknown, index: number): Key {\n if (typeof element === 'string' || typeof element === 'number') return element;\n if (typeof element === 'object' && element !== null && 'id' in element) {\n const id = (element as { id: unknown }).id;\n if (typeof id === 'string' || typeof id === 'number') return id;\n }\n return index;\n}\n\n/**\n * The elements of `children`, through fragments, arrays and `ForEach`, so\n * `Picker` and `TabView` can read their options and tabs.\n */\nexport function flattenChildren(children: ReactNode, options: { keepLazy?: boolean } = {}): ReactElement[] {\n const result: ReactElement[] = [];\n const visit = (node: ReactNode): void => {\n if (node === null || node === undefined || typeof node === 'boolean') return;\n if (Array.isArray(node)) {\n node.forEach(visit);\n return;\n }\n if (!isValidElement(node)) return;\n const element = node as ReactElement<Record<string, unknown>>;\n if (element.type === Fragment) {\n const inner = element.props['children'] as ReactNode;\n // A keyed fragment around one view (a `ForEach` row) hands its key on,\n // so the row keeps its identity when the rows reorder.\n if (element.key !== null && isValidElement(inner) && inner.key === null && inner.type !== Fragment) {\n visit({ ...inner, key: element.key });\n return;\n }\n visit(inner);\n return;\n }\n if (element.type === ForEach) {\n // Expand it as it would render (keys, modifiers and `onDelete` rows included).\n visit(ForEach(element.props as unknown as ForEachProps<unknown>));\n return;\n }\n if (element.type === LazyGroup && !options.keepLazy) {\n visit((element.props as unknown as LazyGroupProps).rows);\n return;\n }\n result.push(element);\n };\n visit(children);\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Grids\n// ---------------------------------------------------------------------------\n\nexport interface GridItemSpec {\n size?: { fixed: number } | { flexible: { minimum?: number; maximum?: number } } | { adaptive: { minimum: number; maximum?: number } };\n spacing?: number | null | undefined;\n alignment?: FrameAlignment | null | undefined;\n}\n\n/** `GridItem(.flexible(), spacing: 8)`; `GridItem.flexible()` for short. */\nexport function GridItem(spec: GridItemSpec = {}): GridItemProps {\n const dimension = (n: number | undefined): number | 'infinity' => (n === undefined || n === Infinity ? 'infinity' : n);\n let size: GridItemProps['size'];\n if (spec.size && 'fixed' in spec.size) size = { kind: 'fixed', value: spec.size.fixed };\n else if (spec.size && 'adaptive' in spec.size) {\n size = { kind: 'adaptive', minimum: spec.size.adaptive.minimum, maximum: dimension(spec.size.adaptive.maximum) };\n } else {\n const flexible = spec.size && 'flexible' in spec.size ? spec.size.flexible : {};\n size = { kind: 'flexible', minimum: flexible.minimum ?? 10, maximum: dimension(flexible.maximum) };\n }\n return { size, spacing: spec.spacing ?? null, alignment: spec.alignment ?? null };\n}\nGridItem.flexible = (options: { minimum?: number; maximum?: number; spacing?: number; alignment?: FrameAlignment } = {}): GridItemProps =>\n GridItem({ size: { flexible: options }, spacing: options.spacing, alignment: options.alignment });\nGridItem.fixed = (value: number, options: { spacing?: number; alignment?: FrameAlignment } = {}): GridItemProps =>\n GridItem({ size: { fixed: value }, spacing: options.spacing, alignment: options.alignment });\nGridItem.adaptive = (options: { minimum: number; maximum?: number; spacing?: number; alignment?: FrameAlignment }): GridItemProps =>\n GridItem({ size: { adaptive: options }, spacing: options.spacing, alignment: options.alignment });\n\n/** A lazy grid's cells: a long `ForEach` of them builds a few rows at a time, as a lazy stack's rows do. */\nfunction lazyCells(axis: 'vertical' | 'horizontal', children: ReactNode): ReactNode {\n return createElement(LazyContext.Provider, { value: axis }, createElement(LazyStackContext.Provider, { value: false }, createElement(LazyBatchContext.Provider, { value: LAZY_GRID_BATCH }, children)));\n}\n\nexport interface LazyVGridProps extends ViewModifiers {\n columns: GridItemProps[];\n alignment?: FrameAlignment;\n spacing?: number | null;\n /** `LazyVGrid(pinnedViews:)`: the `Section` headers (footers) stay in view as their cells scroll. */\n pinnedViews?: PinnedViews;\n children?: ReactNode;\n}\n\nexport function LazyVGrid(props: LazyVGridProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const grid: Record<string, unknown> = { columns: own.columns, spacing: own.spacing ?? null, alignment: own.alignment ?? 'center' };\n if (own.pinnedViews && own.pinnedViews.length > 0) grid['pinned'] = own.pinnedViews;\n return applyModifiers(sb('lazyvgrid', grid, undefined, lazyCells('vertical', pinning(own.pinnedViews, own.children))), modifiers);\n}\n\nexport interface LazyHGridProps extends ViewModifiers {\n rows: GridItemProps[];\n /** How each cell sits in its slot: `top`, `center` (the default) or `bottom`. */\n alignment?: 'top' | 'center' | 'bottom' | 'firstTextBaseline' | 'lastTextBaseline';\n /** Between the columns (8 by default). */\n spacing?: number | null;\n /** `LazyHGrid(pinnedViews:)`: as for `LazyVGrid`, along the leading edge. */\n pinnedViews?: PinnedViews;\n children?: ReactNode;\n}\n\n/**\n * `LazyHGrid(rows:)`: the rows share the height it is proposed and the cells\n * fill them column by column, usually inside a horizontal `ScrollView`.\n */\nexport function LazyHGrid(props: LazyHGridProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const grid: Record<string, unknown> = { rows: own.rows, spacing: own.spacing ?? null, alignment: (own.alignment ?? 'center') as FrameAlignment };\n if (own.pinnedViews && own.pinnedViews.length > 0) grid['pinned'] = own.pinnedViews;\n return applyModifiers(sb('lazyhgrid', grid, undefined, lazyCells('horizontal', pinning(own.pinnedViews, own.children))), modifiers);\n}\n\nexport interface GridProps extends ViewModifiers {\n alignment?: FrameAlignment;\n horizontalSpacing?: number | null;\n verticalSpacing?: number | null;\n children?: ReactNode;\n}\n\nexport function Grid(props: GridProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n return applyModifiers(\n sb(\n 'grid',\n { horizontalSpacing: own.horizontalSpacing ?? null, verticalSpacing: own.verticalSpacing ?? null, alignment: own.alignment ?? 'center' },\n undefined,\n own.children,\n ),\n modifiers,\n );\n}\n\nexport interface GridRowProps extends ViewModifiers {\n alignment?: GridRowAlignment | null;\n children?: ReactNode;\n}\n\nexport function GridRow(props: GridRowProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n return applyModifiers(sb('gridrow', { alignment: own.alignment ?? null }, undefined, own.children), modifiers);\n}\n","import type { Color, Font, ShapeStyle, TextRun } from '@swiftbrowser/web/src/protocol';\nimport { Fragment, isValidElement, type ReactElement, type ReactNode } from 'react';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, styled, takeModifier, type ViewModifiers } from '../modifiers';\nimport { useViewEnvironment } from '../environment';\nimport { color, font, shapeStyle, type ColorValue, type FontValue, type StyleValue } from '../values';\nimport { HStack } from './stacks';\nimport { bitmapExtent, type Bitmap } from '../bitmaps';\n\nexport interface TextProps extends ViewModifiers {\n /**\n * Strings and numbers, nested `<Text>`s (`Text + Text`) and inline\n * `<Image>`s. A nested text's `font`, `bold`, `foregroundStyle` and\n * `background` (a colour behind its glyphs, as `AttributedString`'s\n * `backgroundColor`) style its own run; the outer text's wrap the whole.\n */\n children?: ReactNode;\n italic?: boolean;\n underline?: boolean | { color?: ColorValue };\n strikethrough?: boolean | { color?: ColorValue };\n /** Points between characters (`.tracking` / `.kerning`). */\n tracking?: number;\n kerning?: number;\n baselineOffset?: number;\n /** A tap on the text opens this URL. */\n link?: string;\n}\n\n/** The run-level style of one `Text` (nested texts inherit the outer one). */\ninterface RunStyle {\n italic?: boolean;\n underline?: { color?: unknown };\n strikethrough?: { color?: unknown };\n kerning?: number;\n baselineOffset?: number;\n link?: string;\n font?: Font;\n foreground?: ShapeStyle;\n background?: Color;\n}\n\ntype Segment = { text: string; style: RunStyle } | { image: Record<string, unknown>; style: RunStyle };\n\nfunction runStyleOf(props: TextProps, inherited: RunStyle, nested: boolean): RunStyle {\n const style: RunStyle = { ...inherited };\n if (props.italic) style.italic = true;\n if (props.underline) style.underline = typeof props.underline === 'object' && props.underline.color ? { color: color(props.underline.color) } : {};\n if (props.strikethrough) {\n style.strikethrough = typeof props.strikethrough === 'object' && props.strikethrough.color ? { color: color(props.strikethrough.color) } : {};\n }\n const kerning = props.tracking ?? props.kerning;\n if (kerning !== undefined) style.kerning = kerning;\n if (props.baselineOffset !== undefined) style.baselineOffset = props.baselineOffset;\n if (props.link) style.link = props.link;\n if (nested) {\n // A nested text's font and color modifiers style its run; the outer\n // text's wrap the whole element (as `styled`), like the shim.\n let runFont: Font | undefined = props.font !== undefined ? font(props.font as FontValue) : undefined;\n if (props.bold) runFont = { ...(runFont ?? {}), weight: 'bold' };\n if (props.fontWeight) runFont = { ...(runFont ?? {}), weight: props.fontWeight };\n if (props.monospacedDigit) runFont = { ...(runFont ?? {}), monospacedDigit: true };\n if (runFont) style.font = { ...(style.font ?? {}), ...runFont };\n // A run takes one color: the primary of a layered style.\n if (props.foregroundStyle !== undefined) {\n style.foreground = shapeStyle((Array.isArray(props.foregroundStyle) ? props.foregroundStyle[0] : props.foregroundStyle) as StyleValue);\n }\n // A colour behind the run's glyphs; a view, a shape or a gradient is no run's.\n const background = runBackground(props.background);\n if (background) style.background = background;\n }\n return style;\n}\n\n/** A nested text's `background` as a run's colour: a name or a hex string, or a Color object; nothing for a view, a shape or a style with no colour. */\nfunction runBackground(value: unknown): Color | undefined {\n if (typeof value === 'string') {\n const made = color(value as ColorValue);\n return 'hierarchical' in made ? undefined : made;\n }\n if (typeof value !== 'object' || value === null || isValidElement(value) || 'in' in value) return undefined;\n return 'r' in value || 'name' in value || 'named' in value ? (value as Color) : undefined;\n}\n\n/** The segments of a text: raw strings merge into one; nested texts and images are their own. */\nfunction segmentsOf(children: ReactNode, style: RunStyle, into: Segment[]): void {\n const visit = (node: ReactNode): void => {\n if (node === null || node === undefined || typeof node === 'boolean') return;\n if (typeof node === 'string' || typeof node === 'number') {\n const last = into[into.length - 1];\n if (last && 'text' in last && last.style === style) last.text += String(node);\n else into.push({ text: String(node), style });\n return;\n }\n if (Array.isArray(node)) {\n node.forEach(visit);\n return;\n }\n if (!isValidElement(node)) return;\n const element = node as ReactElement<Record<string, unknown>>;\n if (element.type === Fragment) {\n visit(element.props['children'] as ReactNode);\n return;\n }\n if (element.type === Text) {\n const props = element.props as TextProps;\n segmentsOf(props.children, runStyleOf(props, style, true), into);\n return;\n }\n if (element.type === Image) {\n const props = element.props as ImageProps;\n into.push({ image: imageProps(props), style });\n return;\n }\n };\n visit(children);\n}\n\nfunction isPlainStyle(style: RunStyle): boolean {\n return Object.keys(style).length === 0;\n}\n\nexport function Text(props: TextProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const environment = useViewEnvironment();\n const style = runStyleOf(props, {}, false);\n const segments: Segment[] = [];\n segmentsOf(own.children, style, segments);\n const textCase = takeModifier(modifiers, 'textCase') ?? environment.textCase;\n if (textCase) {\n for (const segment of segments) {\n if ('text' in segment) segment.text = textCase === 'uppercase' ? segment.text.toUpperCase() : segment.text.toLowerCase();\n }\n }\n const redacted = takeModifier(modifiers, 'redacted') ?? environment.redacted;\n const content = segments.map((segment) => ('text' in segment ? segment.text : '')).join('');\n const plain = segments.length <= 1 && (segments.length === 0 || ('text' in segments[0]! && isPlainStyle(segments[0]!.style)));\n if (plain) return applyModifiers(placeholder(sb('text', { text: content }), redacted), modifiers);\n const runs: TextRun[] = segments.map((segment) => {\n const run: Record<string, unknown> = { ...segment.style };\n if ('text' in segment) run['text'] = segment.text;\n else run['image'] = segment.image;\n return run as TextRun;\n });\n const hasLinks = segments.some((segment) => segment.style.link);\n const handlers = hasLinks ? { link: (event: { value: string }) => openURL(event.value) } : undefined;\n return applyModifiers(placeholder(sb('text', { text: content, runs }, handlers), redacted), modifiers);\n}\n\n/**\n * `.redacted(reason: .placeholder)`: the view keeps its size and draws as a\n * rounded block of the tertiary fill, as iOS draws placeholder content.\n */\nexport function placeholder(node: ReactNode, redacted: boolean | undefined): ReactNode {\n if (!redacted) return node;\n return styled({ background: { hierarchical: 3 }, backgroundCornerRadius: 4 }, styled({ foreground: { name: 'clear' } }, node));\n}\n\n/** Opens a link: the system's opener in a SwiftBrowser Native app (its bridge's `openURL`), else a new tab. */\nexport function openURL(url: string): void {\n const native = (globalThis as { __sbNative?: { openURL?: (url: string) => boolean } }).__sbNative;\n if (native?.openURL) {\n native.openURL(url);\n return;\n }\n if (typeof window !== 'undefined') window.open(url, '_blank', 'noopener');\n}\n\n// ---------------------------------------------------------------------------\n// Image\n// ---------------------------------------------------------------------------\n\nexport interface ImageProps extends ViewModifiers {\n /** An SF Symbol name. */\n systemName?: string;\n /** An asset-catalog image name (the renderer needs the catalog manifest). */\n name?: string;\n /** A remote image whose pixel size is known; `AsyncImage` loads one to learn it. */\n url?: string;\n width?: number;\n height?: number;\n resizable?: boolean;\n /**\n * Its accessible name in place of the symbol's or the image's\n * (`.accessibilityLabel(_:)`); an icon-only `Label` names its icon by its\n * title, as on iOS.\n */\n accessibilityLabel?: string | undefined;\n /**\n * `Image(uiImage:)` of a Core Image recipe: a source registered with\n * `bitmapSource` and the steps to draw it with (bitmaps.ts). Its size is\n * the recipe's extent in pixels over `scale`; a clamped (infinite) image\n * has none until it is cropped.\n */\n bitmap?: Bitmap;\n /** Pixels per point of a `bitmap` (`UIImage`'s `scale`): 1 by default. */\n scale?: number;\n /** `.interpolation(.none)`: a `bitmap` scaled up without smoothing (a QR code, pixel art). */\n interpolation?: 'none';\n}\n\nfunction imageProps(props: ImageProps): Record<string, unknown> {\n if (props.systemName !== undefined) return { systemName: props.systemName };\n if (props.bitmap !== undefined) {\n const { source, steps = [], version } = props.bitmap;\n const extent = bitmapExtent(source, steps);\n const finite = Number.isFinite(extent.width) && Number.isFinite(extent.height);\n const width = finite ? Math.max(0, Math.round(extent.width)) : 0;\n const height = finite ? Math.max(0, Math.round(extent.height)) : 0;\n const scale = props.scale !== undefined && props.scale > 0 ? props.scale : 1;\n return {\n bitmap: { source: source?.key ?? null, steps, width, height, ...(version !== undefined ? { version } : {}) },\n resizable: props.resizable ?? false,\n width: width / scale,\n height: height / scale,\n ...(props.interpolation === 'none' ? { interpolation: 'none' } : {}),\n };\n }\n if (props.url !== undefined) return { url: props.url, resizable: props.resizable ?? false, width: props.width ?? 0, height: props.height ?? 0 };\n return { name: props.name ?? '', resizable: props.resizable ?? false };\n}\n\nexport function Image(props: ImageProps): ReactNode {\n const { modifiers } = splitProps(props);\n const environment = useViewEnvironment();\n const redacted = takeModifier(modifiers, 'redacted') ?? environment.redacted;\n // `.palette`: an enclosed filled symbol draws its disc in the secondary\n // level and its glyph in the primary (`.foregroundStyle(.white, .indigo)`).\n const mode = takeModifier(modifiers, 'symbolRenderingMode') ?? environment.symbolRenderingMode;\n const own = imageProps(props);\n const element: Record<string, unknown> = props.systemName !== undefined && mode === 'palette' ? { ...own, renderingMode: 'palette' } : own;\n if (props.accessibilityLabel) element['accessibilityLabel'] = props.accessibilityLabel;\n return applyModifiers(placeholder(sb('image', element), redacted), modifiers);\n}\n\n// ---------------------------------------------------------------------------\n// Label, LabeledContent, Link\n// ---------------------------------------------------------------------------\n\nexport interface LabelProps extends ViewModifiers {\n title: ReactNode;\n systemImage?: string;\n image?: string;\n /** A custom icon view instead of a symbol. */\n icon?: ReactNode;\n}\n\n/** `Label(\"Favorites\", systemImage: \"heart.fill\")`: an 8pt-spaced `HStack` of icon and title. */\nexport function Label(props: LabelProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const environment = useViewEnvironment();\n const style = takeModifier(modifiers, 'labelStyle') ?? environment.labelStyle ?? 'automatic';\n const icon = own.icon ?? (own.systemImage !== undefined ? <Image systemName={own.systemImage} /> : own.image !== undefined ? <Image name={own.image} /> : null);\n const title = typeof own.title === 'string' || typeof own.title === 'number' ? <Text>{own.title}</Text> : own.title;\n if (style === 'iconOnly') {\n // As on iOS, the title stays the icon's accessible name (a toolbar\n // button's), as the Swift shim's label does.\n const name = typeof own.title === 'string' || typeof own.title === 'number' ? String(own.title) : undefined;\n const named =\n own.icon === undefined && name !== undefined\n ? own.systemImage !== undefined\n ? <Image systemName={own.systemImage} accessibilityLabel={name} />\n : own.image !== undefined\n ? <Image name={own.image} accessibilityLabel={name} />\n : icon\n : icon;\n return applyModifiers(named, modifiers);\n }\n if (style === 'titleOnly') return applyModifiers(title, modifiers);\n // The marked icon makes the stack a `Label` to the native renderer, which\n // iOS lays out as one: the icon column of a list row, the icon alone in a\n // bar. An explicit `titleAndIcon` asks for both wherever it is, so it is a\n // plain stack of the two.\n return applyModifiers(\n <HStack spacing={8}>\n {style === 'titleAndIcon' ? icon : styled({ labelIcon: true }, icon)}\n {title}\n </HStack>,\n modifiers,\n );\n}\n\nexport interface LabeledContentProps extends ViewModifiers {\n label: ReactNode;\n value?: ReactNode;\n children?: ReactNode;\n}\n\n/** `LabeledContent(\"Storage\", value: \"2.4 GB\")`: the label, a spacer, the value in the secondary color. */\nexport function LabeledContent(props: LabeledContentProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const label = typeof own.label === 'string' || typeof own.label === 'number' ? <Text>{own.label}</Text> : own.label;\n const content = own.children ?? own.value;\n const value = typeof content === 'string' || typeof content === 'number' ? <Text>{content}</Text> : content;\n return applyModifiers(\n <HStack>\n {label}\n {sb('spacer', { minLength: null })}\n {styled({ foreground: { hierarchical: 2 } }, value)}\n </HStack>,\n modifiers,\n );\n}\n\nexport interface LinkProps extends ViewModifiers {\n destination: string;\n title?: string;\n children?: ReactNode;\n}\n\n/** `Link(\"Visit the website\", destination:)`: a plain button that opens the URL. */\nexport function Link(props: LinkProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const label = own.title !== undefined ? <Text>{own.title}</Text> : own.children;\n return applyModifiers(sb('button', { role: null, style: 'automatic' }, { tap: () => openURL(own.destination) }, label), modifiers);\n}\n","import { Fragment, isValidElement, useContext, useRef, useState, type ReactNode } from 'react';\nimport { readBinding, type BindingValue } from '../binding';\nimport { DismissContext, useViewEnvironment } from '../environment';\nimport { HostTreeContext } from '../host/root';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, takeModifier, type ViewModifiers } from '../modifiers';\nimport { NavigationContext, RegisterDestination, ScreenDepthContext, useNavigation, type NavigationContextValue } from '../navigation-context';\nimport { ListSelectionContext } from './row';\nimport { SplitSelectionContext } from './split';\nimport { Text } from './text';\n\nexport interface NavigationStackProps extends ViewModifiers {\n /** `NavigationStack(path:)`: the pushed values. */\n path?: BindingValue<readonly unknown[]>;\n onPathChange?: (path: readonly unknown[]) => void;\n /** `.navigationDestination(for:)`, for every pushed value. */\n destination?: (value: never) => ReactNode;\n children?: ReactNode;\n}\n\n/** A pushed destination view (`NavigationLink(destination:)`), kept in the path. */\ninterface PushedView {\n view: ReactNode;\n}\n\nconst isPushedView = (value: unknown): value is PushedView => typeof value === 'object' && value !== null && 'view' in value && isValidElement((value as PushedView).view);\n\n/**\n * A pushed value as plain data (strings, finite numbers, booleans, null, and\n * arrays and plain objects of them), or undefined for anything else (a view,\n * a function, a class instance). In a tree another draws (a remote root), a\n * pushed screen carries it as `route`, so the tree that hosts it (`RemoteTree`) can name the screen, in a URL\n * say, and set the path back from it (`setpath`), as SwiftUI's\n * `NavigationPath` of `Codable` values can be saved and restored.\n */\nexport function routeOf(value: unknown, depth = 0): unknown {\n if (depth > 8) return undefined;\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return value;\n if (typeof value === 'number') return Number.isFinite(value) ? value : undefined;\n if (Array.isArray(value)) {\n const items = value.map((item) => routeOf(item, depth + 1));\n return items.every((item) => item !== undefined) ? items : undefined;\n }\n if (typeof value === 'object' && !isPushedView(value)) {\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null) return undefined;\n const out: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value)) {\n if (item === undefined) continue;\n const plain = routeOf(item, depth + 1);\n if (plain === undefined) return undefined;\n out[key] = plain;\n }\n return out;\n }\n return undefined;\n}\n\nexport function NavigationStack(props: NavigationStackProps): ReactNode {\n const enclosing = useNavigation();\n // A stack inside another stack's screen is flattened, as SwiftUI does: its\n // content renders in place and its links push onto the enclosing stack.\n if (enclosing) return <FlattenedStack {...props} />;\n return <OwnStack {...props} />;\n}\n\nfunction FlattenedStack(props: NavigationStackProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n return applyModifiers(\n <>\n {own.destination && <RegisterDestination destination={own.destination} />}\n {own.children}\n </>,\n modifiers,\n );\n}\n\nfunction OwnStack(props: NavigationStackProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n // Routes are for a tree another draws (RemoteTree); a renderer has no use for them.\n const remote = useContext(HostTreeContext)?.remote ?? false;\n const [internalPath, setInternalPath] = useState<readonly unknown[]>([]);\n const [path, setPath] = own.path !== undefined ? readBinding(own.path, own.onPathChange) : [internalPath, setInternalPath];\n const destination = useRef<((value: unknown) => ReactNode) | null>(null);\n destination.current = (own.destination as ((value: unknown) => ReactNode) | undefined) ?? null;\n const context: NavigationContextValue = {\n push: (value) => setPath([...path, value]),\n pop: () => setPath(path.slice(0, -1)),\n path,\n setPath: (next) => setPath(next),\n registerDestination: (builder) => {\n destination.current = builder;\n },\n };\n const screens: ReactNode[] = [\n <Fragment key=\"root\">\n {sb('navscreen', { title: '', displayMode: 'automatic', depth: 0 }, { tap: context.pop }, <ScreenDepthContext.Provider value={0}>{own.children}</ScreenDepthContext.Provider>)}\n </Fragment>,\n ];\n path.forEach((value, index) => {\n const pop = (): void => setPath(path.slice(0, index));\n const route = remote ? routeOf(value) : undefined;\n screens.push(\n <Fragment key={index + 1}>\n {sb(\n 'navscreen',\n { title: '', displayMode: 'automatic', depth: index + 1, ...(route === undefined ? {} : { route }) },\n { tap: pop },\n <DismissContext.Provider value={pop}>\n <ScreenDepthContext.Provider value={index + 1}>\n <PathScreen value={value} destination={destination} />\n </ScreenDepthContext.Provider>\n </DismissContext.Provider>,\n )}\n </Fragment>,\n );\n });\n return applyModifiers(\n sb('navstack', {}, { setpath: (event) => setPath(Array.isArray(event.path) ? event.path : []) }, <NavigationContext.Provider value={context}>{screens}</NavigationContext.Provider>),\n modifiers,\n );\n}\n\n/** Rendered after the root screen, so a destination the root registered is known. */\nfunction PathScreen({ value, destination }: { value: unknown; destination: { current: ((value: unknown) => ReactNode) | null } }): ReactNode {\n if (isPushedView(value)) return value.view;\n return destination.current ? destination.current(value) : null;\n}\n\nexport interface NavigationLinkProps extends ViewModifiers {\n title?: string;\n /** The value to push (`navigationDestination` builds the screen). */\n value?: unknown;\n /** The screen to push. */\n destination?: ReactNode;\n children?: ReactNode;\n}\n\nexport function NavigationLink(props: NavigationLinkProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const navigation = useNavigation();\n const environment = useViewEnvironment();\n const label = own.title !== undefined ? <Text>{own.title}</Text> : own.children;\n // In a split view's sidebar, a `List(selection:)`'s value link selects its\n // value instead of pushing it, and the split shows the detail for it (or,\n // compact, pushes it), as SwiftUI does.\n const listSelection = useContext(ListSelectionContext);\n const sidebar = useContext(SplitSelectionContext) !== null && listSelection !== null && own.destination === undefined && own.value !== undefined;\n const tap = (): void => {\n if (sidebar) {\n listSelection.select(own.value);\n return;\n }\n if (!navigation) return;\n if (own.destination !== undefined) navigation.push({ view: own.destination } satisfies PushedView);\n else navigation.push(own.value);\n };\n // Under `.buttonStyle(.plain)` (its own or around it) the label keeps the\n // foreground it is in instead of the tint.\n const style = takeModifier(modifiers, 'buttonStyle') ?? environment.buttonStyle;\n const linkProps: Record<string, unknown> = style === 'plain' ? { style: 'plain' } : {};\n // A sidebar's link is its row's selection: natively the cell takes the\n // touch and selects itself, as in SwiftUI's split view, rather than the\n // link's button setting the selection after it.\n if (sidebar) linkProps['selects'] = true;\n return applyModifiers(sb('navlink', linkProps, { tap }, label), modifiers);\n}\n","/**\n * `NavigationSplitView`: in a regular width a `navsplit` of two columns (the\n * sidebar's stack and the detail's), the sidebar toggled by the bar button;\n * in a compact width one stack rooted at the sidebar that pushes the detail\n * while the sidebar's list has a selection, as on iOS.\n */\n\nimport { createContext, isValidElement, useLayoutEffect, useRef, useState, type ReactNode } from 'react';\nimport { readBinding, type BindingValue } from '../binding';\nimport { useHorizontalSizeClass } from '../environment';\nimport { withAnimation } from '../host/root';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, type ViewModifiers } from '../modifiers';\nimport { NavigationContext } from '../navigation-context';\nimport { NavigationStack, type NavigationStackProps } from './navigation';\n\nexport type NavigationSplitViewVisibility = 'automatic' | 'all' | 'doubleColumn' | 'detailOnly';\n\n/**\n * What the sidebar's `List(selection:)`s tell their split view: whether\n * each has something selected, and how to clear it. Each list reports under\n * its own key and retracts when it unmounts; the split pushes the detail in\n * a compact width while any of them has a selection.\n */\nexport interface SplitSelection {\n report(key: object, selected: boolean, clear: () => void): void;\n retract(key: object): void;\n}\n\nexport const SplitSelectionContext = createContext<SplitSelection | null>(null);\n\n/**\n * `.navigationSplitViewColumnWidth`: a number is a fixed width; `{ min, ideal,\n * max }` a flexible one, the column starting at `ideal` and, on a Mac, dragged\n * between `min` and `max`.\n */\nexport type SplitColumnWidth = number | { min?: number; ideal: number; max?: number };\n\nexport interface NavigationSplitViewProps extends ViewModifiers {\n sidebar: ReactNode;\n detail: ReactNode;\n columnVisibility?: BindingValue<NavigationSplitViewVisibility>;\n onColumnVisibilityChange?: (visibility: NavigationSplitViewVisibility) => void;\n /**\n * The sidebar column's width (SwiftUI's `.navigationSplitViewColumnWidth` on\n * the sidebar's content); absent, the platform's default (140 on a Mac,\n * 320 on an iPad).\n */\n sidebarWidth?: SplitColumnWidth;\n /**\n * The sidebar was dragged to a new width (a Mac's column divider), once\n * the drag ends: keep it and pass it back as `sidebarWidth`'s `ideal` to\n * start there next time, as a Mac app restores its columns.\n */\n onSidebarWidthChange?: (width: number) => void;\n}\n\n/** The `splitColumnWidth` hint a `sidebarWidth` sends: `{ min?, ideal, max? }`, a fixed width being all three. */\nfunction splitColumnWidthHint(width: SplitColumnWidth): Record<string, number> {\n if (typeof width === 'number') return { min: width, ideal: width, max: width };\n return { ...(width.min !== undefined ? { min: width.min } : {}), ideal: width.ideal, ...(width.max !== undefined ? { max: width.max } : {}) };\n}\n\nexport function NavigationSplitView(props: NavigationSplitViewProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const sizeClass = useHorizontalSizeClass();\n const [selected, setSelected] = useState(false);\n // Each sidebar list's selection and its latest way to clear it (a new\n // closure each render; not state). The split follows whether any has one,\n // so two lists settle instead of overruling each other.\n // One object for the split's life: the lists key their reports by it, and\n // a new one each render would retract and re-report them every pass.\n const reporters = useRef(new Map<object, { selected: boolean; clear: () => void }>());\n // `setSelected` with an unchanged value is a no-op, so the lists settle.\n const settle = (): void => setSelected([...reporters.current.values()].some((entry) => entry.selected));\n const [report] = useState<SplitSelection>(() => {\n return {\n report: (key, nowSelected, clear) => {\n reporters.current.set(key, { selected: nowSelected, clear });\n settle();\n },\n retract: (key) => {\n if (reporters.current.delete(key)) settle();\n },\n };\n });\n // A pop clears the selection and the split's record of it together, so the\n // detail goes in the commit that unmarks the row.\n const clear = (): void => {\n for (const entry of reporters.current.values()) {\n if (!entry.selected) continue;\n entry.clear();\n entry.selected = false;\n }\n settle();\n };\n const [internal, setInternal] = useState<NavigationSplitViewVisibility>('automatic');\n const [visibility, setVisibility] =\n own.columnVisibility !== undefined ? readBinding(own.columnVisibility, own.onColumnVisibilityChange) : [internal, setInternal];\n\n if (sizeClass === 'compact') {\n return applyModifiers(<CompactSplit sidebar={own.sidebar} detail={own.detail} report={report} selected={selected} clear={clear} />, modifiers);\n }\n\n const sidebarVisible = visibility !== 'detailOnly';\n const toggle = (): void => withAnimation(() => setVisibility(sidebarVisible ? 'detailOnly' : 'all'));\n const detail = isValidElement(own.detail) && own.detail.type === NavigationStack ? own.detail : <NavigationStack>{own.detail}</NavigationStack>;\n // The width rides on the sidebar content's styled wrapper, as the shim's modifier sends it.\n const hinted = (content: ReactNode): ReactNode => (own.sidebarWidth !== undefined ? sb('styled', { style: { splitColumnWidth: splitColumnWidthHint(own.sidebarWidth) } }, undefined, content) : content);\n // A sidebar that is a `NavigationStack` of its own (one with a bound path: a host pushing another root's\n // sidebar onto it, `useRemoteSidebar`) is the column's stack, the hint around it (the engine reads it there\n // too); any other sidebar gets a stack.\n const sidebar = isValidElement(own.sidebar) && own.sidebar.type === NavigationStack ? hinted(own.sidebar) : <NavigationStack>{hinted(own.sidebar)}</NavigationStack>;\n return applyModifiers(\n sb('navsplit', { sidebarVisible }, { tap: toggle, columnwidth: (event: { width: number }) => own.onSidebarWidthChange?.(event.width) }, [\n <SplitColumn key=\"sidebar\" report={report}>\n {sidebar}\n </SplitColumn>,\n <SplitColumn key=\"detail\" report={null}>\n {detail}\n </SplitColumn>,\n ]),\n modifiers,\n );\n}\n\n/** A column: its own navigation scope (no enclosing stack), and the sidebar's selection reporting. */\nfunction SplitColumn({ report, children }: { report: SplitSelection | null; children?: ReactNode }): ReactNode {\n return (\n <NavigationContext.Provider value={null}>\n <SplitSelectionContext.Provider value={report}>{children}</SplitSelectionContext.Provider>\n </NavigationContext.Provider>\n );\n}\n\nfunction CompactSplit({\n sidebar,\n detail,\n report,\n selected,\n clear,\n}: {\n sidebar: ReactNode;\n detail: ReactNode;\n report: SplitSelection;\n selected: boolean;\n clear: () => void;\n}): ReactNode {\n // Pushes made from the detail, after it. A detail that is a NavigationStack\n // with a path binding keeps them there, as it would in its own column in a\n // regular width: the app sees the same path either way (and can set it).\n const [internal, setInternal] = useState<readonly unknown[]>([]);\n const detailStack = isValidElement(detail) && detail.type === NavigationStack ? (detail.props as NavigationStackProps) : null;\n const [extra, setExtra] = detailStack?.path !== undefined ? readBinding(detailStack.path, detailStack.onPathChange) : [internal, setInternal];\n const base = selected ? [{ view: detail }] : [];\n const path = [...base, ...extra];\n const setPath = (next: readonly unknown[]): void => {\n if (selected && next.length === 0) {\n setExtra([]);\n clear();\n return;\n }\n setExtra(next.slice(base.length));\n };\n // Only the sidebar reports its selection: the screens pushed over it (the\n // detail, and what the detail pushes) are outside it, so a selectable list\n // there (a folder's, for Select) keeps its links pushing.\n return (\n <NavigationContext.Provider value={null}>\n <SplitSelectionContext.Provider value={null}>\n <NavigationStack path={[path, setPath]}>\n <SplitSelectionContext.Provider value={report}>{sidebar}</SplitSelectionContext.Provider>\n </NavigationStack>\n </SplitSelectionContext.Provider>\n </NavigationContext.Provider>\n );\n}\n\n/**\n * Used by `List(selection:)`: tells the enclosing split view whether the\n * sidebar has a selection. A list without a selection binding (a `Form`, a\n * plain list) passes `active: false` and says nothing.\n */\nexport function useReportSplitSelection(\n split: SplitSelection | null,\n selected: boolean,\n clear: () => void,\n active = true,\n): (selected: boolean, clear: () => void) => void {\n const key = useRef({}).current;\n useLayoutEffect(() => {\n if (active) split?.report(key, selected, clear);\n else split?.retract(key);\n });\n useLayoutEffect(() => () => split?.retract(key), [split, key]);\n // A selection made by a tap, reported in the same update as the list's\n // own: a compact split then pushes the detail in the commit that marks the\n // row, rather than in the next one (natively the root screen would change\n // a frame before the push began, and lose its large title at once).\n return (nowSelected, nowClear) => {\n if (active) split?.report(key, nowSelected, nowClear);\n };\n}\n\n/** Presented content (a sheet, a popover, an inspector) is outside its presenter's split column. */\nexport function OutsideSplit({ children }: { children?: ReactNode }): ReactNode {\n return <SplitSelectionContext.Provider value={null}>{children}</SplitSelectionContext.Provider>;\n}\n","/**\n * Sheets and alerts: presented content becomes a root-level `sheet` / `alert`\n * element after the app's tree, as the Swift core emits them.\n */\n\nimport type { Detent, Style } from '@swiftbrowser/web/src/protocol';\nimport { useEffect, type ReactNode } from 'react';\nimport { readBinding, type BindingValue } from './binding';\nimport { DismissContext, withEnvironment } from './environment';\nimport { HOIST_KIND, PREF_KIND } from './host/instance';\nimport { NavigationContext } from './navigation-context';\nimport { OutsideSplit } from './components/split';\nimport { sb } from './host/sb';\nimport { replayStyles, useInheritedStyles } from './inheritedStyle';\n\nexport interface SheetModifier {\n isPresented: BindingValue<boolean>;\n onDismiss?: () => void;\n content: ReactNode;\n /** `.fullScreenCover` */\n fullScreen?: boolean;\n}\n\n/**\n * A sheet, a full-screen cover or a popover. Its content inherits the\n * presenter's environment, as SwiftUI's presentations do: the inherited\n * styles set around the presenter (`inheritedStyle.ts`), then `inherited`,\n * those its own view sets around it, outermost first.\n */\nexport function SheetPresenter({ isPresented, onDismiss, content, fullScreen, inherited }: SheetModifier & { inherited?: readonly Style[] }): ReactNode {\n const around = useInheritedStyles();\n const [presented, setPresented] = readBinding(isPresented);\n if (!presented) return null;\n const dismiss = (): void => {\n setPresented(false);\n onDismiss?.();\n };\n const detents: Detent[] = fullScreen ? ['full'] : ['large'];\n return sb(\n HOIST_KIND,\n undefined,\n undefined,\n sb(\n 'sheet',\n { detents },\n { tap: dismiss },\n replayStyles(\n inherited && inherited.length > 0 ? [...around, ...inherited] : around,\n <NavigationContext.Provider value={null}>\n <OutsideSplit>\n <DismissContext.Provider value={dismiss}>{content}</DismissContext.Provider>\n </OutsideSplit>\n </NavigationContext.Provider>,\n ),\n ),\n 'root',\n );\n}\n\n/** `.presentationDetents([.medium])`, inside a sheet's content. */\nexport type DetentValue = Detent | { height: number } | { fraction: number };\n\nexport function presentationDetents(detents: DetentValue[]): ReactNode {\n const encoded = detents.map(\n (detent): Detent => (typeof detent === 'string' ? detent : 'height' in detent ? `height:${detent.height}` : `fraction:${detent.fraction}`),\n );\n return sb(PREF_KIND, { detents: encoded }, undefined, undefined, 'sheet');\n}\n\nexport interface AlertModifier {\n title: string;\n isPresented: BindingValue<boolean>;\n message?: string;\n /**\n * The buttons, each dismissing the alert when tapped, and any `TextField`s\n * (`.alert { TextField(\"Name\", text: $name); Button(\"Rename\") { } }`),\n * drawn in the card between the message and the buttons.\n */\n actions?: ReactNode;\n /** `.confirmationDialog` */\n style?: 'alert' | 'dialog';\n}\n\nexport function AlertPresenter({ title, isPresented, message, actions, style }: AlertModifier): ReactNode {\n const [presented, setPresented] = readBinding(isPresented);\n if (!presented) return null;\n const dismiss = (): void => setPresented(false);\n return sb(\n HOIST_KIND,\n undefined,\n undefined,\n sb(\n 'alert',\n { title, message: message ?? null, style: style ?? 'alert' },\n { tap: dismiss },\n withEnvironment({ dismissAlert: dismiss }, actions),\n ),\n 'root',\n );\n}\n\n/** `.onAppear` / `.onDisappear` */\nexport function Lifecycle({ onAppear, onDisappear }: { onAppear?: () => void; onDisappear?: () => void }): null {\n useEffect(() => {\n onAppear?.();\n return () => onDisappear?.();\n // Once per mount, like SwiftUI.\n }, []);\n return null;\n}\n","/**\n * `.inspector(isPresented:)`: in a regular width an `inspector` element, the\n * view and a trailing `inspectorpanel` the renderer slides in and out; in a\n * compact width a sheet with the inspector's content.\n */\n\nimport type { ReactNode } from 'react';\nimport { readBinding } from './binding';\nimport { useHorizontalSizeClass } from './environment';\nimport { sb } from './host/sb';\nimport type { InspectorModifier } from './modifiers';\nimport { SheetPresenter } from './presentation';\nimport { OutsideSplit } from './components/split';\n\nexport function Inspector({ isPresented, content, columnWidth, children }: InspectorModifier & { children?: ReactNode }): ReactNode {\n const sizeClass = useHorizontalSizeClass();\n const [presented, setPresented] = readBinding(isPresented);\n if (sizeClass === 'compact') {\n return (\n <>\n {children}\n <SheetPresenter isPresented={[presented, setPresented]} content={content} />\n </>\n );\n }\n // The panel is beside the content, not part of its split column.\n const outside = <OutsideSplit>{content}</OutsideSplit>;\n const panelContent = columnWidth !== undefined ? sb('styled', { style: { inspectorColumnWidth: columnWidth } }, undefined, outside) : outside;\n return sb('inspector', { presented }, undefined, [\n <InspectorPart key=\"content\">{children}</InspectorPart>,\n <InspectorPart key=\"panel\">{sb('inspectorpanel', {}, undefined, panelContent)}</InspectorPart>,\n ]);\n}\n\nfunction InspectorPart({ children }: { children?: ReactNode }): ReactNode {\n return children;\n}\n","/** `.task` and `.onChange(of:)`, as components the modifiers place beside the view. */\n\nimport { useEffect, useRef } from 'react';\n\nexport function Task({ id, action }: { id: unknown; action: (signal: AbortSignal) => unknown }): null {\n const latest = useRef(action);\n latest.current = action;\n useEffect(() => {\n const controller = new AbortController();\n Promise.resolve()\n .then(() => latest.current(controller.signal))\n .catch((error: unknown) => {\n // A cancelled task's rejection is expected, as Swift's CancellationError is.\n if (!controller.signal.aborted) console.error(error);\n });\n return () => controller.abort();\n }, [id]);\n return null;\n}\n\nexport function OnChange({\n value,\n action,\n initial,\n}: {\n value: unknown;\n action: (oldValue: unknown, newValue: unknown) => void;\n initial?: boolean;\n}): null {\n const previous = useRef<{ value: unknown } | null>(null);\n const latest = useRef(action);\n latest.current = action;\n useEffect(() => {\n const last = previous.current;\n previous.current = { value };\n if (last === null) {\n if (initial) latest.current(value, value);\n return;\n }\n if (!Object.is(last.value, value)) latest.current(last.value, value);\n }, [value, initial]);\n return null;\n}\n","/**\n * Named coordinate spaces: `.coordinateSpace(name:)` reports where its view\n * is on screen (a layout-transparent `zstack` with `reportsFrame`), and a\n * `GeometryReader` inside answers `frame({ named })` relative to it.\n */\n\nimport { createContext, useContext, useState, type ReactNode } from 'react';\nimport { sb } from './host/sb';\n\nexport interface SpaceFrame {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/** The named spaces around a view: their frames on screen (null until reported). */\nexport const CoordinateSpacesContext = createContext<Readonly<Record<string, SpaceFrame | null>>>({});\n\nexport function useCoordinateSpaces(): Readonly<Record<string, SpaceFrame | null>> {\n return useContext(CoordinateSpacesContext);\n}\n\nexport function CoordinateSpace({ name, children }: { name: string; children?: ReactNode }): ReactNode {\n const spaces = useContext(CoordinateSpacesContext);\n const [frame, setFrame] = useState<SpaceFrame | null>(null);\n return (\n <CoordinateSpacesContext.Provider value={{ ...spaces, [name]: frame }}>\n {sb(\n 'zstack',\n { alignment: 'center', reportsSize: true, reportsFrame: true },\n {\n geometry: (event) => {\n const next = { x: event.x ?? 0, y: event.y ?? 0, width: event.width, height: event.height };\n if (!frame || frame.x !== next.x || frame.y !== next.y || frame.width !== next.width || frame.height !== next.height) setFrame(next);\n },\n },\n children,\n )}\n </CoordinateSpacesContext.Provider>\n );\n}\n","/**\n * `GeometryReader` and custom `Layout`: both are round trips with the\n * renderer. The engine lays the element out and reports what it found (a\n * `geometry` event with the size, a `layout` event with the children's\n * measurements); the component answers by rendering again.\n */\n\nimport type { Dimension, GeometryEvent, LayoutChildMeasurement, LayoutProposal as ProtocolProposal } from '@swiftbrowser/web/src/protocol';\nimport { useEffect, useLayoutEffect, useRef, useState, type ReactElement, type ReactNode } from 'react';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, type ModifierKey, type ViewModifiers } from '../modifiers';\nimport { unitPoint, type UnitPointValue } from '../values';\nimport { flattenChildren } from './stacks';\nimport { useCoordinateSpaces } from '../coordinateSpace';\n\nexport interface Size {\n width: number;\n height: number;\n}\n\nexport interface Rect extends Size {\n x: number;\n y: number;\n}\n\n/** A reader's safe-area insets, every edge given. */\nexport interface SafeAreaInsets {\n top: number;\n leading: number;\n bottom: number;\n trailing: number;\n}\n\n/** `GeometryProxy`: what the reader's content is told. */\nexport interface GeometryProxy {\n size: Size;\n /**\n * The reader's frame: in its own space (`local`, the default), on the\n * root's screen (`global`), or relative to an enclosing view marked\n * `coordinateSpace=\"name\"` (`{ named: 'name' }`), scrolling included, kept\n * current as the views around it scroll.\n */\n frame(space?: 'local' | 'global' | { named: string }): Rect;\n /**\n * `bounds(of: .scrollView)`: the visible part of the scroll view (or list)\n * the reader is in, in the reader's own coordinates; null outside one.\n */\n bounds(of: 'scrollView'): Rect | null;\n /** How far the device's safe area (the status bar, the home indicator) reaches into the reader. */\n safeAreaInsets: SafeAreaInsets;\n}\n\nexport interface GeometryReaderProps extends ViewModifiers {\n children: (proxy: GeometryProxy) => ReactNode;\n}\n\n/** What the page last reported about a reader. */\nexport interface ReportedGeometry {\n size: Size;\n origin: { x: number; y: number } | null;\n safeArea: SafeAreaInsets;\n /** The enclosing scroll view's visible rectangle on screen, and its axis. */\n scrollView: (Rect & { axis: 'horizontal' | 'vertical' }) | null;\n}\n\nconst NO_INSETS: SafeAreaInsets = { top: 0, leading: 0, bottom: 0, trailing: 0 };\n\nexport const NO_GEOMETRY: ReportedGeometry = { size: { width: 0, height: 0 }, origin: null, safeArea: NO_INSETS, scrollView: null };\n\n/** The reader's record after a `geometry` event. */\nexport function nextGeometry(event: GeometryEvent, reported: ReportedGeometry): ReportedGeometry {\n const hasOrigin = event.x !== undefined && event.y !== undefined;\n return {\n size: { width: event.width, height: event.height },\n origin: hasOrigin ? { x: event.x!, y: event.y! } : reported.origin,\n safeArea: event.safeArea ?? reported.safeArea,\n // A frame report without a scroll view means the reader is in none.\n scrollView: hasOrigin ? (event.scrollView ?? null) : reported.scrollView,\n };\n}\n\n/**\n * The proxy over a reader's record. `onReadFrame` is called when the content\n * reads anything that needs the reader's place on screen.\n */\nexport function geometryProxy(reported: ReportedGeometry, spaces: Readonly<Record<string, { x: number; y: number } | null>>, onReadFrame: () => void): GeometryProxy {\n return {\n size: reported.size,\n frame: (space = 'local') => {\n if (space === 'local') return { x: 0, y: 0, ...reported.size };\n onReadFrame();\n const origin = reported.origin ?? { x: 0, y: 0 };\n if (space === 'global') return { ...origin, ...reported.size };\n const named = spaces[space.named];\n return { x: origin.x - (named?.x ?? 0), y: origin.y - (named?.y ?? 0), ...reported.size };\n },\n bounds: () => {\n onReadFrame();\n const view = reported.scrollView;\n if (!view || !reported.origin) return null;\n return { x: view.x - reported.origin.x, y: view.y - reported.origin.y, width: view.width, height: view.height };\n },\n get safeAreaInsets() {\n onReadFrame();\n return reported.safeArea;\n },\n };\n}\n\n/**\n * `GeometryReader { proxy in }`: fills its proposal and reports its size.\n * The content renders with a zero size first and again with the real one in\n * the same event cycle, before the page paints. A content that reads the\n * global frame, the scroll view's bounds or the safe-area insets asks the\n * page for them from then on.\n */\nexport function GeometryReader(props: GeometryReaderProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const [reported, setReported] = useState<ReportedGeometry>(NO_GEOMETRY);\n const [needsFrame, setNeedsFrame] = useState(false);\n let readFrame = false;\n const proxy = geometryProxy(reported, useCoordinateSpaces(), () => {\n readFrame = true;\n });\n const content = own.children(proxy);\n useEffect(() => {\n if (readFrame && !needsFrame) setNeedsFrame(true);\n });\n return applyModifiers(\n sb(\n 'geometry',\n needsFrame ? { reportsFrame: true } : {},\n {\n geometry: (event) => {\n const next = nextGeometry(event, reported);\n if (JSON.stringify(next) !== JSON.stringify(reported)) setReported(next);\n },\n },\n content,\n ),\n modifiers,\n );\n}\n\n// ---------------------------------------------------------------------------\n// `.onGeometryChange`\n// ---------------------------------------------------------------------------\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- the spec's value type is the transform's to infer\nexport type GeometryChangeHandler = ((proxy: GeometryProxy) => void) | GeometryChangeSpec<any>;\n\nexport interface GeometryChangeSpec<T> {\n /** The `of:` transform: what of the view's geometry the action watches (`proxy.size`, `proxy.frame('global')`…). */\n of: (proxy: GeometryProxy) => T;\n /** Called when the transform's answer changes, with the new and the old value (the first time, both the new). */\n action: (value: T, oldValue: T) => void;\n}\n\n/**\n * `.onGeometryChange(for:of:action:)` (iOS 18): the view in a box that\n * reports its size (and its frame on screen once the transform reads it,\n * kept current as the page scrolls) without changing its layout; the\n * action runs after the render that heard a change, as SwiftUI's does, so it\n * may set state. It runs in the commit (a layout effect), before anything is\n * painted: state it sets renders and lays out synchronously, so a layout\n * that depends on its own measurement settles within the frame, as a\n * `GeometryReader`'s does in SwiftUI, instead of one round per frame with\n * the page painting each. A function form is called with the proxy on\n * every change.\n */\nexport function GeometryChangeView({ handler, children }: { handler: GeometryChangeHandler; children?: ReactNode }): ReactNode {\n const [reported, setReported] = useState<ReportedGeometry>(NO_GEOMETRY);\n const [needsFrame, setNeedsFrame] = useState(false);\n const last = useRef<{ value: unknown } | null>(null);\n const spaces = useCoordinateSpaces();\n let readFrame = false;\n const proxy = geometryProxy(reported, spaces, () => {\n readFrame = true;\n });\n // Nothing is known before the first report; the transform runs from then on.\n const heard = reported !== NO_GEOMETRY;\n const value = heard && typeof handler !== 'function' ? handler.of(proxy) : undefined;\n useLayoutEffect(() => {\n if (readFrame && !needsFrame) setNeedsFrame(true);\n });\n useLayoutEffect(() => {\n if (!heard) return;\n if (typeof handler === 'function') {\n handler(proxy);\n return;\n }\n const previous = last.current;\n if (previous && JSON.stringify(previous.value) === JSON.stringify(value)) return;\n last.current = { value };\n handler.action(value, previous ? previous.value : value);\n });\n return sb(\n 'zstack',\n { alignment: 'center', reportsSize: true, ...(needsFrame ? { reportsFrame: true } : {}) },\n {\n geometry: (event) => {\n const next = nextGeometry(event, reported);\n if (JSON.stringify(next) !== JSON.stringify(reported)) setReported(next);\n },\n },\n children,\n );\n}\n\n// ---------------------------------------------------------------------------\n// Custom layouts\n// ---------------------------------------------------------------------------\n\n/** A proposal axis: points, `Infinity`, or `null` (unspecified). */\nexport interface LayoutProposal {\n width: number | null;\n height: number | null;\n}\n\nexport interface LayoutSubview {\n /** The engine's answers for a zero, unspecified and infinite proposal. */\n min: Size;\n ideal: Size;\n max: Size;\n /** `.layoutPriority` of the subview (0 by default). */\n priority: number;\n /** `.layoutValue(key:value:)`s of the subview (`subview[Key.self]`). */\n values: Readonly<Record<string, unknown>>;\n /** `ViewSpacing`: the space the subview wants beside another, iOS's default 8 between views. */\n spacing: ViewSpacing;\n /** The size for a proposal: `ideal` on an unspecified axis, else clamped to min…max. */\n sizeThatFits(proposal: LayoutProposal): Size;\n /** Place the subview: `at` is the point `anchor` (default top leading) lands on, in the layout's bounds. */\n place(options: { x: number; y: number; anchor?: UnitPointValue; proposal?: LayoutProposal }): void;\n}\n\n/** `ViewSpacing`: what a subview wants between itself and a neighbor. */\nexport interface ViewSpacing {\n /** `distance(to:along:)`: the space between this subview and `next` on an axis. */\n distance(next: ViewSpacing, axis: 'horizontal' | 'vertical'): number;\n}\n\n/** iOS's default space between two views, the renderer's stack spacing when none is given. */\nexport const DEFAULT_VIEW_SPACING: ViewSpacing = { distance: () => 8 };\n\nexport type LayoutGuide = 'leading' | 'horizontalCenter' | 'trailing' | 'top' | 'verticalCenter' | 'bottom' | 'firstTextBaseline' | 'lastTextBaseline';\n\n/** SwiftUI's `Layout` protocol: the two methods, an optional cache shared by them, and explicit alignment guides. */\nexport interface CustomLayout<Cache = unknown> {\n sizeThatFits(proposal: LayoutProposal, subviews: readonly LayoutSubview[], cache: Cache): Size;\n placeSubviews(bounds: Rect, proposal: LayoutProposal, subviews: readonly LayoutSubview[], cache: Cache): void;\n /** `makeCache(subviews:)`: computed once for the subviews, before sizing and placing. */\n makeCache?(subviews: readonly LayoutSubview[]): Cache;\n /**\n * `explicitAlignment(of:in:proposal:subviews:cache:)`: where the layout\n * puts a guide, in its bounds (null: the guide's default). A stack, frame\n * or overlay aligning the layout by that guide uses it.\n */\n explicitAlignment?(guide: LayoutGuide, bounds: Rect, proposal: LayoutProposal, subviews: readonly LayoutSubview[], cache: Cache): number | null;\n /** `spacing(subviews:cache:)`: accepted; the engine spaces the layout like any view (8 by default). */\n spacing?(subviews: readonly LayoutSubview[], cache: Cache): ViewSpacing;\n}\n\n/** What `Layout` reads from each subview's element besides the engine's measurements. */\nexport interface SubviewTraits {\n priority: number;\n values: Record<string, unknown>;\n}\n\nexport interface LayoutProps<Cache = unknown> extends ViewModifiers {\n layout: CustomLayout<Cache>;\n children?: ReactNode;\n}\n\n/** Each subview's `layoutPriority` and `layoutValue`s, read from its element's props. */\nfunction subviewTraits(children: ReactNode): SubviewTraits[] {\n return flattenChildren(children).map((element: ReactElement) => {\n const props = element.props as { layoutPriority?: number; layoutValue?: Record<string, unknown> };\n return { priority: props.layoutPriority ?? 0, values: props.layoutValue ?? {} };\n });\n}\n\ninterface LayoutRecord {\n proposal: LayoutProposal;\n children: LayoutChildMeasurement[];\n}\n\nconst fromDimension = (value: Dimension | null): number | null => (value === 'infinity' ? Infinity : value);\nconst toDimension = (value: number): Dimension => (Number.isFinite(value) ? Math.round(value * 100) / 100 : 'infinity');\nconst toSize = (size: { width: Dimension; height: Dimension }): Size => ({\n width: fromDimension(size.width) ?? 0,\n height: fromDimension(size.height) ?? 0,\n});\n\nconst GUIDES: readonly LayoutGuide[] = ['leading', 'horizontalCenter', 'trailing', 'top', 'verticalCenter', 'bottom', 'firstTextBaseline', 'lastTextBaseline'];\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.min(Math.max(value, min), max);\n}\n\n/** Run the layout for a record: the size, the frames and the min/ideal/max sizes. */\nexport function answerLayout<Cache>(\n layout: CustomLayout<Cache>,\n record: LayoutRecord,\n traits: readonly SubviewTraits[] = [],\n): {\n size: Size;\n frames: Rect[];\n sizes: { min: Size; ideal: Size; max: Size; atWidth?: Size };\n guides: Partial<Record<LayoutGuide, number>>;\n} {\n const frames: (Rect | null)[] = record.children.map(() => null);\n const subviews: LayoutSubview[] = record.children.map((measurement, index) => {\n const min = toSize(measurement.min);\n const ideal = toSize(measurement.ideal);\n const max = toSize(measurement.max);\n const sizeThatFits = (proposal: LayoutProposal): Size => ({\n width: proposal.width === null ? ideal.width : clamp(proposal.width, min.width, max.width),\n height: proposal.height === null ? ideal.height : clamp(proposal.height, min.height, max.height),\n });\n return {\n min,\n ideal,\n max,\n priority: traits[index]?.priority ?? 0,\n values: traits[index]?.values ?? {},\n spacing: DEFAULT_VIEW_SPACING,\n sizeThatFits,\n place: ({ x, y, anchor, proposal }) => {\n const size = sizeThatFits(proposal ?? { width: null, height: null });\n const point = unitPoint(anchor ?? 'topLeading');\n frames[index] = { x: x - point.x * size.width, y: y - point.y * size.height, ...size };\n },\n };\n });\n const cache = (layout.makeCache ? layout.makeCache(subviews) : undefined) as Cache;\n const measure = (proposal: LayoutProposal): Size => layout.sizeThatFits(proposal, subviews, cache);\n const size = measure(record.proposal);\n layout.placeSubviews({ x: 0, y: 0, ...size }, record.proposal, subviews, cache);\n const placed = frames.map((frame, index) => {\n if (frame) return frame;\n // An unplaced subview sits centered, as in SwiftUI.\n const own = subviews[index]!.sizeThatFits({ width: size.width, height: size.height });\n return { x: (size.width - own.width) / 2, y: (size.height - own.height) / 2, ...own };\n });\n const guides: Partial<Record<LayoutGuide, number>> = {};\n if (layout.explicitAlignment) {\n const bounds = { x: 0, y: 0, ...size };\n for (const guide of GUIDES) {\n const value = layout.explicitAlignment(guide, bounds, record.proposal, subviews, cache);\n if (value !== null && value !== undefined && Number.isFinite(value)) guides[guide] = value;\n }\n }\n const sizes: { min: Size; ideal: Size; max: Size; atWidth?: Size } = {\n min: measure({ width: 0, height: 0 }),\n ideal: measure({ width: null, height: null }),\n max: measure({ width: Infinity, height: Infinity }),\n };\n // The size at the answered width with no height: what a grid or stack\n // measuring the layout at the width it has asks (the Swift core sends the\n // same, docs/ops-protocol.md \"`layout` (custom `Layout`)\").\n const { width, height } = record.proposal;\n if (width !== null && Number.isFinite(width) && height !== null) sizes.atWidth = measure({ width, height: null });\n return { size, frames: placed, guides, sizes };\n}\n\n/**\n * `Layout`: a custom layout the engine asks for sizes and frames. Until the\n * first answer the element fills its proposal; then it answers from the\n * layout's own `sizeThatFits` and `placeSubviews`.\n */\nexport function Layout<Cache = unknown>(props: LayoutProps<Cache>): ReactNode {\n const { own, modifiers } = splitProps(props);\n const [record, setRecord] = useState<LayoutRecord | null>(null);\n let layoutProps: Record<string, unknown> = { proposal: null, size: null, frames: null };\n // The explicit guides the last answer gave, as alignment guides of the layout's box.\n const guideModifiers: [ModifierKey, unknown][] = [];\n if (record) {\n const answer = answerLayout(own.layout, record, subviewTraits(own.children));\n for (const [guide, value] of Object.entries(answer.guides)) guideModifiers.push(['alignmentGuide', { guide, value: () => value }]);\n const encode = (size: Size): { width: Dimension; height: Dimension } => ({ width: toDimension(size.width), height: toDimension(size.height) });\n const round = (value: number): number => Math.round(value * 100) / 100;\n layoutProps = {\n proposal: {\n width: record.proposal.width === null ? null : toDimension(record.proposal.width),\n height: record.proposal.height === null ? null : toDimension(record.proposal.height),\n },\n size: { width: round(answer.size.width), height: round(answer.size.height) },\n frames: answer.frames.map((frame) => ({ x: round(frame.x), y: round(frame.y), width: round(frame.width), height: round(frame.height) })),\n sizes: {\n min: encode(answer.sizes.min),\n ideal: encode(answer.sizes.ideal),\n max: encode(answer.sizes.max),\n ...(answer.sizes.atWidth ? { atWidth: encode(answer.sizes.atWidth) } : {}),\n },\n };\n }\n return applyModifiers(\n sb(\n 'layout',\n layoutProps,\n {\n layout: (event) => {\n const proposal: ProtocolProposal = event.proposal;\n setRecord({\n proposal: { width: fromDimension(proposal.width), height: fromDimension(proposal.height) },\n children: event.children,\n });\n },\n },\n own.children,\n ),\n [...guideModifiers, ...modifiers],\n );\n}\n","/**\n * `.visualEffect { content, proxy in … }` and `.scrollTransition { content, phase in … }`.\n *\n * Both draw effects that depend on where the view is, without changing its\n * layout. A visual effect's view is wrapped in a layout-transparent box that\n * reports its frame on screen (and the visible rectangle of the scroll view\n * it is in), kept current as the page scrolls; the effects apply inside that\n * box, so they never move what is measured. A scroll transition's three\n * phases go to the renderer, which draws them as the view scrolls.\n */\n\nimport type { Rotation3D, ScrollTransition, ScrollTransitionEffect, Style } from '@swiftbrowser/web/src/protocol';\nimport { useEffect, useState, type ReactNode } from 'react';\nimport { useCoordinateSpaces } from './coordinateSpace';\nimport { geometryProxy, nextGeometry, NO_GEOMETRY, type GeometryProxy, type ReportedGeometry } from './components/geometry';\nimport { sb } from './host/sb';\nimport { unitPoint, type UnitPoint, type UnitPointValue } from './values';\n\ninterface EffectValues {\n offsetX: number;\n offsetY: number;\n scaleX: number;\n scaleY: number;\n scaleAnchor?: UnitPoint;\n rotation: number;\n rotationAnchor?: UnitPoint;\n rotation3D?: Rotation3D;\n opacity: number;\n blur: number;\n brightness: number;\n contrast: number;\n saturation: number;\n grayscale: number;\n hueRotation: number;\n}\n\nconst IDENTITY: EffectValues = {\n offsetX: 0,\n offsetY: 0,\n scaleX: 1,\n scaleY: 1,\n rotation: 0,\n opacity: 1,\n blur: 0,\n brightness: 0,\n contrast: 1,\n saturation: 1,\n grayscale: 0,\n hueRotation: 0,\n};\n\n/**\n * SwiftUI's `VisualEffect`: the effects a `visualEffect` or `scrollTransition`\n * closure returns, chained from the `effect` it is handed\n * (`effect.offset({ y: 20 }).opacity(0.5)`). Chained effects compose:\n * offsets and rotations add, scales and opacities multiply.\n */\nexport class VisualEffect {\n /** @internal */\n constructor(readonly values: EffectValues = IDENTITY) {}\n\n private with(patch: Partial<EffectValues>): VisualEffect {\n return new VisualEffect({ ...this.values, ...patch });\n }\n\n offset(offset: { x?: number; y?: number }): VisualEffect {\n return this.with({ offsetX: this.values.offsetX + (offset.x ?? 0), offsetY: this.values.offsetY + (offset.y ?? 0) });\n }\n\n scaleEffect(scale: number | { x?: number; y?: number }, anchor?: UnitPointValue): VisualEffect {\n const x = typeof scale === 'number' ? scale : (scale.x ?? 1);\n const y = typeof scale === 'number' ? scale : (scale.y ?? 1);\n return this.with({ scaleX: this.values.scaleX * x, scaleY: this.values.scaleY * y, ...(anchor !== undefined ? { scaleAnchor: unitPoint(anchor) } : {}) });\n }\n\n /** Degrees. */\n rotationEffect(degrees: number, anchor?: UnitPointValue): VisualEffect {\n return this.with({ rotation: this.values.rotation + degrees, ...(anchor !== undefined ? { rotationAnchor: unitPoint(anchor) } : {}) });\n }\n\n rotation3DEffect(spec: { angle: number; axis: { x: number; y: number; z: number }; anchor?: UnitPointValue; perspective?: number }): VisualEffect {\n const rotation: Rotation3D = { angle: spec.angle, axis: spec.axis };\n if (spec.anchor !== undefined) rotation.anchor = unitPoint(spec.anchor);\n if (spec.perspective !== undefined) rotation.perspective = spec.perspective;\n return this.with({ rotation3D: rotation });\n }\n\n opacity(opacity: number): VisualEffect {\n return this.with({ opacity: this.values.opacity * opacity });\n }\n\n blur(radius: number): VisualEffect {\n return this.with({ blur: this.values.blur + radius });\n }\n\n brightness(amount: number): VisualEffect {\n return this.with({ brightness: this.values.brightness + amount });\n }\n\n contrast(amount: number): VisualEffect {\n return this.with({ contrast: this.values.contrast * amount });\n }\n\n saturation(amount: number): VisualEffect {\n return this.with({ saturation: this.values.saturation * amount });\n }\n\n grayscale(amount: number): VisualEffect {\n return this.with({ grayscale: Math.min(1, this.values.grayscale + amount) });\n }\n\n /** Degrees. */\n hueRotation(degrees: number): VisualEffect {\n return this.with({ hueRotation: this.values.hueRotation + degrees });\n }\n}\n\n/** The effect a closure starts from. */\nexport const EMPTY_EFFECT = new VisualEffect();\n\nconst round = (value: number): number => Math.round(value * 1000) / 1000;\n\n/** The `styled` style that draws `values` (identity fields left out). */\nexport function effectStyle(values: EffectValues): Style {\n const style: Style = {};\n if (values.offsetX !== 0 || values.offsetY !== 0) style.offset = { x: round(values.offsetX), y: round(values.offsetY) };\n if (values.scaleX !== 1 || values.scaleY !== 1) {\n style.scale = { x: round(values.scaleX), y: round(values.scaleY) };\n if (values.scaleAnchor) style.scaleAnchor = values.scaleAnchor;\n }\n if (values.rotation !== 0) {\n style.rotation = round(values.rotation);\n if (values.rotationAnchor) style.rotationAnchor = values.rotationAnchor;\n }\n if (values.rotation3D && values.rotation3D.angle !== 0) style.rotation3D = { ...values.rotation3D, angle: round(values.rotation3D.angle) };\n if (values.opacity !== 1) style.opacity = round(values.opacity);\n if (values.blur !== 0) style.blur = round(values.blur);\n if (values.brightness !== 0) style.brightness = round(values.brightness);\n if (values.contrast !== 1) style.contrast = round(values.contrast);\n if (values.saturation !== 1) style.saturation = round(values.saturation);\n if (values.grayscale !== 0) style.grayscale = round(values.grayscale);\n if (values.hueRotation !== 0) style.hueRotation = round(values.hueRotation);\n return style;\n}\n\n// ---------------------------------------------------------------------------\n// The measured box\n// ---------------------------------------------------------------------------\n\n/**\n * Renders `children` styled by `style(reported, markRead)` inside a box that\n * reports its geometry; the frame on screen is asked for once `markRead` is\n * called.\n */\nfunction EffectBox({ render, children }: { render: (reported: ReportedGeometry, markRead: () => void) => Style; children?: ReactNode }): ReactNode {\n const [reported, setReported] = useState<ReportedGeometry>(NO_GEOMETRY);\n const [needsFrame, setNeedsFrame] = useState(false);\n let readFrame = false;\n const style = render(reported, () => {\n readFrame = true;\n });\n useEffect(() => {\n if (readFrame && !needsFrame) setNeedsFrame(true);\n });\n const content = Object.keys(style).length > 0 ? sb('styled', { style }, undefined, children) : children;\n return sb(\n 'zstack',\n { alignment: 'center', reportsSize: true, ...(needsFrame ? { reportsFrame: true } : {}) },\n {\n geometry: (event) => {\n const next = nextGeometry(event, reported);\n if (JSON.stringify(next) !== JSON.stringify(reported)) setReported(next);\n },\n },\n content,\n );\n}\n\nexport type VisualEffectClosure = (effect: VisualEffect, proxy: GeometryProxy) => VisualEffect;\n\n/** `.visualEffect { content, proxy in … }`. */\nexport function VisualEffectView({ effect, children }: { effect: VisualEffectClosure; children?: ReactNode }): ReactNode {\n const spaces = useCoordinateSpaces();\n return <EffectBox render={(reported, markRead) => effectStyle(effect(EMPTY_EFFECT, geometryProxy(reported, spaces, markRead)).values)}>{children}</EffectBox>;\n}\n\n// ---------------------------------------------------------------------------\n// Scroll transitions\n// ---------------------------------------------------------------------------\n\n/**\n * Where a view is in its scroll view: `topLeading` (going out past the top or\n * leading edge), `identity` (in view) or `bottomTrailing`, with `value` -1, 0\n * or 1. An `interactive` transition draws the effect partway between phases\n * as the view crosses the edge.\n */\nexport interface ScrollTransitionPhase {\n phase: 'topLeading' | 'identity' | 'bottomTrailing';\n value: -1 | 0 | 1;\n isIdentity: boolean;\n}\n\nconst PHASES = {\n topLeading: { phase: 'topLeading', value: -1, isIdentity: false },\n identity: { phase: 'identity', value: 0, isIdentity: true },\n bottomTrailing: { phase: 'bottomTrailing', value: 1, isIdentity: false },\n} as const satisfies Record<string, ScrollTransitionPhase>;\n\nexport type ScrollTransitionClosure = (effect: VisualEffect, phase: ScrollTransitionPhase) => VisualEffect;\n\nexport interface ScrollTransitionSpec {\n transition: ScrollTransitionClosure;\n /**\n * `interactive` (the default) follows the scrolling, drawing the effect\n * partway as the view crosses the edge; `animated` switches phases once the\n * view is partly out; `identity` never leaves the identity phase.\n */\n configuration?: 'interactive' | 'animated' | 'identity';\n /** The axis to follow; the scroll view's own by default. */\n axis?: 'horizontal' | 'vertical';\n}\n\n/**\n * `.scrollTransition { content, phase in … }`: the closure called once for\n * each phase, and the three effects handed to the renderer, which draws them\n * as the view scrolls (between phases by how far out it is, for\n * `interactive`) without asking the app on every step.\n */\nexport function ScrollTransitionView({ spec, children }: { spec: ScrollTransitionSpec; children?: ReactNode }): ReactNode {\n const phase = (which: keyof typeof PHASES): ScrollTransitionEffect => effectStyle(spec.transition(EMPTY_EFFECT, PHASES[which]).values);\n const transition: ScrollTransition = {\n configuration: spec.configuration ?? 'interactive',\n identity: phase('identity'),\n topLeading: phase('topLeading'),\n bottomTrailing: phase('bottomTrailing'),\n };\n if (spec.axis) transition.axis = spec.axis;\n return sb('styled', { style: { scrollTransition: transition } }, undefined, children);\n}\n","/**\n * Modifiers for a page with a mouse and a keyboard, and the effects the\n * renderer draws for them: hover, tooltips, cursors, keyboard shortcuts,\n * key presses, symbol effects, matched geometry, haptics.\n */\n\nimport type { SymbolEffectStyle } from '@swiftbrowser/web/src/protocol';\nimport { useEffect, useId, useRef, type ReactNode } from 'react';\nimport { useCoordinateSpaces } from './coordinateSpace';\nimport { sb } from './host/sb';\nimport { styled, type ContinuousHoverModifier } from './modifiers';\n\nexport function Hover({ action, children }: { action: (hovering: boolean) => void; children?: ReactNode }): ReactNode {\n return sb('styled', { style: { hover: true } }, { hover: (event) => action(event.value) }, children);\n}\n\n/**\n * `.onContinuousHover(coordinateSpace:perform:)`: the box sends where the\n * mouse is as it moves (one event per frame) and that it left. `local` and\n * `global` are the renderer's; a named space is the global point less the\n * frame `coordinateSpace` reported for that name, as a drag's is.\n */\nexport function ContinuousHover({ spec, children }: { spec: ContinuousHoverModifier; children?: ReactNode }): ReactNode {\n const spaces = useCoordinateSpaces();\n const space = spec.coordinateSpace ?? 'local';\n const named = typeof space === 'object' ? spaces[space.named] : null;\n const inSpace = (point: { x: number; y: number }): { x: number; y: number } => (named ? { x: point.x - named.x, y: point.y - named.y } : point);\n return sb(\n 'styled',\n { style: { continuousHover: space === 'local' ? 'local' : 'global' } },\n { continuoushover: (event) => spec.action(event.phase === 'active' ? { kind: 'active', location: inSpace(event.location) } : { kind: 'ended' }) },\n children,\n );\n}\n\nconst CURSORS: Record<string, string> = {\n link: 'pointer',\n automatic: 'auto',\n default: 'default',\n text: 'text',\n verticalText: 'vertical-text',\n grabIdle: 'grab',\n grabActive: 'grabbing',\n rectSelection: 'crosshair',\n columnResize: 'col-resize',\n rowResize: 'row-resize',\n};\n\nexport function cursorFor(style: string): string {\n return CURSORS[style] ?? style;\n}\n\n// ---------------------------------------------------------------------------\n// Symbol effects\n// ---------------------------------------------------------------------------\n\nexport interface SymbolEffectModifier {\n effect: SymbolEffectStyle['effect'];\n direction?: 'up' | 'down';\n speed?: number;\n repeat?: number | 'forever';\n /** `.symbolEffect(_:isActive:)`: the effect runs while true (true by default). */\n isActive?: boolean;\n /** `.symbolEffect(_:value:)`: the effect plays once each time this changes. */\n value?: unknown;\n}\n\nexport function SymbolEffect({ spec, children }: { spec: SymbolEffectModifier; children?: ReactNode }): ReactNode {\n const serial = useRef<{ value: unknown; count: number } | null>(null);\n const discrete = 'value' in spec;\n if (discrete) {\n if (!serial.current) serial.current = { value: spec.value, count: 0 };\n else if (!Object.is(serial.current.value, spec.value)) serial.current = { value: spec.value, count: serial.current.count + 1 };\n }\n if (!discrete && spec.isActive === false) return children;\n const effect: SymbolEffectStyle = { effect: spec.effect };\n if (spec.direction) effect.direction = spec.direction;\n if (spec.speed !== undefined) effect.speed = spec.speed;\n if (spec.repeat !== undefined) effect.repeat = spec.repeat;\n if (discrete) effect.trigger = serial.current!.count;\n return styled({ symbolEffect: effect }, children);\n}\n\n// ---------------------------------------------------------------------------\n// Matched geometry\n// ---------------------------------------------------------------------------\n\n/** `@Namespace`: a namespace for `matchedGeometryEffect` ids. */\nexport function useNamespace(): string {\n return useId();\n}\n\n// ---------------------------------------------------------------------------\n// Keyboard\n// ---------------------------------------------------------------------------\n\nexport type KeyEquivalent = 'return' | 'escape' | 'delete' | 'tab' | 'space' | 'upArrow' | 'downArrow' | 'leftArrow' | 'rightArrow' | (string & {});\nexport type EventModifier = 'command' | 'shift' | 'option' | 'control';\n\nexport interface KeyboardShortcut {\n key: KeyEquivalent;\n /** `command` by default, as SwiftUI's; `[]` for none. `command` is Ctrl off Apple platforms. */\n modifiers?: EventModifier[];\n}\n\nconst KEY_NAMES: Record<string, string> = {\n return: 'Enter',\n escape: 'Escape',\n delete: 'Backspace',\n tab: 'Tab',\n space: ' ',\n upArrow: 'ArrowUp',\n downArrow: 'ArrowDown',\n leftArrow: 'ArrowLeft',\n rightArrow: 'ArrowRight',\n};\n\nconst isApple = (): boolean => typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent);\n\nexport function matchesKey(event: KeyboardEvent, key: KeyEquivalent): boolean {\n const name = KEY_NAMES[key] ?? key;\n return name.length === 1 ? event.key.toLowerCase() === name.toLowerCase() : event.key === name;\n}\n\nfunction matchesShortcut(event: KeyboardEvent, shortcut: KeyboardShortcut): boolean {\n if (!matchesKey(event, shortcut.key)) return false;\n const wanted = new Set(shortcut.modifiers ?? ['command']);\n const command = isApple() ? event.metaKey : event.ctrlKey;\n const control = isApple() ? event.ctrlKey : false;\n return (\n command === wanted.has('command') &&\n event.shiftKey === wanted.has('shift') &&\n event.altKey === wanted.has('option') &&\n control === (isApple() && wanted.has('control'))\n );\n}\n\n/** A shortcut that runs `action` while the component is mounted. */\nexport function useKeyboardShortcut(shortcut: KeyboardShortcut | undefined, action: () => void): void {\n const latest = useRef(action);\n latest.current = action;\n const key = shortcut ? `${shortcut.key}:${(shortcut.modifiers ?? ['command']).join('+')}` : '';\n useEffect(() => {\n if (!shortcut || typeof document === 'undefined') return;\n const onKey = (event: KeyboardEvent): void => {\n if (event.defaultPrevented || !matchesShortcut(event, shortcut)) return;\n event.preventDefault();\n latest.current();\n };\n document.addEventListener('keydown', onKey);\n return () => document.removeEventListener('keydown', onKey);\n }, [key]);\n}\n\nexport interface KeyPress {\n key: string;\n characters: string;\n modifiers: EventModifier[];\n phase: 'down' | 'repeat';\n}\n\nexport interface OnKeyPressModifier {\n /** Only these keys (`KeyEquivalent`s or characters); every key when absent. */\n keys?: KeyEquivalent[];\n /** Return `'handled'` to stop the key there. */\n action: (press: KeyPress) => 'handled' | 'ignored' | void;\n}\n\n/**\n * `.onKeyPress`: keys pressed while the view is on screen and no text field\n * has the focus (the page has no focus for a plain view, so the screen\n * stands in for it).\n */\nexport function KeyPressListener({ spec }: { spec: OnKeyPressModifier }): null {\n const latest = useRef(spec);\n latest.current = spec;\n useEffect(() => {\n if (typeof document === 'undefined') return;\n const onKey = (event: KeyboardEvent): void => {\n const target = event.target as HTMLElement | null;\n if (event.defaultPrevented || target?.closest('input, textarea, [contenteditable]')) return;\n const { keys, action } = latest.current;\n if (keys && !keys.some((key) => matchesKey(event, key))) return;\n const modifiers: EventModifier[] = [];\n if (event.metaKey) modifiers.push('command');\n if (event.shiftKey) modifiers.push('shift');\n if (event.altKey) modifiers.push('option');\n if (event.ctrlKey) modifiers.push('control');\n const result = action({ key: event.key, characters: event.key.length === 1 ? event.key : '', modifiers, phase: event.repeat ? 'repeat' : 'down' });\n if (result === 'handled') event.preventDefault();\n };\n document.addEventListener('keydown', onKey);\n return () => document.removeEventListener('keydown', onKey);\n }, []);\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Sensory feedback\n// ---------------------------------------------------------------------------\n\nexport type SensoryFeedback = 'success' | 'warning' | 'error' | 'selection' | 'increase' | 'decrease' | 'start' | 'stop' | 'alignment' | 'levelChange' | 'impact';\n\nconst PATTERNS: Record<SensoryFeedback, number | number[]> = {\n success: [12, 60, 18],\n warning: [18, 80, 18],\n error: [24, 50, 24, 50, 24],\n selection: 8,\n increase: 10,\n decrease: 10,\n start: 14,\n stop: 14,\n alignment: 6,\n levelChange: 10,\n impact: 16,\n};\n\n/** `.sensoryFeedback(_:trigger:)`: a vibration where the browser and device have one (Android), nothing elsewhere. */\nexport function SensoryFeedbackPlayer({ feedback, trigger }: { feedback: SensoryFeedback; trigger: unknown }): null {\n const first = useRef(true);\n useEffect(() => {\n if (first.current) {\n first.current = false;\n return;\n }\n if (typeof navigator !== 'undefined' && typeof navigator.vibrate === 'function') navigator.vibrate(PATTERNS[feedback]);\n }, [trigger, feedback]);\n return null;\n}\n","/**\n * View modifiers as props. Every component accepts them, and applies them in\n * the order they are written, innermost first, exactly like a SwiftUI\n * modifier chain reads: `<Text padding background=\"red\" />` is\n * `Text().padding().background(.red)`. Each modifier that changes layout or\n * style wraps the view in a `styled` element, as the Swift shim does; the\n * environment ones wrap it in a context; the navigation and presentation ones\n * attach preferences and hoisted elements beside it.\n */\n\nimport type {\n Animation,\n ButtonStyle,\n EdgeInsets,\n FixedSize,\n FontWeight,\n FrameAlignment,\n GestureMode,\n DragPhase,\n TouchPoint as ProtocolTouchPoint,\n ImageScale,\n PickerStyle,\n ToggleStyle,\n Style,\n TextAlignment,\n ToolbarPlacement,\n Transition,\n} from '@swiftbrowser/web/src/protocol';\nimport { Children, Fragment, cloneElement, createElement, isValidElement, useRef, type ReactElement, type ReactNode } from 'react';\nimport type { BindingValue } from './binding';\nimport { readBinding } from './binding';\nimport { useViewEnvironment, withEnvironment, type ControlSize, type KeyboardType, type SymbolRenderingMode, type TextContentType, type TextInputHints, type ViewEnvironment } from './environment';\nimport { Draggable, DropDestination } from './dragDrop';\nimport { FileImporterPresenter, type FileImporterModifier } from './fileImporter';\nimport { FileExporterPresenter, type FileExporterModifier } from './fileExporter';\nimport { Inspector } from './inspector';\nimport { OnChange, Task } from './lifecycle';\nimport { ScrollTarget } from './scrollReader';\nimport { CoordinateSpace, useCoordinateSpaces } from './coordinateSpace';\nimport {\n edgeHiddenSettings,\n edgeStyleSettings,\n marginSettings,\n withScrollSettings,\n type ContentMarginsValue,\n type ScrollEdgeEffectHiddenValue,\n type ScrollEdgeEffectStyleValue,\n} from './scrollEnvironment';\nimport { ScrollTransitionView, VisualEffectView, type ScrollTransitionClosure, type ScrollTransitionSpec, type VisualEffectClosure } from './visualEffect';\nimport { GeometryChangeView, type GeometryChangeHandler } from './components/geometry';\nimport {\n ContinuousHover,\n Hover,\n KeyPressListener,\n SensoryFeedbackPlayer,\n SymbolEffect,\n cursorFor,\n type KeyEquivalent,\n type KeyboardShortcut,\n type OnKeyPressModifier,\n type SensoryFeedback,\n type SymbolEffectModifier,\n} from './pointer';\nimport { HOIST_KIND, PREF_KIND } from './host/instance';\nimport { INHERITED_STYLE_KEYS, InheritStyle, PRESENTATION_KEYS, styleOf } from './inheritedStyle';\nimport { sb } from './host/sb';\nimport { RegisterDestination } from './navigation-context';\nimport {\n AlertPresenter,\n Lifecycle,\n SheetPresenter,\n presentationDetents,\n type AlertModifier,\n type DetentValue,\n type SheetModifier,\n} from './presentation';\nimport {\n color,\n font,\n frame,\n padding,\n rgb,\n shapeStyle,\n unitPoint,\n type ColorValue,\n type UnitPointValue,\n type FontValue,\n type FrameValue,\n type PaddingValue,\n type StyleValue,\n} from './values';\n\n/** A shape component carries its protocol kind; `RoundedRectangle` reads the radius from its props. */\nexport interface ShapeSpec {\n kind: string;\n cornerRadius: number | null;\n}\n\n/** `.background(style, in: shape)` */\nexport interface BackgroundInShape {\n fill: StyleValue;\n in: ReactElement;\n}\n\nexport type BackgroundValue = StyleValue | BackgroundInShape | ReactElement;\n\nexport interface SearchableModifier {\n text: BindingValue<string>;\n onChange?: (text: string) => void;\n prompt?: string;\n}\n\n/** `CoordinateSpace`: a view's own, the screen's, or one named with `coordinateSpace` on an ancestor. */\nexport type CoordinateSpaceValue = 'local' | 'global' | { named: string };\n\n/** `DragGesture.Value`: the renderer's drag event, its points in the gesture's `coordinateSpace` (the view's own by default). */\nexport interface DragValue {\n translation: { width: number; height: number };\n location: { x: number; y: number };\n startLocation: { x: number; y: number };\n velocity: { width: number; height: number };\n}\n\n/** `HoverPhase`: where a mouse is over the view, or that it left. */\nexport type HoverPhase = { kind: 'active'; location: { x: number; y: number } } | { kind: 'ended' };\n\n/** `.onContinuousHover(coordinateSpace:perform:)` with a space other than the view's own. */\nexport interface ContinuousHoverModifier {\n /** The space of an `active` phase's `location`: the view's own by default; `global` or a `{ named }` space stays put as the view moves. */\n coordinateSpace?: CoordinateSpaceValue;\n action: (phase: HoverPhase) => void;\n}\n\nexport interface DragGestureModifier {\n minimumDistance?: number;\n /**\n * `DragGesture(coordinateSpace:)`: the space of `location` and\n * `startLocation`. `local` (the default) moves with the view when the drag\n * moves it; `global` or a `{ named }` space stays put, as a canvas needs.\n */\n coordinateSpace?: CoordinateSpaceValue;\n onChanged?: (value: DragValue) => void;\n onEnded?: (value: DragValue) => void;\n}\n\n/** `.onTapGesture(count:perform:)`: `count` taps (1 by default; 2 is a double tap) run `action`. */\n/** `{ count, action }`, or `{ count, perform }` to hear where the tap landed (`location` on the `tapgesture`). */\nexport type TapGestureModifier = { count?: number; action: () => void } | { count?: number; perform: (location: { x: number; y: number }) => void };\n\n/**\n * The gesture `.simultaneousGesture` or `.highPriorityGesture` takes, as the\n * gesture modifier it would otherwise be: `{ dragGesture: { … } }`,\n * `{ magnifyGesture: { … } }`, `{ rotateGesture: { … } }` or\n * `{ onLongPressGesture: … }`.\n */\nexport type GestureValue = Pick<ViewModifiers, 'dragGesture' | 'magnifyGesture' | 'rotateGesture' | 'onLongPressGesture'>;\n\n/** One pointer on a view with `onTouches`: a stable `id` while it is down and its point in the view's coordinates. */\nexport type TouchPoint = ProtocolTouchPoint;\n/** What changed in an `onTouches` call: `began`, `changed`, `ended` or `cancelled`. */\nexport type TouchesPhase = DragPhase;\nexport type TouchesHandler = (touches: TouchPoint[], phase: TouchesPhase) => void;\n\n/** `MagnifyGesture.Value` / `RotateGesture.Value`: the renderer's pinch event. */\nexport interface PinchValue {\n /** The scale since the gesture began (1 at the start). */\n magnification: number;\n /** The turn since the gesture began, in degrees, clockwise positive. */\n rotation: number;\n /** Per second. */\n magnificationVelocity: number;\n rotationVelocity: number;\n startLocation: { x: number; y: number };\n startAnchor: { x: number; y: number };\n /**\n * Where the fingers' midpoint is now (not in SwiftUI's values): with\n * `startLocation`, two fingers pan as they zoom. `startLocation` where the\n * renderer cannot tell.\n */\n location: { x: number; y: number };\n}\n\nexport interface MagnifyGestureModifier {\n minimumScaleDelta?: number;\n onChanged?: (value: PinchValue) => void;\n onEnded?: (value: PinchValue) => void;\n}\n\nexport interface RotateGestureModifier {\n /** Degrees. */\n minimumAngleDelta?: number;\n onChanged?: (value: PinchValue) => void;\n onEnded?: (value: PinchValue) => void;\n}\n\nexport interface SwipeActionsModifier {\n edge?: 'leading' | 'trailing';\n allowsFullSwipe?: boolean;\n /** The actions: `Button`s (a `tint` colors one, a `destructive` role makes it red). */\n children: ReactNode;\n}\n\nexport type ToolbarItemPlacementName =\n | 'automatic'\n | 'topBarLeading'\n | 'topBarTrailing'\n | 'navigationBarLeading'\n | 'navigationBarTrailing'\n | 'cancellationAction'\n | 'confirmationAction'\n | 'destructiveAction'\n | 'primaryAction'\n | 'navigation'\n | 'principal'\n | 'largeTitle'\n | 'bottomBar'\n | 'secondaryAction'\n | 'keyboard';\n\n/** `.toolbar(_:for:)`: `automatic` leaves a bar as it is. */\nexport type Visibility = 'automatic' | 'visible' | 'hidden';\n/** `.toolbarRole(_:)`: `editor` shows a regular-width screen's secondary actions in its bar. */\nexport type ToolbarRole = 'automatic' | 'navigationStack' | 'browser' | 'editor';\n\nexport function toolbarPlacement(name: ToolbarItemPlacementName | undefined): ToolbarPlacement {\n switch (name) {\n case 'topBarLeading':\n case 'navigationBarLeading':\n case 'cancellationAction':\n case 'navigation':\n return 'leading';\n case 'principal':\n return 'principal';\n case 'largeTitle':\n // iOS 26: in the large title row in place of the title's text.\n return 'largeTitle';\n case 'bottomBar':\n return 'bottom';\n case 'keyboard':\n // A bar above the keyboard while a text input of the screen is focused.\n return 'keyboard';\n case 'secondaryAction':\n // Collapsed into the bar's More menu (inline for an editor role in a regular width).\n return 'secondary';\n default:\n return 'trailing';\n }\n}\n\n/**\n * `.foregroundStyle(primary, secondary[, tertiary])`: the first paints, the\n * others are the `.secondary` and `.tertiary` levels below (a palette symbol's\n * other layers).\n */\nexport type ForegroundLayers = readonly [StyleValue, StyleValue] | readonly [StyleValue, StyleValue, StyleValue];\n\nexport interface ViewModifiers {\n padding?: PaddingValue;\n font?: FontValue;\n fontWeight?: FontWeight;\n bold?: boolean;\n /** `.monospacedDigit()`: digits of one width in the text inside. */\n monospacedDigit?: boolean;\n /** A style, or `[primary, secondary(, tertiary)]` (`.foregroundStyle(.white, .indigo)`). */\n foregroundStyle?: StyleValue | ForegroundLayers;\n background?: BackgroundValue;\n overlay?: ReactElement | { content: ReactElement; alignment?: FrameAlignment };\n frame?: FrameValue;\n cornerRadius?: number;\n clipShape?: ReactElement;\n clipped?: boolean;\n /**\n * `.compositingGroup()`: drawn as one layer before the effects around it, so a `shadow` after it (or around it) is\n * cast by the view as a whole, not by each view inside it, as SwiftUI's `.shadow` on a container otherwise is.\n */\n compositingGroup?: boolean;\n opacity?: number;\n disabled?: boolean;\n hidden?: boolean;\n layoutPriority?: number;\n /** A count, `null` to lift a limit, or a range `[min, max]` (`.lineLimit(2...4)`; `max` null for `2...`). */\n lineLimit?: number | null | readonly [number, number | null];\n multilineTextAlignment?: TextAlignment;\n fixedSize?: boolean | FixedSize;\n offset?: { x?: number; y?: number };\n /** Degrees, clockwise; `{ degrees, anchor }` turns around another point. */\n rotationEffect?: number | { degrees: number; anchor?: UnitPointValue };\n scaleEffect?: number | { x: number; y: number; anchor?: UnitPointValue };\n shadow?: { color?: ColorValue; radius: number; x?: number; y?: number };\n tint?: ColorValue;\n badge?: string | number | null;\n listRowInsets?: EdgeInsets;\n /** `.listRowBackground(_:)`: the row's background in a list, in place of the cell color. */\n listRowBackground?: ColorValue;\n imageScale?: ImageScale;\n /** `.symbolRenderingMode(_:)`: the mode the images below (or this image) draw their symbols in. */\n symbolRenderingMode?: SymbolRenderingMode;\n transition?: Transition;\n /** `.animation(_:value:)`: animate this subtree's changes whenever `value` changes. */\n animation?: { animation?: Animation; value: unknown };\n gridColumnAlignment?: 'leading' | 'center' | 'trailing';\n gridCellColumns?: number;\n // Environment\n buttonStyle?: ButtonStyle;\n controlSize?: ControlSize;\n pickerStyle?: PickerStyle;\n /** `.toggleStyle`: how the toggles below draw (`button` is a button tinted while on). */\n toggleStyle?: ToggleStyle;\n labelsHidden?: boolean;\n // Navigation and presentation\n navigationTitle?: string;\n /** `.navigationSubtitle`: a second line under the title in a Mac's unified title bar (after it in a plain one). */\n navigationSubtitle?: string;\n navigationBarTitleDisplayMode?: 'automatic' | 'inline' | 'large';\n /** `.toolbarRole(.editor)`: the screen's secondary actions show inline in a regular width. */\n toolbarRole?: ToolbarRole;\n /**\n * `.toolbarVisibility(_:for:)` (`.toolbar(_:for:)` on iOS 16): hides the\n * screen's navigation bar (with its title, back button and items; the\n * content starts under the status bar) or its bottom bar, or shows one\n * again. Changed in `withAnimation`, the bars fade. The tab bar cannot be\n * hidden yet.\n */\n toolbarVisibility?: Partial<Record<'navigationBar' | 'bottomBar', Visibility>>;\n /** `.statusBarHidden(_:)`: natively the status bar hides with this screen; the page's frame mode hides the one it draws. */\n statusBarHidden?: boolean;\n /** `ToolbarItem` elements. */\n toolbar?: ReactNode;\n searchable?: SearchableModifier;\n navigationDestination?: (value: never) => ReactNode;\n sheet?: SheetModifier;\n fullScreenCover?: SheetModifier;\n alert?: AlertModifier;\n confirmationDialog?: AlertModifier;\n presentationDetents?: DetentValue[];\n // Gestures and lifecycle\n /**\n * `.onScrollVisibilityChange(threshold:_:)`: `action` hears `true` when at\n * least `threshold` (0.5 by default) of the view is inside its scroll\n * view's visible area (below a bar it scrolls under), `false` when it falls\n * below that, and the view's state when it first appears.\n */\n onScrollVisibilityChange?: ((visible: boolean) => void) | { threshold?: number; action: (visible: boolean) => void };\n /**\n * `.onGeometryChange(for:of:action:)`: `{ of, action }` runs `action(value,\n * oldValue)` when `of(proxy)` (the view's size, its frame on screen, its\n * scroll view's bounds) answers differently; a function hears the proxy on\n * every change. The view's layout is untouched.\n */\n onGeometryChange?: GeometryChangeHandler;\n /**\n * `.onTapGesture { }`, or `{ count: 2, action }` for a double tap. A view\n * with both (the double tap first, inside: `onTapGesture={{ count: 2, … }}\n * modifiers={[{ onTapGesture: … }]}`) delays the single tap until a double\n * tap can no longer land, as iOS does. `{ perform(location) }` is\n * `.onTapGesture { location in }`, the point in the view's coordinates.\n */\n onTapGesture?: (() => void) | TapGestureModifier;\n /** `.gesture(DragGesture().onChanged { }.onEnded { })` */\n dragGesture?: DragGestureModifier;\n /** `.gesture(MagnifyGesture().onChanged { }.onEnded { })`: two fingers or a trackpad pinch. */\n magnifyGesture?: MagnifyGestureModifier;\n /** `.gesture(RotateGesture().onChanged { }.onEnded { })` */\n rotateGesture?: RotateGestureModifier;\n /** `.onLongPressGesture { }` */\n onLongPressGesture?: (() => void) | { minimumDuration?: number; action: () => void };\n /**\n * `.onTouches { touches, phase in }`, a SwiftBrowser addition: every pointer\n * down on the view, in its coordinates, for chords and glissandi (a piano,\n * a drum pad). `phase` is `began` (one came down), `changed` (they moved),\n * `ended` (one lifted) or `cancelled` (the renderer lost them all);\n * `touches` is every pointer still down, so the handler reads its state\n * from each call instead of pairing ups with downs. The view owns its\n * pointers: nothing above it scrolls or swipes with them.\n */\n onTouches?: TouchesHandler;\n /**\n * `.simultaneousGesture(_:)`: a gesture that runs beside the view's others\n * and those of the views inside it, instead of competing with them: it\n * begins when its own distance is met and ends when the pointer lifts,\n * whoever else owns the pointer.\n */\n simultaneousGesture?: GestureValue;\n /** `.highPriorityGesture(_:)`: a gesture asked before the gestures of the views inside it. */\n highPriorityGesture?: GestureValue;\n /** `.contextMenu { items }`: a long press or right click opens the items. */\n contextMenu?: ReactNode;\n /** `.swipeActions(edge:allowsFullSwipe:) { buttons }`, on a list row. */\n swipeActions?: SwipeActionsModifier | SwipeActionsModifier[];\n onAppear?: () => void;\n onDisappear?: () => void;\n /** `.tag(_:)`: read by `Picker` options and `TabView` tabs. */\n tag?: unknown;\n /** Extra modifiers in order, for one that must apply twice (`.padding().background().padding()`). */\n modifiers?: ViewModifiers[];\n // Visual effects\n /** `.aspectRatio(_:contentMode:)`: a ratio (width / height), or `{ ratio, contentMode }`; `ratio: null` keeps the view's own. */\n aspectRatio?: number | { ratio?: number | null; contentMode?: 'fit' | 'fill' };\n scaledToFit?: boolean;\n scaledToFill?: boolean;\n blur?: number;\n brightness?: number;\n contrast?: number;\n saturation?: number;\n grayscale?: number;\n /** Degrees. */\n hueRotation?: number;\n colorInvert?: boolean;\n colorMultiply?: ColorValue;\n /** A CSS `mix-blend-mode` name (`multiply`, `screen`, `overlay`…), as `.blendMode` maps them. */\n blendMode?: string;\n /** `.mask(_:)` with a style: the view shows through its alpha (a gradient fades it). */\n mask?: StyleValue;\n /** `.position(x:y:)` */\n position?: { x: number; y: number };\n zIndex?: number;\n /** `.allowsHitTesting(false)` lets taps through to what is under the view. */\n allowsHitTesting?: boolean;\n /**\n * `.contentShape(Rectangle())`: the whole frame takes taps and gestures,\n * what is drawn in it or not (a clear fill, an outline, the gaps in a\n * stack), as SwiftUI hits only what a view draws.\n */\n contentShape?: 'rectangle';\n /** `.ignoresSafeArea()` (`true`), or the edges. */\n ignoresSafeArea?: true | ('top' | 'bottom' | 'leading' | 'trailing')[];\n /** `.rotation3DEffect(_:axis:anchor:perspective:)`, the angle in degrees. */\n rotation3DEffect?: { angle: number; axis: { x: number; y: number; z: number }; anchor?: UnitPointValue; perspective?: number };\n /** `.gridCellAnchor(_:)` */\n gridCellAnchor?: UnitPointValue;\n /**\n * `.alignmentGuide(_:computeValue:)`: moves the view's guide. `value` gets\n * the view's dimensions; it is sampled at three sizes, so it must be linear\n * in them (`d.width + 4`, `d.height / 2`, a constant), as the shim requires.\n */\n alignmentGuide?: { guide: AlignmentGuideName; value: (d: { width: number; height: number }) => number };\n /** `.preferredColorScheme(_:)`: asks the page for that appearance (`null`: the viewer's). */\n preferredColorScheme?: 'light' | 'dark' | null;\n /** `.refreshable { }`: the nearest `List` or `ScrollView` below shows pull to refresh. */\n refreshable?: () => unknown;\n /** `.submitLabel(_:)` for the text fields below: `done`, `go`, `send`, `search`, `next`… */\n submitLabel?: string;\n /** `.keyboardType(_:)` for the text fields below: the on-screen keyboard. */\n keyboardType?: KeyboardType;\n /** `.textContentType(_:)` for the text fields below: what autofill offers. */\n textContentType?: TextContentType | null;\n /** `.textInputAutocapitalization(_:)` for the text fields below. */\n textInputAutocapitalization?: 'never' | 'words' | 'sentences' | 'characters' | null;\n /** `.autocorrectionDisabled()` for the text fields below. */\n autocorrectionDisabled?: boolean;\n /** `.labelStyle(_:)` for the `Label`s below. */\n labelStyle?: 'automatic' | 'titleAndIcon' | 'titleOnly' | 'iconOnly';\n /**\n * `.task { }`: runs when the view appears, cancelled (the signal aborts)\n * when it disappears. `{ id, action }` restarts it when `id` changes.\n */\n task?: ((signal: AbortSignal) => unknown) | { id: unknown; action: (signal: AbortSignal) => unknown };\n /** `.onChange(of:initial:) { old, new in }` */\n onChangeOf?: { value: unknown; action: (oldValue: unknown, newValue: unknown) => void; initial?: boolean };\n /** `.id(_:)` inside a `ScrollViewReader`: the target `proxy.scrollTo` scrolls to. */\n scrollID?: string | number;\n /** `.draggable(_:)`: a long press or a 10 pt drag lifts the view, carrying `payload`. */\n draggable?: unknown;\n /** `.dropDestination(for:)`: takes what is dropped on the view. */\n dropDestination?: DropDestinationModifier;\n /** `.inspector(isPresented:)`: a trailing panel in a regular width, a sheet in a compact one. */\n inspector?: InspectorModifier;\n /** `.onHover { hovering in }`: a mouse entering and leaving the view. */\n onHover?: (hovering: boolean) => void;\n /** `.onContinuousHover { phase in }`: where a mouse is as it moves over the view (`active`, with the location), and that it left (`ended`). */\n onContinuousHover?: ((phase: HoverPhase) => void) | ContinuousHoverModifier;\n /** `.help(_:)`: a tooltip. */\n help?: string;\n /** `.pointerStyle(_:)`: `link`, `text`, `grabIdle`, `grabActive`… or any CSS cursor. */\n pointerStyle?: string;\n /** `.symbolEffect(_:options:isActive:)` / `.symbolEffect(_:options:value:)` */\n symbolEffect?: SymbolEffectModifier;\n /** `.matchedGeometryEffect(id:in:)`: `namespace` from `useNamespace()`. */\n matchedGeometryEffect?: { id: string | number; namespace?: string };\n /** `.layoutValue(key:value:)`: values a custom `Layout` reads from this subview. */\n layoutValue?: Record<string, unknown>;\n /** `.safeAreaInset(edge:spacing:) { content }`: content beside the view, which the view makes room for. */\n safeAreaInset?: { edge: 'top' | 'bottom' | 'leading' | 'trailing'; spacing?: number; alignment?: 'leading' | 'center' | 'trailing' | 'top' | 'bottom'; content: ReactNode };\n /** `.popover(isPresented:)`: presented as a sheet, as on an iPhone. */\n popover?: SheetModifier;\n /** `.fileImporter(isPresented:allowedContentTypes:…)`: the browser's file chooser, opened from a tap. */\n fileImporter?: FileImporterModifier;\n /** `.fileExporter(isPresented:document:contentType:defaultFilename:…)`: a save dialog, a download or the Files app, opened from a tap. */\n fileExporter?: FileExporterModifier;\n /** `.redacted(reason: .placeholder)` (`true`) and `.unredacted()` (`false`). */\n redacted?: boolean;\n /** `.keyboardShortcut(_:modifiers:)` on a `Button`: the shortcut runs its action. */\n keyboardShortcut?: KeyboardShortcut | KeyEquivalent;\n /** `.onKeyPress(keys:action:)` */\n onKeyPress?: OnKeyPressModifier;\n /** `.sensoryFeedback(_:trigger:)` */\n sensoryFeedback?: { feedback: SensoryFeedback; trigger: unknown };\n /** `.textCase(_:)` */\n textCase?: 'uppercase' | 'lowercase' | null;\n /** `.textSelection(_:)`: `enabled` lets the text below be selected (none is otherwise, as on iOS). */\n textSelection?: 'enabled' | 'disabled';\n /** `.coordinateSpace(name:)`: readers inside answer `frame({ named })` relative to this view. */\n coordinateSpace?: string;\n /**\n * `.contentTransition(_:)`: how the texts below change in an animated pass\n * (`numericText` rolls them up, or down when the new number is smaller;\n * `{ numericText: { countsDown } }` fixes the direction; `opacity` and\n * `interpolate` crossfade; `identity` swaps).\n */\n contentTransition?: 'numericText' | 'opacity' | 'interpolate' | 'identity' | { numericText: { countsDown?: boolean } };\n /**\n * `.scrollDisabled(_:)`: the views below do not scroll; a `TextEditor` is\n * as tall as its lines. Natively every scroll view below takes it; the web\n * renderer reads it in text editors.\n */\n scrollDisabled?: boolean;\n /**\n * `.environment(\\.defaultMinListRowHeight, _)`: every list below (this\n * view's own, a sidebar's, an app's drawn through `RemoteTree`) spaces its\n * rows at least this tall, unless the list sets its own `minRowHeight`. A\n * Mac content list's rows are 24 by default; Apple's Mac apps space them\n * like a sidebar's, 32, which one modifier at the top of an app gives every\n * list. A Mac grouped form keeps its form rows (36).\n */\n defaultMinListRowHeight?: number;\n /**\n * `.scrollEdgeEffectStyle(_:for:)` for the scroll views and lists below\n * (and this one): `hard`, `soft` or `automatic` on both edges, or\n * `[\"hard\", \"top\"]` for some.\n */\n scrollEdgeEffectStyle?: ScrollEdgeEffectStyleValue;\n /** `.scrollEdgeEffectHidden(_:for:)`: `true` for both edges, or `[true, \"bottom\"]`. */\n scrollEdgeEffectHidden?: ScrollEdgeEffectHiddenValue;\n /**\n * `.contentMargins(_:_:)`: padding inside the scroll views below (and this\n * one), which their content scrolls under. Takes what `padding` takes.\n */\n contentMargins?: ContentMarginsValue;\n /**\n * `.containerRelativeFrame(_:)`: the view's size along `axes` follows the\n * nearest container (the scroll view's visible area, else the screen):\n * the whole of it, `span` of `count` columns `spacing` apart, or what\n * `length(containerLength, axis)` answers (a linear function of it).\n */\n containerRelativeFrame?: ContainerRelativeFrameValue;\n /**\n * `.visualEffect { content, proxy in … }`: effects (offset, scale,\n * rotation, opacity, blur, color adjustments) computed from the view's\n * geometry, without changing its layout. `proxy.frame('global')` and\n * `proxy.bounds('scrollView')` stay current as the page scrolls.\n */\n visualEffect?: VisualEffectClosure;\n /**\n * `.scrollTransition { content, phase in … }`: effects as the view goes out\n * of its scroll view's visible area and comes back. A closure, or\n * `{ transition, configuration, axis }`.\n */\n scrollTransition?: ScrollTransitionClosure | ScrollTransitionSpec;\n}\n\n/** The axes `containerRelativeFrame` sizes. */\nexport type ContainerAxes = 'horizontal' | 'vertical' | 'both';\n\nexport type ContainerRelativeFrameValue =\n | ContainerAxes\n | {\n axes: ContainerAxes;\n /** `count:span:spacing:`: `span` of `count` equal columns separated by `spacing`. */\n count?: number;\n span?: number;\n spacing?: number;\n /** The closure form: the length for a container length (sampled as a linear function). */\n length?: (containerLength: number, axis: 'horizontal' | 'vertical') => number;\n alignment?: FrameAlignment;\n };\n\n/** The `containerRelativeFrame` style hint for a modifier value. */\nexport function containerRelativeFrame(value: ContainerRelativeFrameValue): NonNullable<Style['containerRelativeFrame']> {\n const spec = typeof value === 'string' ? { axes: value } : value;\n const horizontal = spec.axes !== 'vertical';\n const vertical = spec.axes !== 'horizontal';\n let a = 1;\n let b = 0;\n if (spec.length) {\n const axis = horizontal ? 'horizontal' : 'vertical';\n b = spec.length(0, axis);\n a = (spec.length(1000, axis) - b) / 1000;\n } else if (spec.count !== undefined) {\n // SwiftUI: (container − spacing × (count − 1)) × span / count + spacing × (span − 1).\n const n = Math.max(spec.count, 1);\n const span = Math.max(spec.span ?? 1, 1);\n const spacing = spec.spacing ?? 0;\n a = span / n;\n b = (-spacing * (n - 1) * span) / n + spacing * (span - 1);\n }\n return { ...(horizontal ? { horizontal: true } : {}), ...(vertical ? { vertical: true } : {}), a, b, alignment: spec.alignment ?? 'center' };\n}\n\nexport type AlignmentGuideName =\n | 'leading'\n | 'trailing'\n | 'horizontalCenter'\n | 'top'\n | 'bottom'\n | 'verticalCenter'\n | 'firstTextBaseline'\n | 'lastTextBaseline'\n | 'listRowSeparatorLeading'\n | 'listRowSeparatorTrailing';\n\nexport interface DropDestinationModifier {\n /**\n * Called on a drop: the payloads of an in-app drag (what `draggable` carried),\n * or the items dragged in from outside the page. Return false to refuse.\n */\n action: (items: unknown[], location: { x: number; y: number }) => boolean | void;\n /** While a drag is over the view. */\n isTargeted?: (targeted: boolean) => void;\n /** The MIME patterns taken from outside the page (`text/plain`, `image/*`…); none by default. */\n accepts?: string[];\n}\n\nexport interface InspectorModifier {\n isPresented: BindingValue<boolean>;\n content: ReactNode;\n /** `.inspectorColumnWidth(_:)` */\n columnWidth?: number;\n}\n\nexport type ModifierKey = keyof ViewModifiers;\nexport type ModifierEntry = [ModifierKey, unknown];\n\nconst MODIFIER_KEYS: ReadonlySet<string> = new Set<ModifierKey>([\n 'padding',\n 'font',\n 'fontWeight',\n 'bold',\n 'monospacedDigit',\n 'foregroundStyle',\n 'background',\n 'overlay',\n 'frame',\n 'cornerRadius',\n 'clipShape',\n 'clipped',\n 'compositingGroup',\n 'opacity',\n 'disabled',\n 'hidden',\n 'layoutPriority',\n 'lineLimit',\n 'multilineTextAlignment',\n 'fixedSize',\n 'offset',\n 'rotationEffect',\n 'scaleEffect',\n 'shadow',\n 'tint',\n 'badge',\n 'listRowInsets',\n 'listRowBackground',\n 'imageScale',\n 'symbolRenderingMode',\n 'transition',\n 'animation',\n 'gridColumnAlignment',\n 'gridCellColumns',\n 'buttonStyle',\n 'controlSize',\n 'pickerStyle',\n 'toggleStyle',\n 'labelsHidden',\n 'navigationTitle',\n 'navigationSubtitle',\n 'navigationBarTitleDisplayMode',\n 'toolbarRole',\n 'toolbarVisibility',\n 'statusBarHidden',\n 'toolbar',\n 'searchable',\n 'navigationDestination',\n 'sheet',\n 'fullScreenCover',\n 'alert',\n 'confirmationDialog',\n 'presentationDetents',\n 'onScrollVisibilityChange',\n 'onGeometryChange',\n 'onTapGesture',\n 'dragGesture',\n 'magnifyGesture',\n 'rotateGesture',\n 'onLongPressGesture',\n 'onTouches',\n 'simultaneousGesture',\n 'highPriorityGesture',\n 'contextMenu',\n 'swipeActions',\n 'onAppear',\n 'onDisappear',\n 'tag',\n 'modifiers',\n 'aspectRatio',\n 'scaledToFit',\n 'scaledToFill',\n 'blur',\n 'brightness',\n 'contrast',\n 'saturation',\n 'grayscale',\n 'hueRotation',\n 'colorInvert',\n 'colorMultiply',\n 'blendMode',\n 'mask',\n 'position',\n 'zIndex',\n 'allowsHitTesting',\n 'contentShape',\n 'ignoresSafeArea',\n 'rotation3DEffect',\n 'gridCellAnchor',\n 'alignmentGuide',\n 'preferredColorScheme',\n 'refreshable',\n 'submitLabel',\n 'keyboardType',\n 'textContentType',\n 'textInputAutocapitalization',\n 'autocorrectionDisabled',\n 'labelStyle',\n 'task',\n 'onChangeOf',\n 'scrollID',\n 'draggable',\n 'dropDestination',\n 'inspector',\n 'onHover',\n 'onContinuousHover',\n 'help',\n 'pointerStyle',\n 'symbolEffect',\n 'matchedGeometryEffect',\n 'layoutValue',\n 'safeAreaInset',\n 'popover',\n 'fileImporter',\n 'fileExporter',\n 'redacted',\n 'keyboardShortcut',\n 'onKeyPress',\n 'sensoryFeedback',\n 'textCase',\n 'textSelection',\n 'coordinateSpace',\n 'contentTransition',\n 'scrollDisabled',\n 'defaultMinListRowHeight',\n 'scrollEdgeEffectStyle',\n 'scrollEdgeEffectHidden',\n 'contentMargins',\n 'containerRelativeFrame',\n 'visualEffect',\n 'scrollTransition',\n]);\n\n/**\n * Separate a component's own props from the modifiers, keeping the modifiers\n * in the order they were written (object keys keep insertion order).\n */\nexport function splitProps<P extends object>(props: P): { own: Omit<P, ModifierKey>; modifiers: ModifierEntry[] } {\n const own: Record<string, unknown> = {};\n const modifiers: ModifierEntry[] = [];\n for (const [key, value] of Object.entries(props)) {\n if (MODIFIER_KEYS.has(key)) modifiers.push([key as ModifierKey, value]);\n else own[key] = value;\n }\n return { own: own as Omit<P, ModifierKey>, modifiers };\n}\n\n/** Remove and return one modifier a component handles itself. */\nexport function takeModifier<K extends ModifierKey>(modifiers: ModifierEntry[], key: K): ViewModifiers[K] | undefined {\n const at = modifiers.findIndex(([name]) => name === key);\n if (at < 0) return undefined;\n const [, value] = modifiers[at]!;\n modifiers.splice(at, 1);\n return value as ViewModifiers[K];\n}\n\nexport function styled(style: Style, child: ReactNode): ReactElement {\n return sb('styled', { style }, undefined, child);\n}\n\n/** The `gesture` element of a drag, pinch or long-press modifier, in a composition `mode` (`.gesture` when absent). */\nfunction gesture(key: keyof GestureValue, value: unknown, node: ReactNode, mode?: GestureMode): ReactNode {\n const base: Record<string, unknown> = { drag: false, longPress: false, minimumDistance: 10, minimumDuration: 0.5 };\n if (mode) base['mode'] = mode;\n switch (key) {\n case 'dragGesture':\n return createElement(DragGestureElement, { spec: value as DragGestureModifier, mode }, node);\n case 'magnifyGesture':\n case 'rotateGesture': {\n const pinch = value as MagnifyGestureModifier & RotateGestureModifier;\n if (key === 'magnifyGesture') {\n base['magnify'] = true;\n base['minimumScaleDelta'] = pinch.minimumScaleDelta ?? 0.01;\n } else {\n base['rotate'] = true;\n base['minimumAngleDelta'] = pinch.minimumAngleDelta ?? 1;\n }\n return sb('gesture', base, {\n pinch: (event) => {\n const pinchValue: PinchValue = {\n magnification: event.scale,\n rotation: event.rotation,\n magnificationVelocity: event.scaleVelocity,\n rotationVelocity: event.rotationVelocity,\n startLocation: event.startLocation,\n startAnchor: event.startAnchor,\n location: event.location ?? event.startLocation,\n };\n if (event.phase === 'ended' || event.phase === 'cancelled') pinch.onEnded?.(pinchValue);\n else pinch.onChanged?.(pinchValue);\n },\n }, node);\n }\n case 'onLongPressGesture': {\n const spec = typeof value === 'function' ? { action: value as () => void } : (value as { minimumDuration?: number; action: () => void });\n base['longPress'] = true;\n base['minimumDuration'] = spec.minimumDuration ?? 0.5;\n return sb('gesture', base, { longpress: () => spec.action() }, node);\n }\n }\n}\n\n/**\n * `.gesture(DragGesture(coordinateSpace:))`: `local` and `global` are the\n * renderer's; a named space is the global point less the frame\n * `coordinateSpace` reported for that name (as `GeometryReader`'s\n * `frame({ named })`), global when no ancestor names it.\n */\nfunction DragGestureElement({ spec, mode, children }: { spec: DragGestureModifier; mode?: GestureMode | undefined; children?: ReactNode }): ReactNode {\n const spaces = useCoordinateSpaces();\n const space = spec.coordinateSpace ?? 'local';\n const named = typeof space === 'object' ? spaces[space.named] : null;\n const props: Record<string, unknown> = { drag: true, longPress: false, minimumDistance: spec.minimumDistance ?? 10, minimumDuration: 0.5 };\n if (space !== 'local') props['coordinateSpace'] = 'global';\n if (mode) props['mode'] = mode;\n const inSpace = (point: { x: number; y: number }): { x: number; y: number } => (named ? { x: point.x - named.x, y: point.y - named.y } : point);\n return sb(\n 'gesture',\n props,\n {\n drag: (event) => {\n const dragValue: DragValue = {\n translation: event.translation,\n location: inSpace(event.location),\n startLocation: inSpace(event.startLocation),\n velocity: event.velocity,\n };\n if (event.phase === 'ended' || event.phase === 'cancelled') spec.onEnded?.(dragValue);\n else spec.onChanged?.(dragValue);\n },\n },\n children,\n );\n}\n\nfunction decorated(role: 'background' | 'overlay', alignment: FrameAlignment, content: ReactNode, decoration: ReactNode): ReactElement {\n return sb('decorated', { role, alignment }, undefined, [\n createElement(Fragment, { key: 'content' }, content),\n createElement(Fragment, { key: 'decoration' }, decoration),\n ]);\n}\n\nexport function shapeSpecOf(element: ReactElement): ShapeSpec | null {\n const spec = (element.type as { shape?: ShapeSpec }).shape;\n if (!spec) return null;\n const radius = (element.props as { cornerRadius?: number }).cornerRadius;\n return { kind: spec.kind, cornerRadius: spec.cornerRadius ?? radius ?? 0 };\n}\n\n/** `.animation(_:value:)`: a token that changes with the value. */\nfunction AnimatedStyle({ animation, value, children }: { animation: Animation; value: unknown; children?: ReactNode }): ReactElement {\n const last = useRef<{ value: unknown; token: number }>({ value, token: 0 });\n if (!Object.is(last.current.value, value)) last.current = { value, token: last.current.token + 1 };\n return styled({ animation, animationToken: last.current.token }, children);\n}\n\nfunction Searchable({ text, onChange, prompt }: SearchableModifier): ReactElement {\n const [value, setValue] = readBinding(text, onChange);\n return sb('searchfield', { text: value, placeholder: prompt ?? 'Search' }, { text: (event) => setValue(event.value) });\n}\n\n/**\n * Apply `modifiers` to `element`, in order. Styled wrappers nest around the\n * element; hoisted elements and lifecycle components come after it, in a\n * fragment. Preferences (`navigationTitle` and the bar's other settings, a\n * color scheme) come before it: the tree merges them in order, so one set\n * inside the view, met later, wins over the view's own, as in SwiftUI, where\n * the innermost `navigationTitle` is the screen's.\n */\nexport function applyModifiers(element: ReactNode, modifiers: readonly ModifierEntry[]): ReactNode {\n const sides: ReactNode[] = [];\n const node = wrap(element, modifiers, sides);\n const prefs = sides.filter(isPreference);\n const rest = sides.filter((side) => !isPreference(side));\n // always this shape (the preferences' fragment first, even empty), so a side modifier coming or going leaves the view in place\n return createElement(Fragment, null, createElement(Fragment, null, ...prefs), node, ...rest);\n}\n\nconst isPreference = (side: ReactNode): boolean => isValidElement<{ kind?: unknown }>(side) && side.props.kind === PREF_KIND;\n\nfunction wrap(element: ReactNode, modifiers: readonly ModifierEntry[], sides: ReactNode[]): ReactNode {\n let node = element;\n // A view that can hold others records its inherited styles for the presentations among them.\n const holds = holdsViews(element);\n /** This view's presentations, each with the inherited styles written after it (around it, in SwiftUI), innermost first. */\n const presentations: { at: number; after: Style[] }[] = [];\n for (const [key, value] of modifiers) {\n const inactive = value === undefined || (value === null && key !== 'lineLimit' && key !== 'badge');\n const before = sides.length;\n const next = inactive ? node : apply(key, value, node, sides);\n node = next === node ? neutral(key, node) : next;\n if (INHERITED_STYLE_KEYS.has(key)) {\n const style = styleOf(node);\n if (Object.keys(style).length > 0) for (const presentation of presentations) presentation.after.push(style);\n if (holds) node = createElement(InheritStyle, { style }, node);\n }\n if (PRESENTATION_KEYS.has(key) && sides.length > before) presentations.push({ at: before, after: [] });\n }\n for (const { at, after } of presentations) {\n const side = sides[at];\n if (after.length > 0 && isValidElement(side)) sides[at] = cloneElement(side, { inherited: after.reverse() } as object);\n }\n return node;\n}\n\n/**\n * Whether `element` can hold other views (and so a presentation below it):\n * anything but a host element written without children (a text, an\n * image, a shape). Decided by how the element is written, not by what it\n * holds now, so its wrappers stay the same as its content comes and goes.\n */\nfunction holdsViews(element: ReactNode): boolean {\n if (!isValidElement<{ children?: unknown }>(element)) return false;\n return element.type !== 'sb' || element.props.children !== undefined;\n}\n\n/** The modifiers whose wrapper is a `styled` node (a view `background` too). */\nconst STYLED_KEYS: ReadonlySet<ModifierKey> = new Set<ModifierKey>([\n 'padding', 'font', 'fontWeight', 'bold', 'monospacedDigit', 'foregroundStyle', 'background', 'frame', 'cornerRadius', 'clipShape', 'clipped', 'compositingGroup',\n 'opacity', 'disabled', 'hidden', 'layoutPriority', 'lineLimit', 'multilineTextAlignment', 'fixedSize', 'offset',\n 'rotationEffect', 'scaleEffect', 'shadow', 'tint', 'badge', 'listRowInsets', 'listRowBackground', 'imageScale', 'transition',\n 'gridColumnAlignment', 'gridCellColumns', 'aspectRatio', 'scaledToFit', 'scaledToFill', 'blur', 'brightness', 'contrast',\n 'saturation', 'grayscale', 'hueRotation', 'colorInvert', 'colorMultiply', 'blendMode', 'mask', 'position', 'zIndex',\n 'allowsHitTesting', 'contentShape', 'ignoresSafeArea', 'rotation3DEffect', 'gridCellAnchor', 'alignmentGuide', 'help', 'pointerStyle',\n 'matchedGeometryEffect', 'containerRelativeFrame', 'contentTransition', 'scrollDisabled', 'textSelection', 'defaultMinListRowHeight',\n]);\n\n/** The modifiers whose wrapper extends the view environment. */\nconst ENVIRONMENT_KEYS: ReadonlySet<ModifierKey> = new Set<ModifierKey>([\n 'buttonStyle', 'controlSize', 'pickerStyle', 'toggleStyle', 'labelsHidden', 'refreshable', 'submitLabel', 'labelStyle', 'redacted', 'textCase',\n 'symbolRenderingMode', 'keyboardType', 'textContentType', 'textInputAutocapitalization', 'autocorrectionDisabled',\n]);\n\n/** The modifiers whose wrapper extends the scroll settings. */\nconst SCROLL_KEYS: ReadonlySet<ModifierKey> = new Set<ModifierKey>(['scrollEdgeEffectStyle', 'scrollEdgeEffectHidden', 'contentMargins']);\n\n/**\n * A modifier that is written but does nothing (`undefined`, `false`) still\n * wraps the view, in the same kind of wrapper it has when it is on, with\n * nothing in it. Otherwise turning it on or off would change the element\n * types above the view and React would remount everything under it, as\n * SwiftUI never does for `.overlay { if open { … } }` or `.disabled(flag)`.\n */\nfunction neutral(key: ModifierKey, node: ReactNode): ReactNode {\n if (key === 'overlay') return decorated('overlay', 'center', node, null);\n if (STYLED_KEYS.has(key)) return styled({}, node);\n if (ENVIRONMENT_KEYS.has(key)) return withEnvironment({}, node);\n if (SCROLL_KEYS.has(key)) return withScrollSettings({}, node);\n return node;\n}\n\nfunction apply(key: ModifierKey, value: unknown, node: ReactNode, sides: ReactNode[]): ReactNode {\n switch (key) {\n case 'padding':\n return styled({ padding: padding(value as PaddingValue) }, node);\n case 'font':\n return styled({ font: font(value as FontValue) }, node);\n case 'fontWeight':\n return styled({ font: { weight: value as FontWeight } }, node);\n case 'bold':\n return value ? styled({ font: { weight: 'bold' } }, node) : node;\n case 'monospacedDigit':\n return value ? styled({ font: { monospacedDigit: true } }, node) : node;\n case 'foregroundStyle': {\n if (!Array.isArray(value)) return styled({ foreground: shapeStyle(value as StyleValue) }, node);\n const [primary, ...levels] = value as unknown as ForegroundLayers;\n return styled({ foreground: shapeStyle(primary), foregroundLevels: levels.map((level) => shapeStyle(level)) }, node);\n }\n case 'background': {\n if (isValidElement(value)) return decorated('background', 'center', node, value);\n const inShape = value as BackgroundInShape;\n if (typeof inShape === 'object' && inShape !== null && 'in' in inShape && isValidElement(inShape.in)) {\n return decorated('background', 'center', node, cloneElement(inShape.in, { fill: inShape.fill } as object));\n }\n return styled({ background: shapeStyle(value as StyleValue) }, node);\n }\n case 'overlay': {\n if (isValidElement(value)) return decorated('overlay', 'center', node, value);\n const spec = value as { content: ReactElement; alignment?: FrameAlignment };\n return decorated('overlay', spec.alignment ?? 'center', node, spec.content);\n }\n case 'frame':\n return styled({ frame: frame(value as FrameValue) }, node);\n case 'cornerRadius':\n return styled({ cornerRadius: value as number }, node);\n case 'clipShape': {\n const spec = isValidElement(value) ? shapeSpecOf(value) : null;\n return styled({ cornerRadius: spec?.cornerRadius ?? 0 }, node);\n }\n case 'clipped':\n return value ? styled({ clipped: true }, node) : node;\n case 'compositingGroup':\n return value ? styled({ compositingGroup: true }, node) : node;\n case 'opacity':\n return styled({ opacity: value as number }, node);\n case 'disabled':\n return value ? styled({ disabled: true }, node) : node;\n case 'hidden':\n return value ? styled({ hidden: true }, node) : node;\n case 'layoutPriority':\n return styled({ layoutPriority: value as number }, node);\n case 'lineLimit': {\n if (Array.isArray(value)) {\n const [min, max] = value as [number, number | null];\n return styled({ lineLimit: max, lineLimitMin: min }, node);\n }\n return styled({ lineLimit: value as number | null }, node);\n }\n case 'multilineTextAlignment':\n return styled({ multilineTextAlignment: value as TextAlignment }, node);\n case 'fixedSize':\n return value ? styled({ fixedSize: value === true ? { horizontal: true, vertical: true } : (value as FixedSize) }, node) : node;\n case 'offset': {\n const offset = value as { x?: number; y?: number };\n return styled({ offset: { x: offset.x ?? 0, y: offset.y ?? 0 } }, node);\n }\n case 'rotationEffect': {\n if (typeof value === 'number') return styled({ rotation: value }, node);\n const spec = value as { degrees: number; anchor?: UnitPointValue };\n const style: Style = { rotation: spec.degrees };\n if (spec.anchor !== undefined) style.rotationAnchor = unitPoint(spec.anchor);\n return styled(style, node);\n }\n case 'scaleEffect': {\n if (typeof value === 'number') return styled({ scale: { x: value, y: value } }, node);\n const spec = value as { x: number; y: number; anchor?: UnitPointValue };\n const style: Style = { scale: { x: spec.x, y: spec.y } };\n if (spec.anchor !== undefined) style.scaleAnchor = unitPoint(spec.anchor);\n return styled(style, node);\n }\n case 'shadow': {\n const shadow = value as { color?: ColorValue; radius: number; x?: number; y?: number };\n return styled(\n { shadow: { color: shadow.color ? color(shadow.color) : rgb(0, 0, 0, 0.33), radius: shadow.radius, x: shadow.x ?? 0, y: shadow.y ?? 0 } },\n node,\n );\n }\n case 'tint':\n return styled({ tint: color(value as ColorValue) }, node);\n case 'badge':\n return styled({ badge: value === null ? null : String(value) }, node);\n case 'listRowInsets':\n return styled({ listRowInsets: value as EdgeInsets }, node);\n case 'listRowBackground':\n return styled({ listRowBackground: color(value as ColorValue) }, node);\n case 'imageScale':\n return styled({ imageScale: value as ImageScale }, node);\n case 'transition':\n return styled({ transition: value as Transition }, node);\n case 'animation': {\n const spec = value as { animation?: Animation; value: unknown };\n return createElement(AnimatedStyle, { animation: spec.animation ?? { type: 'default' }, value: spec.value }, node);\n }\n case 'gridColumnAlignment':\n return styled({ gridColumnAlignment: value } as Style, node);\n case 'gridCellColumns':\n return styled({ gridCellColumns: value as number }, node);\n case 'buttonStyle':\n return withEnvironment({ buttonStyle: value as ButtonStyle }, node);\n case 'controlSize':\n return withEnvironment({ controlSize: value as ControlSize }, node);\n case 'symbolRenderingMode':\n return withEnvironment({ symbolRenderingMode: value as SymbolRenderingMode }, node);\n case 'pickerStyle':\n return withEnvironment({ pickerStyle: value as PickerStyle }, node);\n case 'toggleStyle':\n return withEnvironment({ toggleStyle: value as ToggleStyle }, node);\n case 'labelsHidden':\n return withEnvironment({ labelsHidden: Boolean(value) }, node);\n case 'navigationTitle':\n sides.push(sb(PREF_KIND, { title: value as string }, undefined, undefined, 'navscreen'));\n return node;\n case 'navigationSubtitle':\n sides.push(sb(PREF_KIND, { subtitle: value as string }, undefined, undefined, 'navscreen'));\n return node;\n case 'navigationBarTitleDisplayMode':\n sides.push(sb(PREF_KIND, { displayMode: value as string }, undefined, undefined, 'navscreen'));\n return node;\n case 'toolbarRole':\n sides.push(sb(PREF_KIND, { toolbarRole: value as string }, undefined, undefined, 'navscreen'));\n return node;\n case 'toolbarVisibility': {\n const bars = value as NonNullable<ViewModifiers['toolbarVisibility']>;\n const props: Record<string, boolean> = {};\n if (bars.navigationBar && bars.navigationBar !== 'automatic') props['navigationBarHidden'] = bars.navigationBar === 'hidden';\n if (bars.bottomBar && bars.bottomBar !== 'automatic') props['bottomBarHidden'] = bars.bottomBar === 'hidden';\n sides.push(sb(PREF_KIND, props, undefined, undefined, 'navscreen'));\n return node;\n }\n case 'statusBarHidden':\n sides.push(sb(PREF_KIND, { statusBarHidden: Boolean(value) }, undefined, undefined, 'navscreen'));\n return node;\n case 'toolbar':\n sides.push(sb(HOIST_KIND, undefined, undefined, value as ReactNode, 'navscreen'));\n return node;\n case 'searchable':\n sides.push(sb(HOIST_KIND, undefined, undefined, createElement(Searchable, value as SearchableModifier), 'navscreen'));\n return node;\n case 'navigationDestination':\n sides.push(createElement(RegisterDestination, { destination: value as (value: never) => ReactNode }));\n return node;\n case 'sheet':\n sides.push(createElement(SheetPresenter, value as SheetModifier));\n return node;\n case 'fullScreenCover':\n sides.push(createElement(SheetPresenter, { ...(value as SheetModifier), fullScreen: true }));\n return node;\n case 'alert':\n sides.push(createElement(AlertPresenter, value as AlertModifier));\n return node;\n case 'confirmationDialog':\n sides.push(createElement(AlertPresenter, { ...(value as AlertModifier), style: 'dialog' }));\n return node;\n case 'presentationDetents':\n sides.push(presentationDetents(value as DetentValue[]));\n return node;\n case 'onScrollVisibilityChange': {\n const spec = typeof value === 'function' ? { action: value as (visible: boolean) => void } : (value as { threshold?: number; action: (visible: boolean) => void });\n return sb('styled', { style: { scrollVisibility: { threshold: spec.threshold ?? 0.5 } } }, { scrollvisibility: (event) => spec.action(event.visible) }, node);\n }\n case 'onTapGesture': {\n const spec = typeof value === 'function' ? { action: value as () => void } : (value as TapGestureModifier);\n const count = Math.floor(spec.count ?? 1);\n const props: Record<string, unknown> = count > 1 ? { count } : {};\n if ('perform' in spec) {\n const { perform } = spec;\n return sb('tapgesture', { ...props, location: true }, { tap: (event) => perform({ x: event.x ?? 0, y: event.y ?? 0 }) }, node);\n }\n return sb('tapgesture', props, { tap: () => spec.action() }, node);\n }\n case 'onGeometryChange':\n return createElement(GeometryChangeView, { handler: value as GeometryChangeHandler }, node);\n case 'dragGesture':\n case 'magnifyGesture':\n case 'rotateGesture':\n case 'onLongPressGesture':\n return gesture(key, value, node);\n case 'onTouches': {\n const handler = value as TouchesHandler;\n return sb('touches', {}, { touches: (event) => handler(event.touches, event.phase) }, node);\n }\n case 'simultaneousGesture':\n case 'highPriorityGesture': {\n const mode: GestureMode = key === 'simultaneousGesture' ? 'simultaneous' : 'highPriority';\n let result = node;\n for (const [gestureKey, gestureValue] of Object.entries(value as GestureValue) as [keyof GestureValue, unknown][]) {\n if (gestureValue !== undefined) result = gesture(gestureKey, gestureValue, result, mode);\n }\n return result;\n }\n case 'contextMenu':\n return sb('contextmenu', {}, undefined, [createElement(Fragment, { key: 'content' }, node), createElement(Fragment, { key: 'items' }, value as ReactNode)]);\n case 'swipeActions': {\n const specs = Array.isArray(value) ? (value as SwipeActionsModifier[]) : [value as SwipeActionsModifier];\n const trailing: ReactNode[] = [];\n const leading: ReactNode[] = [];\n let fullSwipeTrailing = true;\n let fullSwipeLeading = true;\n for (const spec of specs) {\n const actions = Children.toArray(spec.children);\n if (spec.edge === 'leading') {\n leading.push(...actions);\n fullSwipeLeading = spec.allowsFullSwipe ?? true;\n } else {\n trailing.push(...actions);\n fullSwipeTrailing = spec.allowsFullSwipe ?? true;\n }\n }\n return sb(\n 'swipeactions',\n { trailing: trailing.length, leading: leading.length, fullSwipeTrailing, fullSwipeLeading },\n undefined,\n [createElement(Fragment, { key: 'content' }, node), ...trailing, ...leading],\n );\n }\n case 'onAppear':\n sides.push(createElement(Lifecycle, { onAppear: value as () => void }));\n return node;\n case 'onDisappear':\n sides.push(createElement(Lifecycle, { onDisappear: value as () => void }));\n return node;\n case 'tag':\n return node;\n case 'aspectRatio': {\n const spec = typeof value === 'number' ? { ratio: value } : (value as { ratio?: number | null; contentMode?: 'fit' | 'fill' });\n return styled({ aspectRatio: { ratio: spec.ratio ?? null, contentMode: spec.contentMode ?? 'fit' } }, node);\n }\n case 'scaledToFit':\n return value ? styled({ aspectRatio: { ratio: null, contentMode: 'fit' } }, node) : node;\n case 'scaledToFill':\n return value ? styled({ aspectRatio: { ratio: null, contentMode: 'fill' } }, node) : node;\n case 'blur':\n return styled({ blur: value as number }, node);\n case 'brightness':\n return styled({ brightness: value as number }, node);\n case 'contrast':\n return styled({ contrast: value as number }, node);\n case 'saturation':\n return styled({ saturation: value as number }, node);\n case 'grayscale':\n return styled({ grayscale: value as number }, node);\n case 'hueRotation':\n return styled({ hueRotation: value as number }, node);\n case 'colorInvert':\n return value ? styled({ colorInvert: true }, node) : node;\n case 'colorMultiply':\n return styled({ colorMultiply: color(value as ColorValue) }, node);\n case 'blendMode':\n return styled({ blendMode: value as string }, node);\n case 'mask':\n return styled({ mask: shapeStyle(value as StyleValue) }, node);\n case 'position':\n return styled({ position: value as { x: number; y: number } }, node);\n case 'zIndex':\n return styled({ zIndex: value as number }, node);\n case 'allowsHitTesting':\n return value === false ? styled({ hitTesting: false }, node) : node;\n case 'contentShape':\n return value === 'rectangle' ? styled({ contentShape: 'rectangle' }, node) : node;\n case 'ignoresSafeArea':\n // `true` is `.ignoresSafeArea()`: every edge and the keyboard region too.\n return styled(\n value === true ? { ignoresSafeArea: 'all', ignoresKeyboard: true } : { ignoresSafeArea: value as ('top' | 'bottom' | 'leading' | 'trailing')[] },\n node,\n );\n case 'rotation3DEffect': {\n const spec = value as { angle: number; axis: { x: number; y: number; z: number }; anchor?: UnitPointValue; perspective?: number };\n const rotation: Style['rotation3D'] = { angle: spec.angle, axis: spec.axis };\n if (spec.anchor !== undefined) rotation!.anchor = unitPoint(spec.anchor);\n if (spec.perspective !== undefined) rotation!.perspective = spec.perspective;\n return styled({ rotation3D: rotation }, node);\n }\n case 'gridCellAnchor':\n return styled({ gridCellAnchor: unitPoint(value as UnitPointValue) }, node);\n case 'alignmentGuide': {\n const spec = value as { guide: AlignmentGuideName; value: (d: { width: number; height: number }) => number };\n const at = (width: number, height: number): number => spec.value({ width, height });\n const a = at(0, 0);\n const round = (n: number): number => Math.round(n * 1e6) / 1e6;\n const vertical = ['top', 'bottom', 'verticalCenter', 'firstTextBaseline', 'lastTextBaseline'].includes(spec.guide);\n const name = spec.guide === 'horizontalCenter' || spec.guide === 'verticalCenter' ? 'center' : spec.guide;\n return styled(\n {\n alignmentGuide: {\n axis: vertical ? 'vertical' : 'horizontal',\n name,\n value: [round(a), round((at(100, 0) - a) / 100), round((at(0, 100) - a) / 100)],\n },\n },\n node,\n );\n }\n case 'preferredColorScheme':\n sides.push(sb(PREF_KIND, { colorScheme: value as 'light' | 'dark' | null }, undefined, undefined, 'root'));\n return node;\n case 'refreshable':\n return withEnvironment({ refresh: value as () => unknown }, node);\n case 'submitLabel':\n return withEnvironment({ submitLabel: value as string }, node);\n case 'keyboardType':\n return withTextInputHint({ keyboard: value as KeyboardType }, node);\n case 'textContentType':\n return withTextInputHint({ contentType: (value as TextContentType | null) ?? undefined }, node);\n case 'textInputAutocapitalization':\n return withTextInputHint({ autocapitalization: (value as TextInputHints['autocapitalization'] | null) ?? undefined }, node);\n case 'autocorrectionDisabled':\n return withTextInputHint({ autocorrectionDisabled: value === true }, node);\n case 'labelStyle':\n return withEnvironment({ labelStyle: value as ViewEnvironment['labelStyle'] }, node);\n case 'task': {\n const spec = typeof value === 'function' ? { id: undefined, action: value as (signal: AbortSignal) => unknown } : (value as { id: unknown; action: (signal: AbortSignal) => unknown });\n sides.push(createElement(Task, spec));\n return node;\n }\n case 'onChangeOf':\n sides.push(createElement(OnChange, value as { value: unknown; action: (oldValue: unknown, newValue: unknown) => void; initial?: boolean }));\n return node;\n case 'scrollID':\n return createElement(ScrollTarget, { id: value as string | number }, node);\n case 'draggable':\n return createElement(Draggable, { payload: value }, node);\n case 'dropDestination':\n return createElement(DropDestination, value as DropDestinationModifier, node);\n case 'inspector':\n return createElement(Inspector, value as InspectorModifier, node);\n case 'onHover':\n return createElement(Hover, { action: value as (hovering: boolean) => void }, node);\n case 'onContinuousHover':\n return createElement(ContinuousHover, { spec: typeof value === 'function' ? { action: value as (phase: HoverPhase) => void } : (value as ContinuousHoverModifier) }, node);\n case 'help':\n return styled({ help: value as string }, node);\n case 'pointerStyle':\n return styled({ pointerStyle: cursorFor(value as string) }, node);\n case 'symbolEffect':\n return createElement(SymbolEffect, { spec: value as SymbolEffectModifier }, node);\n case 'matchedGeometryEffect': {\n const spec = value as { id: string | number; namespace?: string };\n return styled({ matchedGeometry: `${spec.namespace ?? ''}:${spec.id}` }, node);\n }\n case 'layoutValue':\n // Read by the enclosing `Layout` from the subview's props; nothing to draw.\n return node;\n case 'safeAreaInset': {\n const spec = value as { edge: 'top' | 'bottom' | 'leading' | 'trailing'; spacing?: number; alignment?: string; content: ReactNode };\n const vertical = spec.edge === 'top' || spec.edge === 'bottom';\n const before = spec.edge === 'top' || spec.edge === 'leading';\n const children = before\n ? [createElement(Fragment, { key: 'inset' }, spec.content), createElement(Fragment, { key: 'content' }, node)]\n : [createElement(Fragment, { key: 'content' }, node), createElement(Fragment, { key: 'inset' }, spec.content)];\n return vertical\n ? sb('vstack', { spacing: spec.spacing ?? 0, alignment: spec.alignment ?? 'center' }, undefined, children)\n : sb('hstack', { spacing: spec.spacing ?? 0, alignment: spec.alignment ?? 'center' }, undefined, children);\n }\n case 'popover':\n sides.push(createElement(SheetPresenter, value as SheetModifier));\n return node;\n case 'fileImporter':\n sides.push(createElement(FileImporterPresenter, value as FileImporterModifier));\n return node;\n case 'fileExporter':\n sides.push(createElement(FileExporterPresenter, value as FileExporterModifier));\n return node;\n case 'redacted':\n return withEnvironment({ redacted: Boolean(value) }, node);\n case 'keyboardShortcut':\n // A `Button` takes its own shortcut; elsewhere it has no action to run.\n return node;\n case 'onKeyPress':\n sides.push(createElement(KeyPressListener, { spec: value as OnKeyPressModifier }));\n return node;\n case 'sensoryFeedback': {\n const spec = value as { feedback: SensoryFeedback; trigger: unknown };\n sides.push(createElement(SensoryFeedbackPlayer, spec));\n return node;\n }\n case 'textCase':\n return withEnvironment({ textCase: value as 'uppercase' | 'lowercase' | null }, node);\n case 'coordinateSpace':\n return createElement(CoordinateSpace, { name: value as string }, node);\n case 'scrollEdgeEffectStyle':\n return withScrollSettings(edgeStyleSettings(value as ScrollEdgeEffectStyleValue), node);\n case 'scrollEdgeEffectHidden':\n return withScrollSettings(edgeHiddenSettings(value as ScrollEdgeEffectHiddenValue), node);\n case 'contentMargins':\n return withScrollSettings(marginSettings(value as ContentMarginsValue), node);\n case 'containerRelativeFrame':\n return styled({ containerRelativeFrame: containerRelativeFrame(value as ContainerRelativeFrameValue) }, node);\n case 'visualEffect':\n return createElement(VisualEffectView, { effect: value as VisualEffectClosure }, node);\n case 'scrollTransition': {\n const spec = typeof value === 'function' ? { transition: value as ScrollTransitionClosure } : (value as ScrollTransitionSpec);\n return createElement(ScrollTransitionView, { spec }, node);\n }\n case 'scrollDisabled':\n return styled({ scrollDisabled: value === true }, node);\n case 'defaultMinListRowHeight':\n return typeof value === 'number' && Number.isFinite(value) ? styled({ defaultMinListRowHeight: Math.max(0, value) }, node) : styled({}, node);\n case 'textSelection':\n return styled({ textSelection: value === 'enabled' }, node);\n case 'contentTransition': {\n if (value === 'identity') return node;\n if (typeof value === 'object') {\n const countsDown = (value as { numericText: { countsDown?: boolean } }).numericText.countsDown;\n return styled({ contentTransition: { kind: 'numericText', ...(countsDown !== undefined ? { countsDown } : {}) } }, node);\n }\n return styled({ contentTransition: { kind: value as 'numericText' | 'opacity' | 'interpolate' } }, node);\n }\n case 'modifiers': {\n let result = node;\n for (const extra of value as ViewModifiers[]) {\n result = wrap(result, Object.entries(extra) as ModifierEntry[], sides);\n }\n return result;\n }\n default: {\n const unknown: never = key;\n throw new Error(`Unknown modifier ${String(unknown)}`);\n }\n }\n}\n\n/** One text input hint for the text fields below, over the ones above. */\nfunction withTextInputHint(hint: TextInputHints, node: ReactNode): ReactElement {\n return createElement(TextInputHint, { hint }, node);\n}\n\nfunction TextInputHint({ hint, children }: { hint: TextInputHints; children?: ReactNode }): ReactNode {\n const outer = useViewEnvironment().textInputHints;\n return withEnvironment({ textInputHints: { ...outer, ...hint } }, children);\n}\n","/**\n * `HostElement`: an element of a kind of the app's own (`'app:preview'`),\n * for a host that draws it. A tree drawn by another root's `RemoteTree`\n * (an app inside a platform's page) names the kind, with the props the\n * host's view wants, and the host draws its own view there (`RemoteTree`'s\n * `elements`): a file's preview, a map, whatever the host has and the app\n * has not. The modifiers apply around it as around any view. Where no host\n * draws the kind, the renderer draws nothing for it.\n */\nimport type { ReactNode } from 'react';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, type ViewModifiers } from '../modifiers';\n\nexport interface HostElementProps extends ViewModifiers {\n /** The kind, as the host's `elements` names it: a prefix of the host's own keeps it apart from SwiftBrowser's kinds (`'noya:file'`). */\n kind: string;\n /** What the host's view takes: plain data (JSON). */\n props?: Readonly<Record<string, unknown>>;\n children?: ReactNode;\n}\n\nexport function HostElement(props: HostElementProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n return applyModifiers(sb(own.kind, own.props ? { ...own.props } : undefined, undefined, own.children), modifiers);\n}\n","/**\n * `measureText(text, font, width)`: the size a `Text` of `text` in `font`\n * takes wrapped to `width`, answered synchronously by whatever draws the\n * app: on the web the renderer's typography (the same wrapping and line\n * heights its layout engine uses, `mount` installs it), natively the host's\n * `NSAttributedString` bounding rect through the bridge (`run` installs it).\n * For an app that lays out from text sizes itself: pagination, say. SwiftUI\n * has no such call; this is the one `UIFont` and `NSAttributedString` give.\n */\n\nimport type { Font as ProtocolFont } from '@swiftbrowser/web/src/protocol';\nimport { font as fontOf, type FontValue } from './values';\n\nexport interface TextMeasurement {\n /** The widest line, in points. */\n width: number;\n /** The lines' height, as a `Text` is tall. */\n height: number;\n /** How many lines the text wraps to (one for an empty text). */\n lines: number;\n}\n\n/** What answers `measureText`: the renderer's or the host's measurer. */\nexport type TextMeasurerFunction = (text: string, font: ProtocolFont, width: number | null) => TextMeasurement;\n\nlet installed: TextMeasurerFunction | null = null;\n\n/** Points `measureText` at a measurer (`mount`, `run`); the same one again to remove it. */\nexport function installTextMeasurer(measurer: TextMeasurerFunction | null, remove = false): void {\n if (remove) {\n if (installed === measurer) installed = null;\n return;\n }\n installed = measurer;\n}\n\n/** Whether something answers `measureText` here (a mounted app, a native host). */\nexport function canMeasureText(): boolean {\n return installed !== null;\n}\n\n/**\n * The size of `text` in `font` (a text style name or `system(size, weight,\n * design)`; `body` by default) wrapped to `width` points, or on one line\n * when `width` is omitted. Throws before an app is mounted or run.\n */\nexport function measureText(text: string, font: FontValue = 'body', width?: number): TextMeasurement {\n if (!installed) throw new Error('measureText: nothing measures text here yet (mount the app, or run it in a SwiftBrowser Native host)');\n const constrained = typeof width === 'number' && Number.isFinite(width) && width > 0 ? width : null;\n return installed(text, fontOf(font), constrained);\n}\n","/**\n * `mount(screen, element)`: the renderer of @swiftbrowser/web in `screen`\n * (the root container, element id 0, inside the device frame or full screen)\n * drawing a SwiftUI root. The page keeps the device chrome (theme, text size)\n * and tells both sides through `setEnvironment`; the size class follows the\n * root's width, the scene phase the document's visibility and focus, and the\n * platform (docs/notes/macos.md) the browser, unless the page says.\n */\n\nimport { horizontalSizeClassFor, type ColorScheme, type DynamicTypeSize, type Platform } from '@swiftbrowser/web/src/protocol';\nimport type { AssetCatalog } from '@swiftbrowser/web/src/assets';\nimport { BrowserHistory } from '@swiftbrowser/web/src/browserHistory';\nimport { watchKeyboard } from '@swiftbrowser/web/src/deviceMode';\nimport { browserEnvironment } from '@swiftbrowser/web/src/hostRequests';\nimport { Renderer } from '@swiftbrowser/web/src/renderer';\nimport { currentScenePhase, watchScenePhase } from '@swiftbrowser/web/src/scenePhase';\nimport { createElement, type ReactNode } from 'react';\nimport { LazyWindowContext } from './lazy';\nimport { createSwiftUIRoot, type SwiftUIRoot } from './host/root';\nimport { installTextMeasurer, type TextMeasurerFunction } from './measureText';\n\nexport interface MountOptions {\n colorScheme?: ColorScheme;\n dynamicTypeSize?: DynamicTypeSize;\n /**\n * The platform the app is drawn as (docs/notes/macos.md): `ios` or\n * `macos`, or `auto` (the default), which is macOS in a browser with a\n * fine pointer that can hover (a desktop) showing the root at 700 CSS px\n * or more, and iOS otherwise. A preview page's device picker\n * (`installDeviceFrame`) sets it afterwards from the device chosen.\n */\n platform?: Platform | 'auto';\n /** Device mode: the real safe-area insets (frame mode has the iPhone's). */\n safeArea?: { top: number; leading: number; bottom: number; trailing: number } | null;\n /** The root is as tall as its content (an island in a page), not as the screen. */\n contentHeight?: boolean;\n /**\n * The asset catalog manifest `Image(name:)` and catalog colors resolve\n * against (the `/catalog/<App>.json` the SwiftBrowser build writes, or one\n * of your own: `{ images: { name: { src, width, height, scale, kind } }, colors: {} }`).\n */\n assets?: AssetCatalog;\n /**\n * The app's name: its files (`fileManager`) live in the IndexedDB database\n * `sb-files:<app>`, as a Swift app's of that name do. `app` by default.\n */\n app?: string;\n /**\n * Mirror navigation in the browser's history (the default): pushing a\n * screen, presenting a sheet or moving a split view's sidebar selection\n * adds an entry, and the browser's back and edge swipe pop, dismiss or\n * reselect it (the renderer's own swipe back is then off).\n * The URL is left alone; map screens to paths yourself with\n * `history.replaceState` (not `pushState`, which would add a second entry).\n * `false` leaves the history untouched, for an island in a page whose own\n * router owns it.\n */\n history?: boolean;\n /**\n * Follow the on-screen keyboard (a phone's): its height becomes a bottom\n * inset, so a field, a bottom search field or a chat's composer rises\n * above it and a list stops above it, as on iOS, instead of the browser\n * panning the page to the field. For a root that fills the layout\n * viewport (a full-screen app); off by default.\n */\n keyboard?: boolean;\n /**\n * The Mac's sidebar panel paints its top 44 points in the window's color,\n * where macOS draws the title bar behind the window's buttons (`true`, the\n * default). `false` keeps the panel's sidebar fill to its top: a page has\n * no window buttons there. Web only (a native app is in a real window).\n */\n sidebarTitleBar?: boolean;\n}\n\nexport interface Mounted {\n root: SwiftUIRoot;\n renderer: Renderer;\n /** The device environment, for the renderer and the tree both (the page's theme toggle, a device picker's platform). */\n setEnvironment(environment: { colorScheme?: ColorScheme; dynamicTypeSize?: DynamicTypeSize; platform?: Platform }): void;\n /** The renderer's (`installDeviceFrame` drives these). */\n setSafeArea(insets: { top: number; leading: number; bottom: number; trailing: number } | null): void;\n viewportChanged(): void;\n unmount(): void;\n}\n\n/**\n * The platform `auto` decides for a root `width` CSS px wide: macOS with a\n * fine pointer that hovers (a desktop browser) at the regular width, iOS\n * otherwise. Width alone is no signal: a narrow desktop window is not a phone.\n */\nexport function decidePlatform(width: number, media: (query: string) => boolean = matchesMedia): Platform {\n return horizontalSizeClassFor(width) === 'regular' && media('(hover: hover) and (pointer: fine)') ? 'macos' : 'ios';\n}\n\nfunction matchesMedia(query: string): boolean {\n return typeof matchMedia === 'function' && matchMedia(query).matches;\n}\n\nexport function mount(screen: HTMLElement, element: ReactNode, options: MountOptions = {}): Mounted {\n let renderer: Renderer | null = null;\n const root = createSwiftUIRoot((ops) => renderer?.applyOps(ops));\n renderer = new Renderer(screen, (event) => root.dispatch(event));\n // A React app is in the page: a dropped file comes as the `File` itself, a dropped folder as its files by path (src/dragDrop.ts).\n renderer.fileDrops = 'reference';\n // `measureText` answers from this renderer's typography while it is mounted.\n const measurer: TextMeasurerFunction = (text, font, width) => renderer!.measureText(text, font, width);\n installTextMeasurer(measurer);\n // The page's appearance; `.preferredColorScheme` overrides it while set.\n let pageScheme: ColorScheme = options.colorScheme ?? 'light';\n let preferred: ColorScheme | null = null;\n const width = screen.clientWidth || 393;\n const environment = {\n colorScheme: pageScheme,\n dynamicTypeSize: options.dynamicTypeSize ?? 'large',\n horizontalSizeClass: horizontalSizeClassFor(width),\n scenePhase: typeof document !== 'undefined' ? currentScenePhase() : ('active' as const),\n platform: options.platform === undefined || options.platform === 'auto' ? decidePlatform(width) : options.platform,\n };\n renderer.contentHeight = options.contentHeight ?? false;\n if (options.sidebarTitleBar === false) renderer.sidebarTitleBar = false;\n if (options.assets) renderer.setAssetCatalog(options.assets);\n if (options.app) (browserEnvironment.files as { setApp?: (app: string) => void } | undefined)?.setApp?.(options.app);\n renderer.setEnvironment({ colorScheme: environment.colorScheme, dynamicTypeSize: environment.dynamicTypeSize, platform: environment.platform });\n if (options.safeArea !== undefined) renderer.setSafeArea(options.safeArea);\n root.setEnvironment(environment);\n const browserHistory = (options.history ?? true) && typeof window !== 'undefined' ? new BrowserHistory(renderer, screen) : null;\n browserHistory?.enable();\n const stopKeyboard = options.keyboard && typeof window !== 'undefined' ? watchKeyboard((height) => renderer?.setKeyboard(height), { root: screen }) : null;\n\n const applyScheme = (): void => {\n const scheme = preferred ?? pageScheme;\n const device = screen.closest<HTMLElement>('.device');\n if (device) device.dataset['theme'] = scheme;\n renderer?.setEnvironment({ colorScheme: scheme });\n root.setEnvironment({ colorScheme: scheme });\n };\n const onPreferredScheme = (event: Event): void => {\n const scheme = (event as CustomEvent<{ colorScheme: ColorScheme | null }>).detail.colorScheme;\n preferred = scheme;\n // Outside the commit that asked for it.\n queueMicrotask(applyScheme);\n };\n screen.addEventListener('sb:color-scheme', onPreferredScheme);\n\n // The size class follows the root's width (700 points and up is regular).\n let sizeClass = environment.horizontalSizeClass;\n const observer =\n typeof ResizeObserver !== 'undefined'\n ? new ResizeObserver(() => {\n const next = horizontalSizeClassFor(screen.clientWidth);\n if (next === sizeClass) return;\n sizeClass = next;\n root.setEnvironment({ horizontalSizeClass: next });\n })\n : null;\n observer?.observe(screen);\n // The scene phase follows the document (hidden: background) and the window's focus.\n const stopScenePhase = typeof document !== 'undefined' ? watchScenePhase((scenePhase) => root.setEnvironment({ scenePhase })) : null;\n\n // The page unbuilds a lazy stack's rows far from the visible area (renderer.ts `checkLazyWindow`).\n root.render(createElement(LazyWindowContext.Provider, { value: true }, element));\n const mounted: Mounted = {\n root,\n renderer,\n setEnvironment(next) {\n if (next.colorScheme !== undefined) pageScheme = next.colorScheme;\n const scheme = preferred ?? pageScheme;\n renderer?.setEnvironment({ ...next, colorScheme: scheme });\n root.setEnvironment({ ...next, colorScheme: scheme });\n },\n setSafeArea(insets) {\n renderer?.setSafeArea(insets);\n },\n viewportChanged() {\n renderer?.viewportChanged();\n },\n unmount() {\n observer?.disconnect();\n stopScenePhase?.();\n stopKeyboard?.();\n browserHistory?.dispose();\n screen.removeEventListener('sb:color-scheme', onPreferredScheme);\n installTextMeasurer(measurer, true);\n root.unmount();\n renderer?.dispose();\n },\n };\n return mounted;\n}\n","/**\n * `useUndoManager()`: SwiftUI's `@Environment(\\.undoManager)`. The manager\n * keeps a stack of named undo closures with `NSUndoManager`'s rules: a\n * closure registered while undoing goes on the redo stack (so an undo's\n * inverse re-registers as its redo), a new registration drops what could be\n * redone, registrations in one event form one group, and\n * `beginGrouping`/`endGrouping` (or `group`) make one of several events. A\n * registration with a `key` joins the group on top when it has the same key,\n * so a run of keystrokes undoes at once.\n *\n * The stack is the truth: the closures are JavaScript, and `canUndo` must\n * change in the pass that registered them. The system is told what the\n * stack can do and sends its undo and redo here, through the renderer\n * environment's `undoManager` host (Web/src/undo.ts): the keyboard on a\n * page, the window's `UndoManager` natively (its shake, three-finger swipe,\n * keyboard and Edit menu), which mirrors this one.\n */\n\nimport { browserEnvironment } from '@swiftbrowser/web/src/hostRequests';\nimport type { UndoHost, UndoState } from '@swiftbrowser/web/src/undo';\nimport { createContext, useContext, useSyncExternalStore } from 'react';\n\nexport type { UndoHost, UndoState };\n\nexport interface UndoOptions {\n /** Who registered it (`removeAllActions(target)` drops its actions, as `removeAllActions(withTarget:)` does): a document, a view. */\n target?: object;\n /**\n * A registration with the same key as the one before joins its group, so a\n * run of typing in one field (`text:<field>`) undoes at once; an undo, a\n * redo or a registration with another key (or none) ends the run.\n */\n key?: string;\n}\n\nexport interface UndoManagerOptions {\n /** Where the system's undo comes from; the renderer environment's host by default, none for a manager of its own. */\n host?: UndoHost | null;\n /** Closes the group an event opened; the microtask queue by default (the event has ended by then). */\n schedule?: (close: () => void) => void;\n}\n\ninterface Action {\n name: string;\n undo: () => void;\n target: object | undefined;\n}\n\ninterface Group {\n /** The name of what the group undoes, '' when its registrations had none. */\n name: string;\n /** Fixed by `beginGrouping(name)`; otherwise the last registration's. */\n named: boolean;\n actions: Action[];\n key: string | undefined;\n}\n\nconst EMPTY: UndoState = { canUndo: false, canRedo: false, undoActionName: '', redoActionName: '' };\n\nconst defaultSchedule = (close: () => void): void => {\n if (typeof queueMicrotask === 'function') queueMicrotask(close);\n else void Promise.resolve().then(close);\n};\n\nexport class UndoManager {\n /** Whether registrations in one event (one task of the event loop) form one group; true, as `groupsByEvent`. */\n groupsByEvent = true;\n /** How many groups the undo stack keeps; 0 for no limit, as `levelsOfUndo`. */\n levelsOfUndo = 0;\n\n private undoStack: Group[] = [];\n private redoStack: Group[] = [];\n /** The group registrations go in: an explicit group, the event's group, or the inverse of what is being undone or redone. */\n private open: Group | null = null;\n /** How deep `beginGrouping` is; 0 when `open` is the event's group or an inverse. */\n private depth = 0;\n /** Whether `open` is the event's group, which `schedule` closes. */\n private byEvent = false;\n /** The last keyed group closed onto the undo stack, which a registration with its key joins. */\n private coalescing: Group | null = null;\n private undoing = false;\n private redoing = false;\n private snapshot: UndoState = EMPTY;\n private readonly listeners = new Set<() => void>();\n private readonly schedule: (close: () => void) => void;\n private readonly host: UndoHost | null;\n private stopListening: (() => void) | null = null;\n\n constructor(options: UndoManagerOptions = {}) {\n this.schedule = options.schedule ?? defaultSchedule;\n this.host = options.host === undefined ? (browserEnvironment.undoManager ?? null) : options.host;\n if (this.host) {\n this.stopListening = this.host.listen({ undo: () => this.undo(), redo: () => this.redo() });\n this.host.update(this.snapshot);\n }\n }\n\n get canUndo(): boolean {\n return this.undoStack.length > 0;\n }\n\n get canRedo(): boolean {\n return this.redoStack.length > 0;\n }\n\n /** The name of what `undo` takes back ('' for none): \"Move\" for an Edit menu's \"Undo Move\". */\n get undoActionName(): string {\n return this.undoStack[this.undoStack.length - 1]?.name ?? '';\n }\n\n get redoActionName(): string {\n return this.redoStack[this.redoStack.length - 1]?.name ?? '';\n }\n\n get isUndoing(): boolean {\n return this.undoing;\n }\n\n get isRedoing(): boolean {\n return this.redoing;\n }\n\n /** What the stacks can do, one object per change (for `useSyncExternalStore`). */\n get state(): UndoState {\n return this.snapshot;\n }\n\n /**\n * Registers what undoes the change just made, under `name`. Run by `undo`,\n * the closure registers its own inverse the same way, which lands on the\n * redo stack because the manager is undoing.\n */\n registerUndo(name: string, undo: () => void, options: UndoOptions = {}): void {\n const action: Action = { name, undo, target: options.target };\n if (this.undoing || this.redoing) {\n // The inverse of the group being run (`undo` or `redo` opened it), named after that group.\n this.open!.actions.push(action);\n this.changed();\n return;\n }\n this.redoStack = [];\n this.coalescing = this.coalescing && this.undoStack[this.undoStack.length - 1] === this.coalescing ? this.coalescing : null;\n if (this.open) {\n // An explicit group goes on the stack with its first registration (an empty one never does).\n if (!this.undoStack.includes(this.open)) this.push(this.open);\n this.open.actions.push(action);\n if (!this.open.named) this.open.name = name;\n } else if (this.coalescing && options.key !== undefined && this.coalescing.key === options.key) {\n this.coalescing.actions.push(action);\n this.coalescing.name = name;\n } else {\n const group: Group = { name, named: false, actions: [action], key: options.key };\n this.push(group);\n this.coalescing = null;\n if (this.groupsByEvent) {\n this.open = group;\n this.byEvent = true;\n this.schedule(() => {\n if (this.open === group && this.byEvent) this.close();\n });\n } else {\n this.coalescing = group.key !== undefined ? group : null;\n }\n }\n this.changed();\n }\n\n /** Takes back the top group of changes; its inverses become the top of the redo stack. */\n undo(): void {\n this.endOpenGroups();\n const group = this.undoStack.pop();\n if (!group) return;\n this.coalescing = null;\n this.run(group, 'undo');\n }\n\n redo(): void {\n this.endOpenGroups();\n const group = this.redoStack.pop();\n if (!group) return;\n this.run(group, 'redo');\n }\n\n /**\n * Starts a group: every registration until `endGrouping` undoes as one\n * (`beginUndoGrouping`). Nested calls join the outer group. The group is\n * named `name`, else after its last registration.\n */\n beginGrouping(name?: string): void {\n if (this.undoing || this.redoing) return;\n this.depth += 1;\n if (this.depth > 1) return;\n if (this.open) this.close();\n this.open = { name: name ?? '', named: name !== undefined, actions: [], key: undefined };\n this.byEvent = false;\n this.coalescing = null;\n }\n\n /** Ends the group `beginGrouping` started; one that registered nothing is dropped. */\n endGrouping(): void {\n if (this.depth === 0) return;\n this.depth -= 1;\n if (this.depth === 0) this.close();\n }\n\n /** `body` as one group named `name`. */\n group<T>(name: string, body: () => T): T {\n this.beginGrouping(name);\n try {\n return body();\n } finally {\n this.endGrouping();\n }\n }\n\n /** Forgets every registration, or those `target` made (`removeAllActions(withTarget:)`), on both stacks and in the open group. */\n removeAllActions(target?: object): void {\n const mine = (action: Action): boolean => target === undefined || action.target === target;\n const strip = (groups: Group[]): Group[] =>\n groups.filter((group) => {\n group.actions = group.actions.filter((action) => !mine(action));\n return group.actions.length > 0;\n });\n this.undoStack = strip(this.undoStack);\n this.redoStack = strip(this.redoStack);\n if (this.open) this.open.actions = this.open.actions.filter((action) => !mine(action));\n if (this.coalescing && !this.undoStack.includes(this.coalescing)) this.coalescing = null;\n this.changed();\n }\n\n /** Calls `listener` after each change to `state`; returns what stops it. */\n readonly subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n };\n\n /** Stops listening to the host, for a manager made in a test. */\n dispose(): void {\n this.stopListening?.();\n this.stopListening = null;\n }\n\n private push(group: Group): void {\n this.undoStack.push(group);\n if (this.levelsOfUndo > 0 && this.undoStack.length > this.levelsOfUndo) this.undoStack.splice(0, this.undoStack.length - this.levelsOfUndo);\n }\n\n /** Closes `open`; a keyed group on top stays open to its key. */\n private close(): void {\n const group = this.open;\n this.open = null;\n this.byEvent = false;\n if (group && group.key !== undefined && this.undoStack[this.undoStack.length - 1] === group) this.coalescing = group;\n }\n\n private endOpenGroups(): void {\n this.depth = 0;\n if (this.open) this.close();\n }\n\n private run(group: Group, direction: 'undo' | 'redo'): void {\n const inverse: Group = { name: group.name, named: true, actions: [], key: undefined };\n this.open = inverse;\n this.byEvent = false;\n if (direction === 'undo') this.undoing = true;\n else this.redoing = true;\n try {\n for (let i = group.actions.length - 1; i >= 0; i -= 1) group.actions[i]!.undo();\n } finally {\n this.undoing = false;\n this.redoing = false;\n this.open = null;\n if (inverse.actions.length > 0) {\n if (direction === 'undo') this.redoStack.push(inverse);\n else this.push(inverse);\n }\n this.changed();\n }\n }\n\n private changed(): void {\n const next: UndoState = { canUndo: this.canUndo, canRedo: this.canRedo, undoActionName: this.undoActionName, redoActionName: this.redoActionName };\n const last = this.snapshot;\n if (next.canUndo === last.canUndo && next.canRedo === last.canRedo && next.undoActionName === last.undoActionName && next.redoActionName === last.redoActionName) return;\n this.snapshot = next;\n this.host?.update(next);\n for (const listener of [...this.listeners]) listener();\n }\n}\n\n/** A manager for the views below, in place of the page's (an island with a stack of its own, a test). */\nexport const UndoManagerContext = createContext<UndoManager | null>(null);\n\nlet shared: UndoManager | null = null;\n\n/** The page's manager, made on first use and connected to the environment's host. */\nfunction sharedUndoManager(): UndoManager {\n shared ??= new UndoManager();\n return shared;\n}\n\n/**\n * The window's undo manager: `registerUndo(name, undo)` after a change,\n * `undo()`, `redo()`, and `canUndo`, `canRedo`, `undoActionName` and\n * `redoActionName`, which re-render the view as they change.\n */\nexport function useUndoManager(): UndoManager {\n const manager = useContext(UndoManagerContext) ?? sharedUndoManager();\n useSyncExternalStore(\n manager.subscribe,\n () => manager.state,\n () => manager.state,\n );\n return manager;\n}\n","/**\n * React context does not cross a root boundary, and a `Host` (a react-dom\n * root inside the SwiftUI tree) or a `SwiftUIView` (a SwiftUI root inside a\n * react-dom tree) is one. The bridge reads the contexts on the outer side and\n * provides them again on the inner side. This package's own contexts always\n * travel; a component names any others it needs.\n */\n\nimport { createElement, useContext, type Context, type ReactNode } from 'react';\nimport { DismissContext, EnvironmentContext, ViewEnvironmentContext } from './environment';\nimport { NavigationContext } from './navigation-context';\nimport { UndoManagerContext } from './undo';\n\nconst OWN: readonly Context<unknown>[] = [\n EnvironmentContext as Context<unknown>,\n ViewEnvironmentContext as Context<unknown>,\n NavigationContext as Context<unknown>,\n DismissContext as Context<unknown>,\n UndoManagerContext as Context<unknown>,\n];\n\n/**\n * Returns a function that wraps `children` in providers of the current\n * values of this package's contexts and of `contexts`. The list of contexts\n * must not change between renders (each is read with a hook).\n */\nexport function useContextBridge(\n contexts: readonly Context<unknown>[] = [],\n options: { environment?: boolean } = {},\n): (children: ReactNode) => ReactNode {\n // An island is the source of its own device environment (its root\n // provides it), so it bridges everything but that.\n const own = options.environment === false ? OWN.filter((context) => context !== (EnvironmentContext as Context<unknown>)) : OWN;\n const all = [...own, ...contexts];\n // One hook per context, in a stable order: the list is fixed per call site.\n const values = all.map((context) => useContext(context));\n return (children) =>\n all.reduceRight<ReactNode>((inner, context, index) => createElement(context.Provider, { value: values[index] }, inner), children);\n}\n","/**\n * `SwiftUIView`: a SwiftUI tree inside a react-dom app. The element carries\n * the device's design tokens (the `device` class, without its frame) and the\n * renderer draws the tree in it. `fit=\"fill\"` draws in the box the page\n * gives it (give it a height); `fit=\"content\"` makes the island as tall as\n * its content. Navigation stacks and tab views fill the box, so they want\n * `fill`.\n */\n\nimport type { AssetCatalog } from '@swiftbrowser/web/src/assets';\nimport type { ColorScheme, DynamicTypeSize } from '@swiftbrowser/web/src/protocol';\nimport { applyTypeSizeVariables } from '@swiftbrowser/web/src/typography';\nimport { useLayoutEffect, useRef, type CSSProperties, type Context, type ReactNode } from 'react';\nimport { useContextBridge } from './bridge';\nimport { mount, type Mounted } from './mount';\n\nexport interface SwiftUIViewProps {\n children?: ReactNode;\n fit?: 'fill' | 'content';\n colorScheme?: ColorScheme;\n dynamicTypeSize?: DynamicTypeSize;\n /** Contexts of the page the SwiftUI tree reads (this package's own are not needed). */\n contexts?: readonly Context<unknown>[];\n /** The asset catalog manifest for `Image(name:)` and catalog colors (see `mount`). */\n assets?: AssetCatalog;\n /**\n * Insets the views keep clear of, as a device's status bar and home\n * indicator: a navigation bar sits below `top` (its background reaching\n * into it), a list starts below it. A number is the top inset. By default\n * a `fill` island keeps `WINDOW_TOP_INSET` at the top, as SwiftUI keeps its\n * bars off a window's edge where there is no status bar; `content` has none.\n */\n safeArea?: number | Partial<SafeAreaInsets>;\n /**\n * Mirror navigation in the browser's history (the default): a pushed\n * screen, a presented sheet or a moved split-view sidebar selection adds\n * an entry, and the browser's back and edge swipe pop, dismiss or\n * reselect it. The URL is left alone; set paths with\n * `history.replaceState`. `false` for an island in a page whose own router\n * owns the history.\n */\n history?: boolean;\n /**\n * Follow the on-screen keyboard: its height becomes a bottom inset, so a\n * field, a bottom search field or a chat's composer rises above it and a\n * list stops above it, as on iOS, instead of the browser panning the page\n * to the field. On by default for a `fill` island, which fills the layout\n * viewport as a full-screen app; a `content` island in a page leaves the\n * page to the browser.\n */\n keyboard?: boolean;\n /**\n * The Mac's sidebar panel paints its top 44 points in the window's color,\n * behind where macOS draws the window's buttons (`true`, the default);\n * `false` keeps the panel's sidebar fill to its top, as a page has no\n * window buttons there (see `mount`).\n */\n sidebarTitleBar?: boolean;\n className?: string;\n style?: CSSProperties;\n}\n\ninterface SafeAreaInsets {\n top: number;\n leading: number;\n bottom: number;\n trailing: number;\n}\n\n/** The top inset of a `fill` island: a window's bar row clear of its edge. */\nconst WINDOW_TOP_INSET = 10;\n\nexport function insetsOf(safeArea: SwiftUIViewProps['safeArea'], fit: 'fill' | 'content'): SafeAreaInsets {\n const given = typeof safeArea === 'number' ? { top: safeArea } : (safeArea ?? { top: fit === 'fill' ? WINDOW_TOP_INSET : 0 });\n return { top: given.top ?? 0, leading: given.leading ?? 0, bottom: given.bottom ?? 0, trailing: given.trailing ?? 0 };\n}\n\nexport function SwiftUIView({\n children,\n fit = 'fill',\n colorScheme = 'light',\n dynamicTypeSize = 'large',\n contexts,\n assets,\n safeArea,\n history = true,\n keyboard = fit === 'fill',\n sidebarTitleBar = true,\n className,\n style,\n}: SwiftUIViewProps): ReactNode {\n const device = useRef<HTMLDivElement>(null);\n const screen = useRef<HTMLDivElement>(null);\n const mounted = useRef<Mounted | null>(null);\n const bridge = useContextBridge(contexts, { environment: false });\n const tree = bridge(children);\n const latest = useRef(tree);\n latest.current = tree;\n\n useLayoutEffect(() => {\n if (!screen.current) return;\n const instance = mount(screen.current, latest.current, {\n colorScheme,\n dynamicTypeSize,\n safeArea: insetsOf(safeArea, fit),\n contentHeight: fit === 'content',\n history,\n keyboard,\n ...(assets ? { assets } : {}),\n });\n mounted.current = instance;\n return () => {\n mounted.current = null;\n instance.unmount();\n };\n // The environment is updated below; a change of fit, history or keyboard re-mounts.\n }, [fit, history, keyboard]);\n\n // After the mount above, so a new renderer takes it too; a change applies in place.\n useLayoutEffect(() => {\n if (mounted.current) mounted.current.renderer.sidebarTitleBar = sidebarTitleBar;\n }, [sidebarTitleBar, fit, history, keyboard]);\n\n useLayoutEffect(() => {\n mounted.current?.root.render(tree);\n });\n\n const insets = insetsOf(safeArea, fit);\n const insetsKey = `${insets.top},${insets.leading},${insets.bottom},${insets.trailing}`;\n useLayoutEffect(() => {\n mounted.current?.renderer.setSafeArea(insets);\n // Keyed by value: a new object each render is the same insets.\n }, [insetsKey]);\n\n useLayoutEffect(() => {\n if (device.current) applyTypeSizeVariables(device.current, dynamicTypeSize, mounted.current?.renderer.platform);\n mounted.current?.setEnvironment({ colorScheme, dynamicTypeSize });\n }, [colorScheme, dynamicTypeSize]);\n\n const classes = ['device', 'sb-island', className].filter(Boolean).join(' ');\n return (\n <div ref={device} className={classes} data-theme={colorScheme} data-type-size={dynamicTypeSize} data-state=\"ready\" data-sb-fit={fit} style={style}>\n <div className=\"device-screen\">\n <div ref={screen} className=\"screen\" />\n </div>\n </div>\n );\n}\n","/**\n * `Path`: a builder for SVG path data, in SwiftUI's vocabulary. Custom\n * shapes (`Shape` with a `path` function) and `Canvas` drawing take one.\n * Points are rounded to hundredths, as the Swift shim rounds them.\n */\n\nexport interface Point {\n x: number;\n y: number;\n}\n\nexport interface CGRect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\nconst r = (n: number): string => {\n const v = Math.round(n * 100) / 100;\n return Object.is(v, -0) ? '0' : String(v);\n};\n\nexport class Path {\n private readonly parts: string[] = [];\n private current: Point | null = null;\n private start: Point | null = null;\n\n constructor(build?: (path: Path) => void) {\n build?.(this);\n }\n\n /** `Path(rect)` */\n static rect(rect: CGRect): Path {\n return new Path().addRect(rect);\n }\n /** `Path(roundedRect:cornerRadius:)` */\n static roundedRect(rect: CGRect, cornerRadius: number): Path {\n return new Path().addRoundedRect(rect, cornerRadius);\n }\n /** `Path(ellipseIn:)` */\n static ellipse(rect: CGRect): Path {\n return new Path().addEllipse(rect);\n }\n\n move(to: Point): this {\n this.parts.push(`M${r(to.x)} ${r(to.y)}`);\n this.current = to;\n this.start = to;\n return this;\n }\n\n addLine(to: Point): this {\n if (!this.current) return this.move(to);\n this.parts.push(`L${r(to.x)} ${r(to.y)}`);\n this.current = to;\n return this;\n }\n\n addLines(points: readonly Point[]): this {\n points.forEach((point, index) => (index === 0 ? this.move(point) : this.addLine(point)));\n return this;\n }\n\n addQuadCurve(to: Point, control: Point): this {\n if (!this.current) this.move(control);\n this.parts.push(`Q${r(control.x)} ${r(control.y)} ${r(to.x)} ${r(to.y)}`);\n this.current = to;\n return this;\n }\n\n addCurve(to: Point, control1: Point, control2: Point): this {\n if (!this.current) this.move(control1);\n this.parts.push(`C${r(control1.x)} ${r(control1.y)} ${r(control2.x)} ${r(control2.y)} ${r(to.x)} ${r(to.y)}`);\n this.current = to;\n return this;\n }\n\n /**\n * `addArc(center:radius:startAngle:endAngle:clockwise:)`, angles in\n * degrees. As in SwiftUI's flipped coordinates, `clockwise: false` draws\n * clockwise on screen.\n */\n addArc(center: Point, radius: number, startAngle: number, endAngle: number, clockwise: boolean): this {\n const rad = (deg: number): number => (deg * Math.PI) / 180;\n const point = (deg: number): Point => ({ x: center.x + radius * Math.cos(rad(deg)), y: center.y + radius * Math.sin(rad(deg)) });\n const from = point(startAngle);\n if (this.current) this.addLine(from);\n else this.move(from);\n // On screen (y down), SwiftUI's `clockwise: false` sweeps with increasing angles.\n const sweepPositive = !clockwise;\n let delta = endAngle - startAngle;\n if (sweepPositive) while (delta < 0) delta += 360;\n else while (delta > 0) delta -= 360;\n if (Math.abs(delta) >= 360) {\n // A full circle: two half arcs.\n const half = point(startAngle + (sweepPositive ? 180 : -180));\n const flag = sweepPositive ? 1 : 0;\n this.parts.push(`A${r(radius)} ${r(radius)} 0 0 ${flag} ${r(half.x)} ${r(half.y)}`);\n this.parts.push(`A${r(radius)} ${r(radius)} 0 0 ${flag} ${r(from.x)} ${r(from.y)}`);\n this.current = from;\n return this;\n }\n const to = point(startAngle + delta);\n const large = Math.abs(delta) > 180 ? 1 : 0;\n this.parts.push(`A${r(radius)} ${r(radius)} 0 ${large} ${sweepPositive ? 1 : 0} ${r(to.x)} ${r(to.y)}`);\n this.current = to;\n return this;\n }\n\n addRect(rect: CGRect): this {\n this.move({ x: rect.x, y: rect.y });\n this.addLine({ x: rect.x + rect.width, y: rect.y });\n this.addLine({ x: rect.x + rect.width, y: rect.y + rect.height });\n this.addLine({ x: rect.x, y: rect.y + rect.height });\n return this.closeSubpath();\n }\n\n addRoundedRect(rect: CGRect, cornerRadius: number): this {\n const c = Math.max(0, Math.min(cornerRadius, rect.width / 2, rect.height / 2));\n if (c === 0) return this.addRect(rect);\n const { x, y, width: w, height: h } = rect;\n this.move({ x: x + c, y });\n this.addLine({ x: x + w - c, y });\n this.parts.push(`A${r(c)} ${r(c)} 0 0 1 ${r(x + w)} ${r(y + c)}`);\n this.current = { x: x + w, y: y + c };\n this.addLine({ x: x + w, y: y + h - c });\n this.parts.push(`A${r(c)} ${r(c)} 0 0 1 ${r(x + w - c)} ${r(y + h)}`);\n this.current = { x: x + w - c, y: y + h };\n this.addLine({ x: x + c, y: y + h });\n this.parts.push(`A${r(c)} ${r(c)} 0 0 1 ${r(x)} ${r(y + h - c)}`);\n this.current = { x, y: y + h - c };\n this.addLine({ x, y: y + c });\n this.parts.push(`A${r(c)} ${r(c)} 0 0 1 ${r(x + c)} ${r(y)}`);\n this.current = { x: x + c, y };\n return this.closeSubpath();\n }\n\n addEllipse(rect: CGRect): this {\n const rx = rect.width / 2;\n const ry = rect.height / 2;\n const cx = rect.x + rx;\n const cy = rect.y + ry;\n this.move({ x: cx + rx, y: cy });\n this.parts.push(`A${r(rx)} ${r(ry)} 0 0 1 ${r(cx - rx)} ${r(cy)}`);\n this.parts.push(`A${r(rx)} ${r(ry)} 0 0 1 ${r(cx + rx)} ${r(cy)}`);\n this.current = { x: cx + rx, y: cy };\n return this.closeSubpath();\n }\n\n addPath(path: Path): this {\n this.parts.push(path.svg());\n return this;\n }\n\n closeSubpath(): this {\n this.parts.push('Z');\n this.current = this.start;\n return this;\n }\n\n get isEmpty(): boolean {\n return this.parts.length === 0;\n }\n\n /** The SVG path data. */\n svg(): string {\n return this.parts.join('');\n }\n\n toString(): string {\n return this.svg();\n }\n}\n","/**\n * Attributed text, SwiftUI's `AttributedString` as the rich `TextEditor`\n * edits it (`TextEditor(text: $attributed, selection: $selection)`, iOS 26):\n * runs of text, each with its own weight, slant, lines and color. Plain\n * objects, so the text saves as JSON; the functions here are what an edit\n * in the editor does to it.\n */\n\nimport type { FontDesign, FontWeight, TextRun } from '@swiftbrowser/web/src/protocol';\nimport { color, type ColorValue } from './values';\n\n/** A run's own font over the editor's (`AttributedString`'s `font`): `Font.system(size:weight:design:)`'s parts, each optional. */\nexport interface RunFont {\n size?: number;\n weight?: FontWeight;\n design?: FontDesign;\n}\n\nexport interface AttributedRun {\n text: string;\n bold?: boolean;\n italic?: boolean;\n underline?: boolean;\n strikethrough?: boolean;\n /** The run's color, over the editor's foreground. */\n foregroundColor?: ColorValue;\n /** A color behind the run's glyphs (`backgroundColor`): a find highlight, say. */\n backgroundColor?: ColorValue;\n /** The run's size, weight or design over the editor's font (`bold` is the weight `bold` when the font names none). */\n font?: RunFont;\n}\n\nexport type AttributedText = readonly AttributedRun[];\n\n/** A range of an editor's text in UTF-16 offsets (JavaScript's string indices); `start === end` is the caret. */\nexport interface TextSelection {\n start: number;\n end: number;\n}\n\n/** A run's attributes without its text. */\nexport type TextAttributes = Omit<AttributedRun, 'text'>;\n\nconst plain = (text: AttributedText): string => text.map((run) => run.text).join('');\n\nfunction attributesOf(run: AttributedRun | undefined): TextAttributes {\n if (!run) return {};\n const { text: _text, ...attributes } = run;\n return attributes;\n}\n\n/** Whether two runs look the same (an absent flag is false). */\nfunction alike(a: TextAttributes, b: TextAttributes): boolean {\n return (\n !a.bold === !b.bold &&\n !a.italic === !b.italic &&\n !a.underline === !b.underline &&\n !a.strikethrough === !b.strikethrough &&\n JSON.stringify(a.foregroundColor ?? null) === JSON.stringify(b.foregroundColor ?? null) &&\n JSON.stringify(a.backgroundColor ?? null) === JSON.stringify(b.backgroundColor ?? null) &&\n JSON.stringify(runFont(a.font) ?? null) === JSON.stringify(runFont(b.font) ?? null)\n );\n}\n\n/** A run font with its fields in one order and none unset, or undefined when it says nothing. */\nfunction runFont(font: RunFont | undefined): RunFont | undefined {\n if (!font) return undefined;\n const out: RunFont = {};\n if (typeof font.size === 'number' && Number.isFinite(font.size) && font.size > 0) out.size = font.size;\n if (font.weight) out.weight = font.weight;\n if (font.design) out.design = font.design;\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/** The same text with no empty runs and no two alike side by side. */\nfunction normalized(text: AttributedText): AttributedText {\n const runs: AttributedRun[] = [];\n for (const run of text) {\n if (!run.text) continue;\n const last = runs[runs.length - 1];\n if (last && alike(last, run)) runs[runs.length - 1] = { ...last, text: last.text + run.text };\n else runs.push(run);\n }\n return runs;\n}\n\n/** The runs between two offsets, cut where they fall. */\nfunction slice(text: AttributedText, start: number, end = Infinity): AttributedText {\n const runs: AttributedRun[] = [];\n let at = 0;\n for (const run of text) {\n const from = Math.max(start, at);\n const to = Math.min(end, at + run.text.length);\n if (from < to) runs.push({ ...run, text: run.text.slice(from - at, to - at) });\n at += run.text.length;\n }\n return runs;\n}\n\n/** The attributes of the character at `offset` (the last one's past the end; none in an empty text). */\nfunction attributesAt(text: AttributedText, offset: number): TextAttributes {\n let at = 0;\n for (const run of text) {\n if (offset < at + run.text.length) return attributesOf(run);\n at += run.text.length;\n }\n return attributesOf([...text].reverse().find((run) => run.text.length > 0));\n}\n\n/**\n * `text` changed to read `next`, as a keystroke, a paste or a deletion in\n * the editor changes it: the start and end that did not change keep their\n * runs, and what was typed takes the attributes of what it replaced, else\n * of the character before it (the first character's, typed at the start).\n */\nfunction replacingCharacters(text: AttributedText, next: string): AttributedText {\n const old = plain(text);\n if (old === next) return text;\n let head = 0;\n const shorter = Math.min(old.length, next.length);\n while (head < shorter && old[head] === next[head]) head++;\n let tail = 0;\n while (tail < shorter - head && old[old.length - 1 - tail] === next[next.length - 1 - tail]) tail++;\n const removedEnd = old.length - tail;\n const typed = next.slice(head, next.length - tail);\n const attributes = attributesAt(text, removedEnd > head || head === 0 ? head : head - 1);\n return normalized([...slice(text, 0, head), { ...attributes, text: typed }, ...slice(text, removedEnd)]);\n}\n\n/** `text` with `change` over the characters between `start` and `end`. */\nfunction settingAttributes(text: AttributedText, start: number, end: number, change: TextAttributes): AttributedText {\n const inside = slice(text, start, end).map((run) => ({ ...run, ...change }));\n return normalized([...slice(text, 0, start), ...inside, ...slice(text, end)]);\n}\n\n/** Whether every character between `start` and `end` has `key` on (false for an empty range). */\nfunction every(text: AttributedText, start: number, end: number, key: 'bold' | 'italic' | 'underline' | 'strikethrough'): boolean {\n const inside = slice(text, start, end);\n return inside.length > 0 && inside.every((run) => run[key] === true);\n}\n\n/** The functions over attributed text, as `AttributedString`'s methods. */\nexport const AttributedText = {\n plain,\n normalized,\n slice,\n attributesAt,\n replacingCharacters,\n settingAttributes,\n every,\n /** A text of one run. */\n of: (text: string, attributes: TextAttributes = {}): AttributedText => normalized([{ ...attributes, text }]),\n};\n\n/** The weights `fromProtocolRuns` reads as bold (the native editor names the system's Bold `bold`; an app may have sent a heavier one). */\nconst BOLD_WEIGHTS = new Set(['semibold', 'bold', 'heavy', 'black']);\n\n/**\n * The text the protocol's runs stand for (a `runs` event: the native\n * editor's own Bold, Italic or Underline over the text), `protocolRuns`\n * read back: a bold weight is `bold`, a line is on, a color is the run's,\n * and a run's size, design and other weight are its `font`.\n */\nexport function fromProtocolRuns(runs: readonly TextRun[]): AttributedText {\n return normalized(\n runs.map((run) => {\n const out: AttributedRun = { text: run.text ?? '' };\n const font = (run.font ?? {}) as { weight?: unknown; size?: unknown; design?: unknown };\n const bold = typeof font.weight === 'string' && BOLD_WEIGHTS.has(font.weight);\n if (bold) out.bold = true;\n const own = runFont({\n ...(typeof font.size === 'number' ? { size: font.size } : {}),\n ...(typeof font.weight === 'string' && !bold ? { weight: font.weight as FontWeight } : {}),\n ...(typeof font.design === 'string' ? { design: font.design as FontDesign } : {}),\n });\n if (own) out.font = own;\n if (run.italic) out.italic = true;\n if (run.underline) out.underline = true;\n if (run.strikethrough) out.strikethrough = true;\n if (run.foreground !== undefined) out.foregroundColor = run.foreground as ColorValue;\n if (run.background !== undefined) out.backgroundColor = run.background as ColorValue;\n return out;\n }),\n );\n}\n\n/** The protocol's runs for a text: a run's font over the editor's (bold is the weight `bold`), its lines and colors. */\nexport function protocolRuns(text: AttributedText): TextRun[] {\n return text.map((run) => {\n const out: TextRun = { text: run.text };\n const font = { ...(runFont(run.font) ?? {}) };\n if (run.bold && !font.weight) font.weight = 'bold';\n if (Object.keys(font).length > 0) out.font = font;\n if (run.italic) out.italic = true;\n if (run.underline) out.underline = {};\n if (run.strikethrough) out.strikethrough = {};\n if (run.foregroundColor !== undefined) out.foreground = color(run.foregroundColor);\n if (run.backgroundColor !== undefined) out.background = color(run.backgroundColor);\n return out;\n });\n}\n","/**\n * `useAudioRecorder()`: the microphone, as an iOS app records with\n * `AVAudioRecorder`. `record()` asks for the microphone and starts; while it\n * records the hook meters the input (`levels`, one 0…1 level per tick, for a\n * waveform) and counts `time`; `stop()` resolves with the recording's URL\n * (a `data:` URL on a page, a file natively) to play with `useAVPlayer`;\n * `trim()` makes a new recording out of parts of one. The page records with\n * `MediaRecorder` and cuts with the Web Audio API (Web/src/audioRecorder.ts);\n * the native app answers with `AVAudioRecorder` and `AVAssetExportSession`\n * (AudioRecorderBridge.swift).\n */\n\nimport type { AudioRange, AudioRecording } from '@swiftbrowser/web/src/audioRecorder';\nimport { browserEnvironment } from '@swiftbrowser/web/src/hostRequests';\nimport { useCallback, useEffect, useRef, useState } from 'react';\n\nexport type { AudioRange, AudioRecording };\n\nexport type AudioRecorderStatus = 'idle' | 'starting' | 'recording' | 'paused' | 'stopping';\n\nexport interface AudioRecorder {\n /** Whether this page or app can record at all. */\n available: boolean;\n status: AudioRecorderStatus;\n /** Seconds recorded so far (it holds while paused). */\n time: number;\n /** The input's level at each tick of this recording (0 silent … 1 loud), oldest first. */\n levels: readonly number[];\n /** Why the last call failed (`permission: …` when the microphone was refused), or null. */\n error: string | null;\n record(): Promise<void>;\n pause(): Promise<void>;\n resume(): Promise<void>;\n /** Ends the recording and resolves with it, or null when there was none. */\n stop(): Promise<AudioRecording | null>;\n /** Ends the recording and keeps nothing. */\n cancel(): Promise<void>;\n /** Deletes a recording `stop` made before (its file, natively), when the app deletes it. */\n discard(url: string): Promise<void>;\n /**\n * A new recording made of the parts of `url` in `keep` (seconds, in\n * order, concatenated): `[{ start, end }]` trims to that range, two parts\n * around a range delete it. Resolves with the new recording (a `data:` URL\n * on a page, a new file natively); the original is left as it was (the app\n * discards it when it no longer wants it). Rejects with `unsupported: …`\n * where the host cannot cut audio.\n */\n trim(url: string, keep: readonly { start: number; end: number }[]): Promise<AudioRecording>;\n}\n\nexport interface AudioRecorderOptions {\n /** Milliseconds between meter readings (50: twenty a second). */\n meterInterval?: number;\n}\n\nexport function useAudioRecorder(options: AudioRecorderOptions = {}): AudioRecorder {\n const interval = options.meterInterval ?? 50;\n const host = browserEnvironment.audioRecorder;\n const [status, setStatus] = useState<AudioRecorderStatus>('idle');\n const [time, setTime] = useState(0);\n const [levels, setLevels] = useState<readonly number[]>([]);\n const [error, setError] = useState<string | null>(null);\n const statusRef = useRef(status);\n statusRef.current = status;\n\n const fail = (reason: unknown): void => setError(reason instanceof Error ? reason.message : String(reason));\n\n // Meter while recording; one reading at a time, so a slow host never queues them.\n useEffect(() => {\n if (status !== 'recording' || !host) return;\n let reading = false;\n let live = true;\n const timer = setInterval(() => {\n if (reading) return;\n reading = true;\n host\n .meter()\n .then((meter) => {\n if (!live) return;\n setTime(meter.time);\n setLevels((previous) => [...previous, meter.level]);\n })\n .catch(() => undefined)\n .finally(() => {\n reading = false;\n });\n }, interval);\n return () => {\n live = false;\n clearInterval(timer);\n };\n }, [status, host, interval]);\n\n // A recording still going when the view goes is cancelled.\n useEffect(\n () => () => {\n if (statusRef.current !== 'idle') void host?.cancel().catch(() => undefined);\n },\n [host],\n );\n\n const record = useCallback(async (): Promise<void> => {\n if (!host) {\n setError('unsupported: this page cannot record');\n return;\n }\n if (statusRef.current !== 'idle') return;\n setError(null);\n setTime(0);\n setLevels([]);\n setStatus('starting');\n try {\n await host.start();\n setStatus('recording');\n } catch (reason) {\n fail(reason);\n setStatus('idle');\n }\n }, [host]);\n\n const pause = useCallback(async (): Promise<void> => {\n if (!host || statusRef.current !== 'recording') return;\n await host.pause().catch(fail);\n setStatus('paused');\n }, [host]);\n\n const resume = useCallback(async (): Promise<void> => {\n if (!host || statusRef.current !== 'paused') return;\n await host.resume().catch(fail);\n setStatus('recording');\n }, [host]);\n\n const stop = useCallback(async (): Promise<AudioRecording | null> => {\n if (!host || (statusRef.current !== 'recording' && statusRef.current !== 'paused')) return null;\n setStatus('stopping');\n try {\n const recording = await host.stop();\n setTime(recording.duration);\n return recording;\n } catch (reason) {\n fail(reason);\n return null;\n } finally {\n setStatus('idle');\n }\n }, [host]);\n\n const cancel = useCallback(async (): Promise<void> => {\n if (!host || statusRef.current === 'idle') return;\n await host.cancel().catch(fail);\n setStatus('idle');\n setTime(0);\n setLevels([]);\n }, [host]);\n\n const discard = useCallback(async (url: string): Promise<void> => {\n await host?.discard(url).catch(fail);\n }, [host]);\n\n // The cut needs no status: it reads one recording and writes another while the recorder does as it was.\n const trim = useCallback(\n async (url: string, keep: readonly AudioRange[]): Promise<AudioRecording> => {\n if (!host) throw new Error('unsupported: this page cannot cut audio');\n try {\n return await host.trim(url, keep);\n } catch (reason) {\n fail(reason);\n throw reason;\n }\n },\n [host],\n );\n\n return { available: host !== undefined, status, time, levels, error, record, pause, resume, stop, cancel, discard, trim };\n}\n","/**\n * AVFoundation's assets, as an iOS app edits video: `CMTime` and\n * `CMTimeRange`; `AVURLAsset` (`load('duration')`, `load('tracks')`,\n * `loadTracks(withMediaType)`); `AVAssetImageGenerator` (a still at a time,\n * for thumbnails and filmstrips); `AVMutableComposition` (parts of assets\n * placed in order: trims, cuts, joins); and `AVAssetExportSession` (an\n * asset or a composition written as a file, with a preset and a\n * `timeRange`). The host does the work (`browserEnvironment.avAsset`): the\n * page with WebCodecs (Web/src/avAsset.ts), the native app with\n * AVFoundation itself (AVAssetBridge.swift). A still or an export is a URL\n * an `Image`, `AsyncImage` or `VideoPlayer` shows (a `blob:` URL on a page, a\n * file natively), or the app's own `outputURL`.\n */\n\nimport { browserEnvironment } from '@swiftbrowser/web/src/hostRequests';\nimport type { AssetExportResult, AssetFileType, AssetInfo, AssetSegment, AVAssetHost } from '@swiftbrowser/web/src/avAsset';\n\nfunction host(): AVAssetHost {\n const found = browserEnvironment.avAsset;\n if (!found) throw new Error('unsupported: this page cannot read or write video');\n return found;\n}\n\n// ---------------------------------------------------------------------------\n// CMTime, CMTimeRange\n// ---------------------------------------------------------------------------\n\n/** `CMTime`: a time as `value / timescale` seconds (600 is the usual video timescale). */\nexport class CMTime {\n static readonly zero = new CMTime(0, 1);\n static readonly invalid = new CMTime(0, 0);\n static readonly positiveInfinity = new CMTime(Infinity, 1);\n\n constructor(\n readonly value: number,\n readonly timescale: number,\n ) {}\n\n /** `CMTime(value:timescale:)`. */\n static make(value: number, timescale: number): CMTime {\n return new CMTime(value, timescale);\n }\n\n /** `CMTime(seconds:preferredTimescale:)`: rounded to the timescale. */\n static seconds(seconds: number, preferredTimescale = 600): CMTime {\n if (!Number.isFinite(seconds)) return seconds > 0 ? CMTime.positiveInfinity : CMTime.invalid;\n return new CMTime(Math.round(seconds * preferredTimescale), preferredTimescale);\n }\n\n get isValid(): boolean {\n return this.timescale > 0;\n }\n\n /** `CMTimeGetSeconds`. */\n get seconds(): number {\n return this.timescale > 0 ? this.value / this.timescale : Number.NaN;\n }\n\n add(other: CMTime): CMTime {\n return CMTime.seconds(this.seconds + other.seconds, Math.max(this.timescale, other.timescale, 1));\n }\n\n subtract(other: CMTime): CMTime {\n return CMTime.seconds(this.seconds - other.seconds, Math.max(this.timescale, other.timescale, 1));\n }\n\n /** `CMTimeCompare`: -1, 0 or 1. */\n compare(other: CMTime): -1 | 0 | 1 {\n const a = this.seconds;\n const b = other.seconds;\n return a < b ? -1 : a > b ? 1 : 0;\n }\n\n static minimum(a: CMTime, b: CMTime): CMTime {\n return a.compare(b) <= 0 ? a : b;\n }\n\n static maximum(a: CMTime, b: CMTime): CMTime {\n return a.compare(b) >= 0 ? a : b;\n }\n}\n\n/** `CMTimeRange`: from `start`, `duration` long. */\nexport class CMTimeRange {\n static readonly zero = new CMTimeRange(CMTime.zero, CMTime.zero);\n\n constructor(\n readonly start: CMTime,\n readonly duration: CMTime,\n ) {}\n\n /** `CMTimeRange(start:end:)`. */\n static fromTo(start: CMTime, end: CMTime): CMTimeRange {\n return new CMTimeRange(start, CMTime.maximum(end.subtract(start), CMTime.zero));\n }\n\n /** `CMTimeRange(start:duration:)` in seconds. */\n static seconds(start: number, duration: number, preferredTimescale = 600): CMTimeRange {\n return new CMTimeRange(CMTime.seconds(start, preferredTimescale), CMTime.seconds(duration, preferredTimescale));\n }\n\n get end(): CMTime {\n return this.start.add(this.duration);\n }\n\n get isEmpty(): boolean {\n return this.duration.seconds <= 0;\n }\n\n containsTime(time: CMTime): boolean {\n return time.compare(this.start) >= 0 && time.compare(this.end) < 0;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Assets\n// ---------------------------------------------------------------------------\n\n/** `AVMediaType`. */\nexport const AVMediaType = { video: 'vide', audio: 'soun' } as const;\nexport type AVMediaType = (typeof AVMediaType)[keyof typeof AVMediaType];\n\n/** `AVAssetTrack`: one of an asset's tracks. */\nexport class AVAssetTrack {\n constructor(\n readonly trackID: number,\n readonly mediaType: AVMediaType,\n /** The display size (its rotation applied), 0 × 0 for audio. */\n readonly naturalSize: { width: number; height: number },\n readonly nominalFrameRate: number,\n readonly timeRange: CMTimeRange,\n /** The codec (`avc`, `hevc`, `vp9`, `aac`, `opus` …), or null when unknown. */\n readonly codec: string | null,\n ) {}\n}\n\n/** What `load` answers for each key, as `try await asset.load(.duration)` does. */\nexport interface AVAssetProperties {\n duration: CMTime;\n tracks: AVAssetTrack[];\n naturalSize: { width: number; height: number };\n isPlayable: boolean;\n isExportable: boolean;\n}\n\n/** `AVAsset`: media to read, play and write; an `AVURLAsset` or an `AVMutableComposition`. */\nexport abstract class AVAsset {\n /** The parts of files this asset is made of, in order (an `AVURLAsset` is one whole file). */\n protected abstract segments(): Promise<AssetSegment[]>;\n /** @internal */\n segmentsForExport(): Promise<AssetSegment[]> {\n return this.segments();\n }\n abstract load<K extends keyof AVAssetProperties>(key: K): Promise<AVAssetProperties[K]>;\n\n /** `loadTracks(withMediaType:)`. */\n async loadTracks(mediaType: AVMediaType): Promise<AVAssetTrack[]> {\n return (await this.load('tracks')).filter((track) => track.mediaType === mediaType);\n }\n}\n\nconst tracksOf = (info: AssetInfo): AVAssetTrack[] =>\n info.tracks.map(\n (t) =>\n new AVAssetTrack(\n t.trackID,\n t.mediaType === 'video' ? AVMediaType.video : AVMediaType.audio,\n t.naturalSize,\n t.nominalFrameRate,\n CMTimeRange.seconds(t.timeRange.start, t.timeRange.duration),\n t.codec,\n ),\n );\n\n/** `AVURLAsset(url:)`: the media at a URL (a file of the app's, a `blob:`, `data:` or `http(s):` URL). */\nexport class AVURLAsset extends AVAsset {\n private info: Promise<AssetInfo> | null = null;\n\n constructor(readonly url: string) {\n super();\n }\n\n private loaded(): Promise<AssetInfo> {\n if (!this.info) {\n this.info = host().load(this.url);\n // A failed load is tried again on the next `load`.\n this.info.catch(() => {\n this.info = null;\n });\n }\n return this.info;\n }\n\n protected async segments(): Promise<AssetSegment[]> {\n return [{ url: this.url, start: 0, end: (await this.loaded()).duration }];\n }\n\n async load<K extends keyof AVAssetProperties>(key: K): Promise<AVAssetProperties[K]> {\n const info = await this.loaded();\n const values: AVAssetProperties = {\n duration: CMTime.seconds(info.duration),\n tracks: tracksOf(info),\n naturalSize: info.naturalSize,\n isPlayable: info.tracks.length > 0,\n isExportable: info.tracks.length > 0,\n };\n return values[key];\n }\n}\n\n/** One part of a composition: `asset`'s media in `range`, placed at `at`. */\ninterface CompositionPart {\n asset: AVURLAsset;\n range: CMTimeRange;\n}\n\n/**\n * `AVMutableComposition`: parts of assets placed one after another, as a\n * timeline editor cuts and joins them. `insertTimeRange(_:of:at:)` places a\n * part at a time (splitting the part already there), `removeTimeRange(_:)`\n * cuts a range out (the rest closes up), and the composition plays nowhere\n * itself: export it (`AVAssetExportSession`) to watch or keep it.\n */\nexport class AVMutableComposition extends AVAsset {\n private parts: CompositionPart[] = [];\n\n /** The composition's length. */\n get duration(): CMTime {\n return CMTime.seconds(this.parts.reduce((sum, part) => sum + part.range.duration.seconds, 0));\n }\n\n /** `insertTimeRange(_:of:at:)`: `range` of `asset` (an `AVURLAsset`, or another composition's parts) placed at `at`. */\n async insertTimeRange(range: CMTimeRange, asset: AVAsset, at: CMTime): Promise<void> {\n const inserted: CompositionPart[] = [];\n if (asset instanceof AVURLAsset) {\n const length = (await asset.load('duration')).seconds;\n const start = Math.max(0, range.start.seconds);\n const end = Math.min(length, range.end.seconds);\n if (end - start > 1e-3) inserted.push({ asset, range: CMTimeRange.seconds(start, end - start) });\n } else if (asset instanceof AVMutableComposition) {\n inserted.push(...asset.partsIn(range.start.seconds, range.end.seconds));\n } else {\n throw new Error('unsupported: only an AVURLAsset or an AVMutableComposition can be inserted');\n }\n const time = Math.max(0, Math.min(at.seconds, this.duration.seconds));\n const [before, after] = this.splitAt(time);\n this.parts = [...before, ...inserted, ...after];\n }\n\n /** `removeTimeRange(_:)`: the media in `range` cut out, the rest closing up. */\n removeTimeRange(range: CMTimeRange): void {\n const [before] = this.splitAt(range.start.seconds);\n const [, after] = this.splitAt(range.end.seconds);\n this.parts = [...before, ...after];\n }\n\n /** The parts' media from `start` to `end` of the composition's timeline. */\n private partsIn(start: number, end: number): CompositionPart[] {\n const [, from] = this.splitAt(start);\n const out: CompositionPart[] = [];\n let cursor = start;\n for (const part of from) {\n if (cursor >= end) break;\n const take = Math.min(part.range.duration.seconds, end - cursor);\n if (take > 1e-3) out.push({ asset: part.asset, range: CMTimeRange.seconds(part.range.start.seconds, take) });\n cursor += take;\n }\n return out;\n }\n\n /** The parts before `time` and from it, a part across it split in two. */\n private splitAt(time: number): [CompositionPart[], CompositionPart[]] {\n const before: CompositionPart[] = [];\n const after: CompositionPart[] = [];\n let cursor = 0;\n for (const part of this.parts) {\n const length = part.range.duration.seconds;\n const start = part.range.start.seconds;\n if (cursor + length <= time + 1e-9) before.push(part);\n else if (cursor >= time - 1e-9) after.push(part);\n else {\n const head = time - cursor;\n before.push({ asset: part.asset, range: CMTimeRange.seconds(start, head) });\n after.push({ asset: part.asset, range: CMTimeRange.seconds(start + head, length - head) });\n }\n cursor += length;\n }\n return [before, after];\n }\n\n protected async segments(): Promise<AssetSegment[]> {\n return this.parts.map((part) => ({ url: part.asset.url, start: part.range.start.seconds, end: part.range.end.seconds }));\n }\n\n async load<K extends keyof AVAssetProperties>(key: K): Promise<AVAssetProperties[K]> {\n const first = this.parts[0]?.asset;\n const tracks = first ? await first.load('tracks') : [];\n const values: AVAssetProperties = {\n duration: this.duration,\n tracks: tracks.map((t) => new AVAssetTrack(t.trackID, t.mediaType, t.naturalSize, t.nominalFrameRate, new CMTimeRange(CMTime.zero, this.duration), t.codec)),\n naturalSize: first ? await first.load('naturalSize') : { width: 0, height: 0 },\n isPlayable: this.parts.length > 0,\n isExportable: this.parts.length > 0,\n };\n return values[key];\n }\n}\n\n// ---------------------------------------------------------------------------\n// Image generation\n// ---------------------------------------------------------------------------\n\n/** A still `AVAssetImageGenerator` made: a URL an `Image` or `AsyncImage` shows, the time of the frame drawn, and its size. */\nexport interface AVAssetImage {\n image: string;\n actualTime: CMTime;\n width: number;\n height: number;\n}\n\n/**\n * `AVAssetImageGenerator(asset:)`: stills of a video, for a thumbnail or a\n * trim editor's filmstrip. `maximumSize` bounds them (aspect kept; 0 on an\n * axis leaves it open); `image(at:)` answers the frame at (or nearest\n * before) a time; `images(for:)` one after another.\n */\nexport class AVAssetImageGenerator {\n maximumSize: { width: number; height: number } = { width: 0, height: 0 };\n /** Stills come upright (the track's rotation applied), as with `appliesPreferredTrackTransform = true`. */\n appliesPreferredTrackTransform = true;\n private readonly made: string[] = [];\n\n constructor(readonly asset: AVAsset) {}\n\n /** The file and the time in it that `time` on the asset's timeline falls on (a composition's part). */\n private async source(time: number): Promise<{ url: string; time: number }> {\n let cursor = 0;\n const segments = await this.asset.segmentsForExport();\n for (const segment of segments) {\n const length = segment.end - segment.start;\n if (time < cursor + length || segment === segments[segments.length - 1]) return { url: segment.url, time: segment.start + Math.max(0, Math.min(length, time - cursor)) };\n cursor += length;\n }\n throw new Error('empty: the asset has no media');\n }\n\n /** `image(at:)`: the still at `time`. */\n async image(at: CMTime): Promise<AVAssetImage> {\n const { url, time } = await this.source(Math.max(0, at.seconds));\n const options = {\n ...(this.maximumSize.width > 0 ? { maxWidth: this.maximumSize.width } : {}),\n ...(this.maximumSize.height > 0 ? { maxHeight: this.maximumSize.height } : {}),\n };\n const still = await host().image(url, time, options);\n this.made.push(still.url);\n return { image: still.url, actualTime: CMTime.seconds(at.seconds + (still.actualTime - time)), width: still.width, height: still.height };\n }\n\n /** `images(for:)`: a still for each time, in turn. */\n async *images(times: readonly CMTime[]): AsyncGenerator<AVAssetImage & { requestedTime: CMTime }> {\n for (const time of times) yield { ...(await this.image(time)), requestedTime: time };\n }\n\n /** Lets go of the stills this generator made (their `blob:` URLs on a page). */\n async release(): Promise<void> {\n const urls = this.made.splice(0);\n await Promise.all(urls.map((url) => host().release(url)));\n }\n}\n\n// ---------------------------------------------------------------------------\n// Export\n// ---------------------------------------------------------------------------\n\n/** `AVFileType` (and WebM, which a page writes and AVFoundation does not). */\nexport const AVFileType = { mp4: 'public.mpeg-4', mov: 'com.apple.quicktime-movie', m4v: 'com.apple.m4v-video', webm: 'org.webmproject.webm' } as const;\nexport type AVFileType = (typeof AVFileType)[keyof typeof AVFileType];\n\nconst FILE_TYPES: Record<AVFileType, AssetFileType> = {\n 'public.mpeg-4': 'mp4',\n 'com.apple.m4v-video': 'mp4',\n 'com.apple.quicktime-movie': 'mov',\n 'org.webmproject.webm': 'webm',\n};\n\nexport const AVAssetExportPresetPassthrough = 'AVAssetExportPresetPassthrough';\nexport const AVAssetExportPresetHighestQuality = 'AVAssetExportPresetHighestQuality';\nexport const AVAssetExportPresetMediumQuality = 'AVAssetExportPresetMediumQuality';\nexport const AVAssetExportPresetLowQuality = 'AVAssetExportPresetLowQuality';\nexport const AVAssetExportPreset640x480 = 'AVAssetExportPreset640x480';\nexport const AVAssetExportPreset960x540 = 'AVAssetExportPreset960x540';\nexport const AVAssetExportPreset1280x720 = 'AVAssetExportPreset1280x720';\nexport const AVAssetExportPreset1920x1080 = 'AVAssetExportPreset1920x1080';\nexport const AVAssetExportPreset3840x2160 = 'AVAssetExportPreset3840x2160';\n\n/** `AVAssetExportSession.Status`. */\nexport type AVAssetExportSessionStatus = 'unknown' | 'waiting' | 'exporting' | 'completed' | 'failed' | 'cancelled';\n\nlet exports = 0;\n\n/**\n * `AVAssetExportSession(asset:presetName:)`: an asset (or a composition)\n * written as one file. `AVAssetExportPresetPassthrough` copies the media,\n * its cuts on key frames; the other presets re-encode it, cutting exactly,\n * fitted to the preset's size. `timeRange` keeps only that part (a trim);\n * `outputURL` is the app's file to write (else the host makes one, which\n * `export()` answers); `outputFileType` the container. While it runs,\n * `progress` goes 0 to 1 (`onProgress` hears it); `cancelExport()` stops it.\n */\nexport class AVAssetExportSession {\n outputURL: string | null = null;\n outputFileType: AVFileType = AVFileType.mp4;\n timeRange: CMTimeRange | null = null;\n status: AVAssetExportSessionStatus = 'unknown';\n progress = 0;\n error: Error | null = null;\n /** Heard as `progress` changes (a few times a second). */\n onProgress: ((progress: number) => void) | null = null;\n /** The written file's length and MIME type, once completed. */\n result: Omit<AssetExportResult, 'url'> | null = null;\n private readonly id = `export-${++exports}`;\n\n constructor(\n readonly asset: AVAsset,\n readonly presetName: string,\n ) {}\n\n /** `AVAssetExportSession.allExportPresets()`. */\n static allExportPresets(): string[] {\n return [\n AVAssetExportPresetPassthrough,\n AVAssetExportPresetHighestQuality,\n AVAssetExportPresetMediumQuality,\n AVAssetExportPresetLowQuality,\n AVAssetExportPreset640x480,\n AVAssetExportPreset960x540,\n AVAssetExportPreset1280x720,\n AVAssetExportPreset1920x1080,\n AVAssetExportPreset3840x2160,\n ];\n }\n\n /** The asset's parts, cut to `timeRange` when it is set. */\n private async parts(): Promise<AssetSegment[]> {\n const all = await this.asset.segmentsForExport();\n if (!this.timeRange) return all;\n const from = this.timeRange.start.seconds;\n const to = this.timeRange.end.seconds;\n const out: AssetSegment[] = [];\n let cursor = 0;\n for (const segment of all) {\n const length = segment.end - segment.start;\n const start = Math.max(from, cursor);\n const end = Math.min(to, cursor + length);\n if (end - start > 1e-3) out.push({ url: segment.url, start: segment.start + (start - cursor), end: segment.start + (end - cursor) });\n cursor += length;\n }\n return out;\n }\n\n /** `export()`: writes the file and answers its URL (also `outputURL`); rejects with why it could not. */\n async export(): Promise<string> {\n if (this.status === 'exporting') throw new Error('busy: already exporting');\n this.status = 'exporting';\n this.error = null;\n this.setProgress(0);\n const assets = host();\n const ticker = setInterval(() => {\n void assets.progress(this.id).then((p) => this.status === 'exporting' && this.setProgress(p));\n }, 200);\n try {\n const result = await assets.export(this.id, {\n segments: await this.parts(),\n preset: this.presetName,\n fileType: FILE_TYPES[this.outputFileType] ?? 'mp4',\n ...(this.outputURL ? { outputURL: this.outputURL } : {}),\n });\n this.outputURL = result.url;\n this.result = { duration: result.duration, type: result.type };\n this.status = 'completed';\n this.setProgress(1);\n return result.url;\n } catch (reason) {\n const error = reason instanceof Error ? reason : new Error(String(reason));\n this.error = error;\n this.status = error.message.startsWith('cancelled') ? 'cancelled' : 'failed';\n throw error;\n } finally {\n clearInterval(ticker);\n }\n }\n\n /** `cancelExport()`. */\n cancelExport(): void {\n if (this.status !== 'exporting') return;\n void host().cancel(this.id);\n }\n\n private setProgress(progress: number): void {\n if (progress === this.progress) return;\n this.progress = progress;\n this.onProgress?.(progress);\n }\n}\n","/**\n * `useVideoRecorder()`: the camera, as an iOS app records video with an\n * `AVCaptureSession` and a movie file output. `open()` asks for the camera\n * and the microphone and starts the live picture, which `CameraPreview`\n * shows; `record()` records it and `time` counts; `stop()` resolves with\n * the recording (a URL to play with `useAVPlayer`, its length, type and\n * size) and leaves the camera open for the next; `close()` lets the camera\n * go (as leaving the view does). The page records with `getUserMedia` and\n * `MediaRecorder` (Web/src/videoRecorder.ts) into a `blob:` URL; the native\n * app with an `AVCaptureSession` (VideoRecorderBridge.swift) into a\n * QuickTime file in Documents/Recordings.\n */\n\nimport type { CameraFacing, VideoRecording } from '@swiftbrowser/web/src/videoRecorder';\nimport { browserEnvironment } from '@swiftbrowser/web/src/hostRequests';\nimport { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';\nimport { sb } from './host/sb';\nimport { applyModifiers, splitProps, type ViewModifiers } from './modifiers';\n\nexport type { CameraFacing, VideoRecording };\n\n/** `closed` (no camera), `opening` (asking for it), `ready` (its picture shows), `recording`, `paused`, `stopping`. */\nexport type VideoRecorderStatus = 'closed' | 'opening' | 'ready' | 'recording' | 'paused' | 'stopping';\n\nexport interface VideoRecorder {\n /** Whether this page or app can record video at all. */\n available: boolean;\n status: VideoRecorderStatus;\n /** The live picture's stream while the camera is open, for `CameraPreview`. */\n stream: string | null;\n /** The camera in use. */\n facing: CameraFacing;\n /** Seconds recorded so far (it holds while paused). */\n time: number;\n /** Why the last call failed (`permission: …` when the camera was refused), or null. */\n error: string | null;\n /** Opens the camera (`facing`, else the one used last, else the front); the picture shows once `status` is `ready`. */\n open(facing?: CameraFacing): Promise<void>;\n /** Lets the camera go (a recording under way is cancelled). */\n close(): Promise<void>;\n /** The other camera, front or back. */\n flip(): Promise<void>;\n record(): Promise<void>;\n pause(): Promise<void>;\n resume(): Promise<void>;\n /** Ends the recording and resolves with it, or null when there was none. The camera stays open. */\n stop(): Promise<VideoRecording | null>;\n /** Ends the recording and keeps nothing. */\n cancel(): Promise<void>;\n /** Lets go of a recording `stop` made, when the app is done with it (saved it, or deleted it). */\n discard(url: string): Promise<void>;\n}\n\nexport interface VideoRecorderOptions {\n /** Milliseconds between readings of the recorded time (100: ten a second). */\n timeInterval?: number;\n}\n\nexport function useVideoRecorder(options: VideoRecorderOptions = {}): VideoRecorder {\n const interval = options.timeInterval ?? 100;\n const host = browserEnvironment.videoRecorder;\n const [status, setStatus] = useState<VideoRecorderStatus>('closed');\n const [stream, setStream] = useState<string | null>(null);\n const [facing, setFacing] = useState<CameraFacing>('user');\n const [time, setTime] = useState(0);\n const [error, setError] = useState<string | null>(null);\n const statusRef = useRef(status);\n statusRef.current = status;\n const facingRef = useRef(facing);\n facingRef.current = facing;\n const fail = (reason: unknown): void => setError(reason instanceof Error ? reason.message : String(reason));\n\n // The time while recording; one reading at a time, so a slow host never queues them.\n useEffect(() => {\n if (status !== 'recording' || !host) return;\n let reading = false;\n let live = true;\n const timer = setInterval(() => {\n if (reading) return;\n reading = true;\n host\n .time()\n .then((seconds) => live && setTime(seconds))\n .catch(() => undefined)\n .finally(() => {\n reading = false;\n });\n }, interval);\n return () => {\n live = false;\n clearInterval(timer);\n };\n }, [status, host, interval]);\n\n // The camera goes with the view (a recording under way is cancelled).\n useEffect(\n () => () => {\n if (statusRef.current !== 'closed') void host?.close().catch(() => undefined);\n },\n [host],\n );\n\n const open = useCallback(\n async (wanted?: CameraFacing): Promise<void> => {\n if (!host) {\n setError('unsupported: this page cannot record video');\n return;\n }\n if (statusRef.current === 'recording' || statusRef.current === 'paused' || statusRef.current === 'stopping') return;\n setError(null);\n setStatus('opening');\n try {\n const opened = await host.open({ facing: wanted ?? facingRef.current });\n setStream(opened.stream);\n setFacing(opened.facing);\n setStatus('ready');\n } catch (reason) {\n fail(reason);\n setStream(null);\n setStatus('closed');\n }\n },\n [host],\n );\n\n const close = useCallback(async (): Promise<void> => {\n if (!host) return;\n await host.close().catch(fail);\n setStream(null);\n setStatus('closed');\n setTime(0);\n }, [host]);\n\n const flip = useCallback(async (): Promise<void> => {\n if (statusRef.current !== 'ready') return;\n await open(facingRef.current === 'user' ? 'environment' : 'user');\n }, [open]);\n\n const record = useCallback(async (): Promise<void> => {\n if (!host || statusRef.current !== 'ready') return;\n setError(null);\n setTime(0);\n try {\n await host.start();\n setStatus('recording');\n } catch (reason) {\n fail(reason);\n }\n }, [host]);\n\n const pause = useCallback(async (): Promise<void> => {\n if (!host || statusRef.current !== 'recording') return;\n await host.pause().catch(fail);\n setStatus('paused');\n }, [host]);\n\n const resume = useCallback(async (): Promise<void> => {\n if (!host || statusRef.current !== 'paused') return;\n await host.resume().catch(fail);\n setStatus('recording');\n }, [host]);\n\n const stop = useCallback(async (): Promise<VideoRecording | null> => {\n if (!host || (statusRef.current !== 'recording' && statusRef.current !== 'paused')) return null;\n setStatus('stopping');\n try {\n const recording = await host.stop();\n setTime(recording.duration);\n return recording;\n } catch (reason) {\n fail(reason);\n return null;\n } finally {\n setStatus('ready');\n }\n }, [host]);\n\n const cancel = useCallback(async (): Promise<void> => {\n if (!host || (statusRef.current !== 'recording' && statusRef.current !== 'paused')) return;\n await host.cancel().catch(fail);\n setStatus('ready');\n setTime(0);\n }, [host]);\n\n const discard = useCallback(\n async (url: string): Promise<void> => {\n await host?.discard(url).catch(fail);\n },\n [host],\n );\n\n return { available: host !== undefined, status, stream, facing, time, error, open, close, flip, record, pause, resume, stop, cancel, discard };\n}\n\nexport interface CameraPreviewProps extends ViewModifiers {\n /** The recorder whose camera to show (its `stream`); nothing shows while it is closed. */\n recorder: Pick<VideoRecorder, 'stream' | 'facing'>;\n /** `videoGravity`: fill the view (the default, as the Camera app does) or fit in it. */\n gravity?: 'resizeAspect' | 'resizeAspectFill' | 'resize';\n /** Flipped left to right; by default the front camera is, as a mirror. */\n mirrored?: boolean;\n}\n\n/**\n * The camera's live picture (an `AVCaptureVideoPreviewLayer`), black while\n * the recorder's camera is closed. It fills its frame, cropping as needed.\n */\nexport function CameraPreview(props: CameraPreviewProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const stream = own.recorder.stream;\n if (!stream) return applyModifiers(sb('color', { color: { r: 0, g: 0, b: 0, a: 1 } }), modifiers);\n return applyModifiers(\n sb('video', {\n url: null,\n playing: false,\n muted: true,\n volume: 0,\n rate: 1,\n loop: false,\n gravity: own.gravity ?? 'resizeAspectFill',\n controls: false,\n seek: { time: 0, serial: 0 },\n stream,\n mirrored: own.mirrored ?? own.recorder.facing === 'user',\n }),\n modifiers,\n );\n}\n","/**\n * `AVAudioEngine` for a JavaScript app: the engine, its nodes and their\n * files and buffers, shaped as AVFoundation's, so an app builds a graph as\n * an iOS app does. Attach a player, a sampler, a mixer or an effect,\n * connect them toward `mainMixerNode`, `start()`, then schedule files and\n * buffers on a player (`AVAudioPlayerNode`) or play notes on a sampler\n * (`AVAudioUnitSampler`); reverb, delay, distortion, EQ and time-pitch\n * effects shape what passes through them, and `inputNode` is the\n * microphone. Each object is a number the app chooses and each call one\n * command to the host, in order: natively `AVAudioEngine` itself answers\n * (packages/native, AudioEngineBridge.swift), on a page the Web Audio API\n * (Web/src/audioEngine.ts). Per-sample work never runs in JavaScript.\n *\n * What differs from Swift: `start()`, opening a file and loading a sampler\n * are asynchronous (await them before playing); a scheduled file or\n * buffer's completion is also the promise its `schedule…` call returns; a\n * sampler's `loadAudioFiles` places each file on the keyboard by the note in\n * its name (`Piano C4.wav`, `F#2`, `60`; C4 is middle C, MIDI 60) or the\n * `rootNotes` given, each covering the keys up to halfway to the next; and\n * `meter()` reads a node's output level, as a tap would. A page cannot load\n * sound banks (`loadInstrument`) or change pitch apart from speed\n * (`AVAudioUnitTimePitch` passes its input through there).\n */\n\nimport type {\n AudioBufferInfo,\n AudioEngineCommand,\n AudioEngineHost,\n AudioFileInfo,\n AudioNodeKind,\n AudioTimeSpec,\n AudioValue,\n CustomAudioNodeKind,\n SamplerZone,\n} from '@swiftbrowser/web/src/audioEngine';\nimport { browserEnvironment } from '@swiftbrowser/web/src/hostRequests';\nimport { useEffect, useState } from 'react';\n\nexport type { AudioEngineHost, SamplerZone };\n\n/** One id space for every engine, node, file and buffer on the page or in the app. */\nlet nextId = 1;\nconst newId = (): number => nextId++;\n\nconst hostNow = (): AudioEngineHost | undefined => browserEnvironment.audioEngine;\n\nfunction unsupported(): Error {\n return new Error('unsupported: this page or app has no audio engine');\n}\n\nfunction perform<T = unknown>(command: AudioEngineCommand): Promise<T> {\n const host = hostNow();\n if (!host) return Promise.reject(unsupported());\n return host.perform(command) as Promise<T>;\n}\n\n/** A format as an app reads it: the sample rate and the channels. */\nexport interface AVAudioFormat {\n sampleRate: number;\n channelCount: number;\n}\n\n/**\n * When something starts. `new AVAudioTime(sampleTime, rate)` is a sample\n * time on a player's own timeline (frames at `rate` from when it started\n * playing): what a sequencer schedules on, sample-accurately.\n * `AVAudioTime.secondsFromNow(s)` is a delay from when the call arrives.\n */\nexport class AVAudioTime {\n readonly spec: AudioTimeSpec;\n\n constructor(sampleTime: number, atRate: number) {\n this.spec = { sampleTime: Math.round(sampleTime), sampleRate: atRate };\n }\n\n static secondsFromNow(seconds: number): AVAudioTime {\n const time = Object.create(AVAudioTime.prototype) as { spec: AudioTimeSpec };\n time.spec = { delay: Math.max(0, seconds) };\n return time as AVAudioTime;\n }\n\n get isSampleTimeValid(): boolean {\n return 'sampleTime' in this.spec;\n }\n\n get sampleTime(): number {\n return 'sampleTime' in this.spec ? this.spec.sampleTime : 0;\n }\n\n get sampleRate(): number {\n return 'sampleTime' in this.spec ? this.spec.sampleRate : 0;\n }\n\n /** The time in seconds: a sample time's place on its timeline, or the delay. */\n get seconds(): number {\n return 'sampleTime' in this.spec ? this.spec.sampleTime / this.spec.sampleRate : this.spec.delay;\n }\n}\n\n/** Frees a file or buffer's audio on the host once the app's object is gone, if the app did not `close()` it. */\nconst released =\n typeof FinalizationRegistry !== 'undefined' ? new FinalizationRegistry<number>((id) => void perform({ action: 'release', id }).catch(() => undefined)) : null;\n\n/**\n * Audio for a player to play or a sampler to load: `AVAudioFile.open(url)`\n * decodes it (natively it streams), and `read(into:)` fills a buffer from\n * `framePosition`. The URL is the app's file (`file:`), a page's URL, or a\n * `data:` URL.\n */\nexport class AVAudioFile {\n /** Where the next `read` starts, in frames. */\n framePosition = 0;\n\n private constructor(\n readonly id: number,\n readonly url: string,\n readonly length: number,\n readonly processingFormat: AVAudioFormat,\n ) {\n released?.register(this, id, this);\n }\n\n /** Opens a file for reading; rejects with `notFound: …` or `decode: …`. */\n static async open(url: string): Promise<AVAudioFile> {\n const id = newId();\n const info = await perform<AudioFileInfo>({ action: 'openFile', file: id, url });\n return new AVAudioFile(id, url, info.length, { sampleRate: info.sampleRate, channelCount: info.channelCount });\n }\n\n /** Seconds. */\n get duration(): number {\n return this.length / this.processingFormat.sampleRate;\n }\n\n /** Reads frames from `framePosition` into `buffer` (up to its capacity, or `frameCount`) and moves past them. */\n async read(into: AVAudioPCMBuffer, frameCount?: number): Promise<void> {\n const frames = Math.max(0, Math.min(frameCount ?? into.frameCapacity, into.frameCapacity, this.length - this.framePosition));\n const info = await perform<AudioBufferInfo>({ action: 'readFile', file: this.id, buffer: into.id, start: this.framePosition, frames });\n into.frameLength = info.frameLength;\n into.format = { sampleRate: info.sampleRate, channelCount: info.channelCount };\n this.framePosition += info.frameLength;\n }\n\n /** Lets the host free the decoded audio (what a scheduled segment still plays keeps playing). */\n close(): void {\n released?.unregister(this);\n void perform({ action: 'release', id: this.id }).catch(() => undefined);\n }\n}\n\n/**\n * PCM audio a player schedules: read from a file (`AVAudioFile.read(into:)`)\n * or written from the app's own samples (`write`, one `Float32Array` per\n * channel, -1 … 1), which is how a JavaScript app hands over sound it\n * computed.\n */\nexport class AVAudioPCMBuffer {\n readonly id = newId();\n frameLength = 0;\n\n constructor(\n public format: AVAudioFormat,\n readonly frameCapacity: number,\n ) {\n released?.register(this, this.id, this);\n }\n\n /** Seconds of audio it holds. */\n get duration(): number {\n return this.frameLength / this.format.sampleRate;\n }\n\n /** Fills the buffer with the app's samples, one array per channel (up to its capacity). */\n async write(channels: readonly Float32Array[]): Promise<void> {\n const frames = Math.min(this.frameCapacity, ...channels.map((data) => data.length));\n await perform({\n action: 'writeBuffer',\n buffer: this.id,\n sampleRate: this.format.sampleRate,\n channels: channels.map((data) => (data.length === frames ? data : data.subarray(0, frames))),\n });\n this.frameLength = frames;\n this.format = { sampleRate: this.format.sampleRate, channelCount: channels.length };\n }\n\n /** Lets the host free the audio. */\n close(): void {\n released?.unregister(this);\n void perform({ action: 'release', id: this.id }).catch(() => undefined);\n }\n}\n\n/** A node in an engine's graph. Its properties are kept until it is attached, then sent as they change. */\nexport abstract class AVAudioNode {\n readonly id = newId();\n /** The engine it is attached to, or null. */\n engine: AVAudioEngine | null = null;\n protected readonly values: Record<string, AudioValue> = {};\n /**\n * The command kind it is attached as (null: one an engine makes itself). A\n * package's node subclasses this with its own kind (@swiftbrowser/dsp's\n * `DSPNode` is `program`), which the host makes from what the package\n * registered.\n */\n abstract readonly kind: AudioNodeKind | CustomAudioNodeKind | null;\n\n protected get<T extends AudioValue>(key: string, fallback: T): T {\n return (this.values[key] as T | undefined) ?? fallback;\n }\n\n protected set(key: string, value: AudioValue): void {\n this.values[key] = value;\n this.engine?.fire({ action: 'set', node: this.id, values: { [key]: value } });\n }\n\n /** The properties to attach it with. */\n attachValues(): Record<string, AudioValue> {\n return { ...this.values };\n }\n\n /** How many EQ bands it has (only an EQ has any). */\n get bandCount(): number | undefined {\n return undefined;\n }\n\n /** What its engine must be for a call to reach it. */\n protected attached(): AVAudioEngine {\n if (!this.engine) throw new Error('notAttached: attach the node to an engine first');\n return this.engine;\n }\n\n /** Its output's level now (0 silent … 1 at 0 dB, from -50 dB), as a tap on it would measure; 0 when not attached. */\n async meter(): Promise<number> {\n if (!this.engine) return 0;\n const result = await this.engine.send<{ level?: number }>({ action: 'meter', node: this.id });\n return typeof result?.level === 'number' ? result.level : 0;\n }\n}\n\n/** A node that mixes into what it connects to (`AVAudioMixing`): its volume (0 … 1) and pan (-1 left … 1 right). */\nabstract class MixingNode extends AVAudioNode {\n get volume(): number {\n return this.get('volume', 1);\n }\n\n set volume(value: number) {\n this.set('volume', value);\n }\n\n get pan(): number {\n return this.get('pan', 0);\n }\n\n set pan(value: number) {\n this.set('pan', value);\n }\n}\n\n/** `AVAudioMixerNode`: sums what connects to it; `outputVolume` scales the sum. An engine's `mainMixerNode` is one. */\nexport class AVAudioMixerNode extends MixingNode {\n readonly kind: AudioNodeKind | null = 'mixer';\n\n get outputVolume(): number {\n return this.get('outputVolume', 1);\n }\n\n set outputVolume(value: number) {\n this.set('outputVolume', value);\n }\n}\n\n/** The engine's output to the speakers. */\nexport class AVAudioOutputNode extends AVAudioNode {\n readonly kind = null;\n}\n\n/** The microphone: connect it (to a mixer, an effect) and start the engine, which asks for the microphone then. */\nexport class AVAudioInputNode extends MixingNode {\n readonly kind = null;\n}\n\n/** What a scheduled buffer does (`AVAudioPlayerNodeBufferOptions`). */\nexport interface AVAudioPlayerNodeBufferOptions {\n /** Plays it over and over, until the player stops or another buffer interrupts it. */\n loops?: boolean;\n /** Stops what the player is playing and plays this now. */\n interrupts?: boolean;\n /** As `interrupts`, once a looping buffer that is playing finishes its pass (a pattern swapped on the bar line). */\n interruptsAtLoop?: boolean;\n}\n\n/**\n * `AVAudioPlayerNode`: a timeline of scheduled files, segments and\n * buffers. Each plays after the last, or at its own `AVAudioTime`; `play()`\n * starts the timeline once the engine runs. Each `schedule…` resolves\n * (and calls its completion handler) when its audio has played, or the\n * player stopped.\n */\nexport class AVAudioPlayerNode extends MixingNode {\n readonly kind = 'player' as const;\n private playing = false;\n\n get isPlaying(): boolean {\n return this.playing && this.engine?.isRunning === true;\n }\n\n scheduleFile(file: AVAudioFile, at: AVAudioTime | null = null, completionHandler?: () => void): Promise<void> {\n return this.schedule({ action: 'scheduleFile', node: this.id, file: file.id, ...(at ? { at: at.spec } : {}) }, completionHandler);\n }\n\n scheduleSegment(file: AVAudioFile, startingFrame: number, frameCount: number, at: AVAudioTime | null = null, completionHandler?: () => void): Promise<void> {\n return this.schedule(\n {\n action: 'scheduleFile',\n node: this.id,\n file: file.id,\n start: Math.max(0, Math.floor(startingFrame)),\n frames: Math.max(0, Math.floor(frameCount)),\n ...(at ? { at: at.spec } : {}),\n },\n completionHandler,\n );\n }\n\n scheduleBuffer(\n buffer: AVAudioPCMBuffer,\n at: AVAudioTime | null = null,\n options: AVAudioPlayerNodeBufferOptions = {},\n completionHandler?: () => void,\n ): Promise<void> {\n const command: Extract<AudioEngineCommand, { action: 'scheduleBuffer' }> = {\n action: 'scheduleBuffer',\n node: this.id,\n buffer: buffer.id,\n ...(at ? { at: at.spec } : {}),\n };\n if (options.loops) command.loops = true;\n if (options.interruptsAtLoop) command.interruptsAtLoop = true;\n else if (options.interrupts) command.interrupts = true;\n return this.schedule(command, completionHandler);\n }\n\n private schedule(command: AudioEngineCommand, completionHandler: (() => void) | undefined): Promise<void> {\n const engine = this.attached();\n return engine.send(command).then(() => completionHandler?.());\n }\n\n /** Starts (or resumes) the timeline, now or at `at`; the engine must be running. */\n play(at: AVAudioTime | null = null): void {\n const engine = this.attached();\n this.playing = true;\n engine.fire({ action: 'play', node: this.id, ...(at ? { at: at.spec } : {}) });\n }\n\n /** Holds the timeline where it is; `play()` goes on from there. */\n pause(): void {\n this.playing = false;\n this.engine?.fire({ action: 'pausePlayer', node: this.id });\n }\n\n /** Drops everything scheduled (each completion called) and returns the timeline to 0. */\n stop(): void {\n this.playing = false;\n this.engine?.fire({ action: 'stopPlayer', node: this.id });\n }\n\n /** Where the timeline is now (`playerTime(forNodeTime: lastRenderTime)`), or null before it plays. */\n async playerTime(): Promise<AVAudioTime | null> {\n const time = await this.attached().send<{ sampleTime: number; sampleRate: number } | null>({ action: 'playerTime', node: this.id });\n return time && typeof time.sampleTime === 'number' ? new AVAudioTime(time.sampleTime, time.sampleRate) : null;\n }\n\n /** Called by the engine when it stops: the player stops with it. */\n engineStopped(): void {\n this.playing = false;\n }\n}\n\n/** Options for `loadAudioFiles`: where each file sits on the keyboard, and the notes' envelope. */\nexport interface SamplerLoadOptions {\n /** Each file's root note (MIDI), in the order of the URLs; absent, read from each file's name. */\n rootNotes?: readonly number[];\n /** Seconds from silence to full level (0.002). */\n attack?: number;\n /** Seconds to fade once a note is let go (0.15). */\n release?: number;\n}\n\nconst NOTE_CLASSES: Record<string, number> = { c: 0, d: 2, e: 4, f: 5, g: 7, a: 9, b: 11 };\n\n/**\n * The MIDI note a sample's file name names: `C4` (middle C, 60), `F#2`,\n * `Bb3`, `A-1`, or a bare number `60`; the last one in the name wins. Null\n * when it names none.\n */\nexport function noteInName(url: string): number | null {\n const name = decodeURIComponent(url.split(/[/\\\\]/).pop() ?? '').replace(/\\.[^.]*$/, '');\n const named = [...name.matchAll(/(?:^|[^A-Za-z])([A-Ga-g])([#♯]|b|♭)?(-?\\d)(?!\\d)/g)].pop();\n if (named) {\n const pitchClass = NOTE_CLASSES[named[1]!.toLowerCase()]!;\n const accidental = named[2] === '#' || named[2] === '♯' ? 1 : named[2] ? -1 : 0;\n const note = (Number(named[3]) + 1) * 12 + pitchClass + accidental;\n return note >= 0 && note <= 127 ? note : null;\n }\n const numbered = [...name.matchAll(/(?:^|\\D)(\\d{1,3})(?!\\d)/g)].pop();\n if (numbered) {\n const note = Number(numbered[1]);\n return note <= 127 ? note : null;\n }\n return null;\n}\n\n/**\n * Zones for samples at their root notes: sorted by root, each covering the\n * keys from halfway after the one below to halfway to the one above (the\n * lowest down to 0, the highest up to 127). A second sample on a root\n * already taken is left out.\n */\nexport function samplerZones(samples: readonly { file: number; root: number }[]): SamplerZone[] {\n const sorted = [...samples].sort((a, b) => a.root - b.root).filter((sample, i, all) => i === 0 || sample.root !== all[i - 1]!.root);\n return sorted.map((sample, i) => {\n const below = sorted[i - 1];\n const above = sorted[i + 1];\n return {\n file: sample.file,\n root: sample.root,\n low: below ? Math.floor((below.root + sample.root) / 2) + 1 : 0,\n high: above ? Math.floor((sample.root + above.root) / 2) : 127,\n };\n });\n}\n\n/**\n * `AVAudioUnitSampler`: notes played from samples. `loadAudioFiles(urls)`\n * places each file on the keyboard (see the file comment) and pitches it\n * across its zone; `startNote` and `stopNote` play, with velocity, the\n * sustain pedal and other controllers (`sendController`) and the pitch\n * wheel (`sendPitchBend`). Natively `loadInstrument` and\n * `loadSoundBankInstrument` load an `.aupreset`, a DLS or a SoundFont too.\n */\nexport class AVAudioUnitSampler extends MixingNode {\n readonly kind = 'sampler' as const;\n private files: AVAudioFile[] = [];\n\n /** Decibels, -90 … 12. */\n get overallGain(): number {\n return this.get('overallGain', 0);\n }\n\n set overallGain(value: number) {\n this.set('overallGain', value);\n }\n\n /** Cents, -2400 … 2400. */\n get globalTuning(): number {\n return this.get('globalTuning', 0);\n }\n\n set globalTuning(value: number) {\n this.set('globalTuning', value);\n }\n\n /** -100 left … 100 right. */\n get stereoPan(): number {\n return this.get('stereoPan', 0);\n }\n\n set stereoPan(value: number) {\n this.set('stereoPan', value);\n }\n\n async loadAudioFiles(urls: readonly string[], options: SamplerLoadOptions = {}): Promise<void> {\n const engine = this.attached();\n const roots = urls.map((url, i) => options.rootNotes?.[i] ?? noteInName(url) ?? 60);\n const files = await Promise.all(urls.map((url) => AVAudioFile.open(url)));\n const zones = samplerZones(files.map((file, i) => ({ file: file.id, root: roots[i]! })));\n await engine.send({ action: 'loadZones', node: this.id, zones, attack: options.attack ?? 0.002, release: options.release ?? 0.15 });\n const previous = this.files;\n this.files = files;\n for (const file of previous) file.close();\n }\n\n /** Loads an `.aupreset`, a DLS or a SoundFont's first instrument (natively; a page rejects with `unsupported: …`). */\n async loadInstrument(url: string): Promise<void> {\n await this.attached().send({ action: 'loadInstrument', node: this.id, url });\n }\n\n /** Loads one instrument of a SoundFont or DLS bank by program and bank (natively; a page rejects with `unsupported: …`). */\n async loadSoundBankInstrument(url: string, program: number, bankMSB = 0x79, bankLSB = 0): Promise<void> {\n await this.attached().send({ action: 'loadInstrument', node: this.id, url, program, bankMSB, bankLSB });\n }\n\n startNote(note: number, withVelocity: number, onChannel = 0): void {\n this.attached().fire({ action: 'startNote', node: this.id, note: Math.round(note), velocity: Math.round(withVelocity), channel: onChannel });\n }\n\n stopNote(note: number, onChannel = 0): void {\n this.attached().fire({ action: 'stopNote', node: this.id, note: Math.round(note), channel: onChannel });\n }\n\n /** A MIDI controller: 64 the sustain pedal, 7 volume, 11 expression, 10 pan, 123 all notes off. */\n sendController(controller: number, withValue: number, onChannel = 0): void {\n this.attached().fire({ action: 'controller', node: this.id, controller, value: Math.round(withValue), channel: onChannel });\n }\n\n /** The pitch wheel: 0 … 16383, 8192 centered (±2 semitones). */\n sendPitchBend(pitchbend: number, onChannel = 0): void {\n this.attached().fire({ action: 'pitchBend', node: this.id, value: Math.round(pitchbend), channel: onChannel });\n }\n}\n\n/** An effect node: `bypass` passes its input through untouched. */\nexport abstract class AVAudioUnitEffect extends AVAudioNode {\n get bypass(): boolean {\n return this.get('bypass', false);\n }\n\n set bypass(value: boolean) {\n this.set('bypass', value);\n }\n}\n\nexport type AVAudioUnitReverbPreset =\n | 'smallRoom'\n | 'mediumRoom'\n | 'largeRoom'\n | 'mediumHall'\n | 'largeHall'\n | 'plate'\n | 'mediumChamber'\n | 'largeChamber'\n | 'cathedral'\n | 'largeRoom2'\n | 'mediumHall2'\n | 'mediumHall3'\n | 'largeHall2';\n\n/** `AVAudioUnitReverb`: a room, a hall or a plate (`loadFactoryPreset`), mixed in by `wetDryMix` (percent). */\nexport class AVAudioUnitReverb extends AVAudioUnitEffect {\n readonly kind = 'reverb' as const;\n\n constructor() {\n super();\n this.values['preset'] = 'mediumHall';\n this.values['wetDryMix'] = 100;\n }\n\n get wetDryMix(): number {\n return this.get('wetDryMix', 100);\n }\n\n set wetDryMix(value: number) {\n this.set('wetDryMix', value);\n }\n\n loadFactoryPreset(preset: AVAudioUnitReverbPreset): void {\n this.values['preset'] = preset;\n this.engine?.fire({ action: 'preset', node: this.id, preset });\n }\n}\n\n/** `AVAudioUnitDelay`: an echo `delayTime` seconds later (0 … 2), fed back by `feedback` percent, darkened above `lowPassCutoff` Hz. */\nexport class AVAudioUnitDelay extends AVAudioUnitEffect {\n readonly kind = 'delay' as const;\n\n constructor() {\n super();\n Object.assign(this.values, { delayTime: 1, feedback: 50, lowPassCutoff: 15000, wetDryMix: 100 });\n }\n\n get delayTime(): number {\n return this.get('delayTime', 1);\n }\n\n set delayTime(value: number) {\n this.set('delayTime', value);\n }\n\n get feedback(): number {\n return this.get('feedback', 50);\n }\n\n set feedback(value: number) {\n this.set('feedback', value);\n }\n\n get lowPassCutoff(): number {\n return this.get('lowPassCutoff', 15000);\n }\n\n set lowPassCutoff(value: number) {\n this.set('lowPassCutoff', value);\n }\n\n get wetDryMix(): number {\n return this.get('wetDryMix', 100);\n }\n\n set wetDryMix(value: number) {\n this.set('wetDryMix', value);\n }\n}\n\nexport type AVAudioUnitDistortionPreset =\n | 'drumsBitBrush'\n | 'drumsBufferBeats'\n | 'drumsLoFi'\n | 'multiBrokenSpeaker'\n | 'multiCellphoneConcert'\n | 'multiDecimated1'\n | 'multiDecimated2'\n | 'multiDecimated3'\n | 'multiDecimated4'\n | 'multiDistortedFunk'\n | 'multiDistortedCubed'\n | 'multiDistortedSquared'\n | 'multiEcho1'\n | 'multiEcho2'\n | 'multiEchoTight1'\n | 'multiEchoTight2'\n | 'multiEverythingIsBroken'\n | 'speechAlienChatter'\n | 'speechCosmicInterference'\n | 'speechGoldenPi'\n | 'speechRadioTower'\n | 'speechWaves';\n\n/** `AVAudioUnitDistortion`: driven by `preGain` (dB), mixed in by `wetDryMix`, its character from a factory preset. */\nexport class AVAudioUnitDistortion extends AVAudioUnitEffect {\n readonly kind = 'distortion' as const;\n\n constructor() {\n super();\n Object.assign(this.values, { preGain: -6, wetDryMix: 50 });\n }\n\n get preGain(): number {\n return this.get('preGain', -6);\n }\n\n set preGain(value: number) {\n this.set('preGain', value);\n }\n\n get wetDryMix(): number {\n return this.get('wetDryMix', 50);\n }\n\n set wetDryMix(value: number) {\n this.set('wetDryMix', value);\n }\n\n loadFactoryPreset(preset: AVAudioUnitDistortionPreset): void {\n this.values['preset'] = preset;\n this.engine?.fire({ action: 'preset', node: this.id, preset });\n }\n}\n\nexport type AVAudioUnitEQFilterType =\n | 'parametric'\n | 'lowPass'\n | 'highPass'\n | 'resonantLowPass'\n | 'resonantHighPass'\n | 'bandPass'\n | 'bandStop'\n | 'lowShelf'\n | 'highShelf'\n | 'resonantLowShelf'\n | 'resonantHighShelf';\n\n/** One band of an `AVAudioUnitEQ`. A band is bypassed until the app sets `bypass = false`, as Apple's are. */\nexport class AVAudioUnitEQFilterParameters {\n constructor(\n private readonly eq: AVAudioUnitEQ,\n private readonly index: number,\n ) {}\n\n private key(field: string): string {\n return `bands.${this.index}.${field}`;\n }\n\n get filterType(): AVAudioUnitEQFilterType {\n return this.eq.band(this.key('filterType'), 'parametric') as AVAudioUnitEQFilterType;\n }\n\n set filterType(value: AVAudioUnitEQFilterType) {\n this.eq.setBand(this.key('filterType'), value);\n }\n\n /** Hz. */\n get frequency(): number {\n return this.eq.band(this.key('frequency'), 1000) as number;\n }\n\n set frequency(value: number) {\n this.eq.setBand(this.key('frequency'), value);\n }\n\n /** Octaves (0.05 … 5). */\n get bandwidth(): number {\n return this.eq.band(this.key('bandwidth'), 0.5) as number;\n }\n\n set bandwidth(value: number) {\n this.eq.setBand(this.key('bandwidth'), value);\n }\n\n /** Decibels (-96 … 24). */\n get gain(): number {\n return this.eq.band(this.key('gain'), 0) as number;\n }\n\n set gain(value: number) {\n this.eq.setBand(this.key('gain'), value);\n }\n\n get bypass(): boolean {\n return this.eq.band(this.key('bypass'), true) as boolean;\n }\n\n set bypass(value: boolean) {\n this.eq.setBand(this.key('bypass'), value);\n }\n}\n\n/** `AVAudioUnitEQ(numberOfBands:)`: a filter per band and a `globalGain` (dB). */\nexport class AVAudioUnitEQ extends AVAudioUnitEffect {\n readonly kind = 'eq' as const;\n readonly bands: readonly AVAudioUnitEQFilterParameters[];\n\n constructor(numberOfBands = 1) {\n super();\n const count = Math.max(1, Math.min(32, Math.floor(numberOfBands)));\n this.bands = Array.from({ length: count }, (_, i) => new AVAudioUnitEQFilterParameters(this, i));\n for (let i = 0; i < count; i += 1) {\n Object.assign(this.values, {\n [`bands.${i}.filterType`]: 'parametric',\n [`bands.${i}.frequency`]: 1000,\n [`bands.${i}.bandwidth`]: 0.5,\n [`bands.${i}.gain`]: 0,\n [`bands.${i}.bypass`]: true,\n });\n }\n }\n\n override get bandCount(): number {\n return this.bands.length;\n }\n\n get globalGain(): number {\n return this.get('globalGain', 0);\n }\n\n set globalGain(value: number) {\n this.set('globalGain', value);\n }\n\n /** A band's field (for `AVAudioUnitEQFilterParameters`). */\n band(key: string, fallback: AudioValue): AudioValue {\n return this.values[key] ?? fallback;\n }\n\n setBand(key: string, value: AudioValue): void {\n this.set(key, value);\n }\n}\n\n/** `AVAudioUnitTimePitch`: `pitch` in cents (-2400 … 2400) and `rate` (1/32 … 32) apart (natively; a page passes the sound through). */\nexport class AVAudioUnitTimePitch extends AVAudioUnitEffect {\n readonly kind = 'timePitch' as const;\n\n get pitch(): number {\n return this.get('pitch', 0);\n }\n\n set pitch(value: number) {\n this.set('pitch', value);\n }\n\n get rate(): number {\n return this.get('rate', 1);\n }\n\n set rate(value: number) {\n this.set('rate', value);\n }\n\n get overlap(): number {\n return this.get('overlap', 8);\n }\n\n set overlap(value: number) {\n this.set('overlap', value);\n }\n}\n\n/** Frees an engine on the host once the app's engine object is gone, if the app did not `dispose()` it. */\nconst engines =\n typeof FinalizationRegistry !== 'undefined'\n ? new FinalizationRegistry<number>((id) => void perform({ action: 'destroy', engine: id }).catch(() => undefined))\n : null;\n\n/**\n * `AVAudioEngine`: a graph of nodes from players, samplers and the input\n * through effects and mixers to `mainMixerNode` and `outputNode` (the\n * speakers). `start()` resolves once it runs; a failure of a call that\n * answers nothing (a property, a note) goes to `onError`.\n */\nexport class AVAudioEngine {\n readonly id = newId();\n readonly mainMixerNode = new AVAudioMixerNode();\n readonly outputNode = new AVAudioOutputNode();\n readonly inputNode = new AVAudioInputNode();\n readonly attachedNodes = new Set<AVAudioNode>();\n /** Where failures of calls that answer nothing go (a console warning by default). */\n onError: (error: Error) => void = (error) => console.warn(`AVAudioEngine: ${error.message}`);\n private running = false;\n private disposed = false;\n\n /** Whether this page or app has an audio engine. */\n static get isAvailable(): boolean {\n return hostNow() !== undefined;\n }\n\n constructor() {\n for (const node of [this.mainMixerNode, this.outputNode, this.inputNode]) {\n node.engine = this;\n this.attachedNodes.add(node);\n }\n this.fire({ action: 'create', engine: this.id, mixer: this.mainMixerNode.id, output: this.outputNode.id, input: this.inputNode.id });\n engines?.register(this, this.id, this);\n }\n\n get isRunning(): boolean {\n return this.running;\n }\n\n /** Sends a command and answers its result. */\n send<T = unknown>(command: AudioEngineCommand): Promise<T> {\n if (this.disposed) return Promise.reject(new Error('disposed: the engine was disposed'));\n return perform<T>(command);\n }\n\n /** Sends a command that answers nothing; a failure goes to `onError`. */\n fire(command: AudioEngineCommand): void {\n this.send(command).catch((error: unknown) => this.onError(error instanceof Error ? error : new Error(String(error))));\n }\n\n attach(node: AVAudioNode): void {\n if (node.engine === this) return;\n if (node.engine) throw new Error('attached: the node is attached to another engine');\n if (!node.kind) throw new Error('unsupported: an engine makes its own mixer, output and input');\n node.engine = this;\n this.attachedNodes.add(node);\n const bands = node.bandCount;\n this.fire({ action: 'attach', engine: this.id, node: node.id, kind: node.kind, values: node.attachValues(), ...(bands !== undefined ? { bands } : {}) });\n }\n\n detach(node: AVAudioNode): void {\n if (node.engine !== this || !node.kind) return;\n this.fire({ action: 'detach', engine: this.id, node: node.id });\n if (node instanceof AVAudioPlayerNode) node.engineStopped();\n node.engine = null;\n this.attachedNodes.delete(node);\n }\n\n /**\n * Connects `from`'s output to `to` (an array: to each of them), replacing\n * where it went before; a node that is not a mixer takes one input, so\n * what was connected into it is let go. `format` is accepted for Swift's\n * shape: the host picks one that fits both ends.\n */\n connect(from: AVAudioNode, to: AVAudioNode | readonly AVAudioNode[], format: AVAudioFormat | null = null): void {\n void format;\n const destinations = Array.isArray(to) ? (to as readonly AVAudioNode[]) : [to as AVAudioNode];\n for (const node of [from, ...destinations]) {\n if (node.engine !== this) throw new Error('notAttached: attach both nodes to the engine before connecting them');\n }\n this.fire({ action: 'connect', engine: this.id, from: from.id, to: destinations.map((node) => node.id) });\n }\n\n disconnectNodeOutput(node: AVAudioNode): void {\n this.fire({ action: 'disconnectOutput', engine: this.id, node: node.id });\n }\n\n disconnectNodeInput(node: AVAudioNode): void {\n this.fire({ action: 'disconnectInput', engine: this.id, node: node.id });\n }\n\n prepare(): void {\n this.fire({ action: 'prepare', engine: this.id });\n }\n\n /** Starts rendering; with the input connected, asks for the microphone (rejecting `permission: …` when refused). */\n async start(): Promise<void> {\n await this.send({ action: 'start', engine: this.id });\n this.running = true;\n }\n\n /** Pauses rendering; players hold their place and play on at `start()`. */\n pause(): void {\n this.running = false;\n this.fire({ action: 'pause', engine: this.id });\n }\n\n /** Stops rendering; players stop and drop what they had scheduled. */\n stop(): void {\n this.running = false;\n for (const node of this.attachedNodes) if (node instanceof AVAudioPlayerNode) node.engineStopped();\n this.fire({ action: 'stop', engine: this.id });\n }\n\n /** Silences every node (players stop, notes end) without stopping the engine. */\n reset(): void {\n for (const node of this.attachedNodes) if (node instanceof AVAudioPlayerNode) node.engineStopped();\n this.fire({ action: 'reset', engine: this.id });\n }\n\n /** Stops the engine and frees it on the host; it cannot be used after. */\n dispose(): void {\n if (this.disposed) return;\n engines?.unregister(this);\n void perform({ action: 'destroy', engine: this.id }).catch(() => undefined);\n this.disposed = true;\n this.running = false;\n for (const node of this.attachedNodes) node.engine = null;\n this.attachedNodes.clear();\n }\n}\n\n/**\n * An engine for a view: made once (`build` attaches and connects its\n * nodes), disposed when the view goes. Null where there is no audio engine.\n */\nexport function useAudioEngine(build?: (engine: AVAudioEngine) => void): AVAudioEngine | null {\n const [engine] = useState(() => {\n if (!AVAudioEngine.isAvailable) return null;\n const made = new AVAudioEngine();\n build?.(made);\n return made;\n });\n useEffect(() => () => engine?.dispose(), [engine]);\n return engine;\n}\n","/**\n * Foundation Models for a JavaScript app: Apple Intelligence's on-device\n * language model, shaped as the framework is, so an app talks to it as an iOS\n * app does. Check `SystemLanguageModel.default`'s availability (or\n * `useSystemLanguageModel()`), make a `LanguageModelSession` with\n * instructions, then `respond(to:)` for a whole answer or `streamResponse(to:)`\n * for the answer as it grows; a session keeps the conversation, so each prompt\n * follows the ones before it. Natively FoundationModels answers\n * (packages/native, LanguageModelBridge.swift; iOS 26 with Apple\n * Intelligence on); on a page Chrome's built-in model where the browser has\n * one (Web/src/languageModel.ts), else the model is unavailable, as on an\n * iPhone without Apple Intelligence.\n *\n * What differs from Swift: availability is asked for (a promise, or the hook\n * that keeps it current), a stream yields snapshots `{ content }` of the whole\n * response so far and can be `cancel()`ed (as cancelling the task iterating\n * it), failures are `GenerationError`s whose `kind` names the case, and a\n * session the app is done with is `close()`d. Tools are objects with a JSON\n * schema for their arguments and a `call` the model's calls run (natively;\n * a page's model answers without them). Guided generation (`@Generable`) is\n * not here.\n */\n\nimport type {\n GenerationOptionsSpec,\n LanguageModelAvailability,\n LanguageModelChoice,\n LanguageModelDownload,\n LanguageModelCommand,\n LanguageModelHost,\n LanguageModelUnavailableReason,\n} from '@swiftbrowser/web/src/languageModel';\nimport { browserEnvironment } from '@swiftbrowser/web/src/hostRequests';\nimport { useEffect, useState } from 'react';\n\nexport type { LanguageModelAvailability, LanguageModelChoice, LanguageModelDownload, LanguageModelHost, LanguageModelUnavailableReason };\n\n/** One id space for every session and stream. */\nlet nextId = 1;\n\nconst hostNow = (): LanguageModelHost | undefined => browserEnvironment.languageModel;\n\nfunction perform<T>(command: LanguageModelCommand): Promise<T> {\n const host = hostNow();\n if (!host) return Promise.reject(new GenerationError('assetsUnavailable', 'This page or app has no language model.'));\n return (host.perform(command) as Promise<T>).catch((error: unknown) => {\n throw GenerationError.from(error);\n });\n}\n\n// MARK: Errors\n\n/** `LanguageModelSession.GenerationError`'s cases. */\nexport type GenerationErrorKind =\n | 'assetsUnavailable'\n | 'exceededContextWindowSize'\n | 'guardrailViolation'\n | 'unsupportedLanguageOrLocale'\n | 'concurrentRequests'\n | 'rateLimited'\n | 'refusal'\n | 'unknown';\n\nconst KINDS: Record<string, GenerationErrorKind> = {\n unavailable: 'assetsUnavailable',\n context: 'exceededContextWindowSize',\n guardrail: 'guardrailViolation',\n language: 'unsupportedLanguageOrLocale',\n concurrent: 'concurrentRequests',\n rateLimited: 'rateLimited',\n refusal: 'refusal',\n};\n\n/** A failed response, as `LanguageModelSession.GenerationError`. */\nexport class GenerationError extends Error {\n constructor(\n readonly kind: GenerationErrorKind,\n message: string,\n ) {\n super(message);\n this.name = 'GenerationError';\n }\n\n /** The error a host's tagged message (`context: …`) stands for. */\n static from(error: unknown): GenerationError {\n if (error instanceof GenerationError) return error;\n const message = error instanceof Error ? error.message : String(error);\n const match = /^(\\w+): ?([\\s\\S]*)$/.exec(message);\n const kind = match ? KINDS[match[1]!] : undefined;\n return kind ? new GenerationError(kind, match![2]!) : new GenerationError('unknown', message);\n }\n}\n\n// MARK: The model\n\nexport type { GenerationOptionsSpec as GenerationOptions };\n\n/** The on-device model: `SystemLanguageModel.default`. */\nexport class SystemLanguageModel {\n static readonly default = new SystemLanguageModel();\n\n private constructor() {}\n\n /** Views showing the availability, asked again when a download starts or the model goes. */\n private readonly listeners = new Set<() => void>();\n\n /** Whether the model can answer now, or why not. */\n async availability(): Promise<LanguageModelAvailability> {\n if (!hostNow()) return { status: 'unavailable', reason: 'deviceNotEligible' };\n try {\n return await perform<LanguageModelAvailability>({ action: 'availability' });\n } catch {\n return { status: 'unavailable', reason: 'deviceNotEligible' };\n }\n }\n\n async isAvailable(): Promise<boolean> {\n return (await this.availability()).status === 'available';\n }\n\n /**\n * Starts fetching a model the app fetches itself (availability's\n * `download`), which the viewer asked for: show its size first. Not part\n * of FoundationModels, whose model the system manages.\n */\n async download(): Promise<void> {\n await perform({ action: 'download' });\n this.changed();\n }\n\n /**\n * Makes the model with this `id` (one of availability's `models`) the one\n * that answers, from the next session on; remembered across launches.\n */\n async selectModel(id: string): Promise<void> {\n await perform({ action: 'select', id });\n this.changed();\n }\n\n /** Stops such a download, or removes the model from the device to free its space. */\n async deleteDownload(): Promise<void> {\n await perform({ action: 'deleteDownload' });\n this.changed();\n }\n\n /** @internal `useSystemLanguageModel` hears downloads start and models go. */\n listen(listener: () => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n private changed(): void {\n for (const listener of this.listeners) listener();\n }\n}\n\n/**\n * The model's availability, kept current: null until known, then asked again\n * while the model is not ready yet (it is downloading), every few seconds or,\n * while a download reports its `progress`, every second, and whenever\n * `download()` or `deleteDownload()` changes it, as a view reading\n * `SystemLanguageModel.default.availability` would update.\n */\nexport function useSystemLanguageModel(model: SystemLanguageModel = SystemLanguageModel.default): LanguageModelAvailability | null {\n const [availability, setAvailability] = useState<LanguageModelAvailability | null>(null);\n useEffect(() => {\n let live = true;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const check = (): void => {\n if (timer !== undefined) clearTimeout(timer);\n timer = undefined;\n void model.availability().then((next) => {\n if (!live) return;\n setAvailability((current) => (JSON.stringify(current) === JSON.stringify(next) ? current : next));\n if (timer !== undefined) return;\n if (next.download?.progress !== undefined) timer = setTimeout(check, 1000);\n else if (next.status === 'unavailable' && next.reason === 'modelNotReady' && !next.download) timer = setTimeout(check, 5000);\n });\n };\n check();\n const stop = model.listen(check);\n return () => {\n live = false;\n stop();\n if (timer !== undefined) clearTimeout(timer);\n };\n }, [model]);\n return availability;\n}\n\n// MARK: Sessions\n\n/** A whole response: `Response<String>`. */\nexport interface Response {\n content: string;\n}\n\n/**\n * A response as it grows (`ResponseStream`): iterate it for snapshots of the\n * whole response so far, or `collect()` the last. The request starts when the\n * stream is made; `cancel()` (or leaving a `for await` early) ends it.\n */\nexport class ResponseStream implements AsyncIterable<Response> {\n private readonly id = nextId++;\n private readonly started: Promise<unknown>;\n private finished = false;\n private last: Response = { content: '' };\n\n /** @internal Made by `LanguageModelSession.streamResponse`. */\n constructor(\n session: LanguageModelSession,\n opened: Promise<unknown>,\n prompt: string,\n options: GenerationOptionsSpec | undefined,\n private readonly ended: () => void,\n ) {\n this.started = opened.then(() =>\n perform({ action: 'stream', session: session.id, stream: this.id, prompt, ...(options ? { options } : {}) }),\n );\n this.started.catch(() => this.end());\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<Response> {\n try {\n await this.started;\n while (!this.finished) {\n const { content, done } = await perform<{ content: string; done: boolean }>({ action: 'next', stream: this.id });\n if (done) this.end();\n if (content !== this.last.content) {\n this.last = { content };\n yield this.last;\n }\n }\n } catch (error) {\n this.end();\n throw error;\n } finally {\n // Left early (`break`, `return`): the model stops too.\n this.cancel();\n }\n }\n\n /** The whole response, once it has ended. */\n async collect(): Promise<Response> {\n for await (const snapshot of this) this.last = snapshot;\n return this.last;\n }\n\n /** Stops the response; the iteration ends with what came so far. */\n cancel(): void {\n if (this.finished) return;\n this.end();\n void this.started.then(() => perform({ action: 'cancel', stream: this.id })).catch(() => {});\n }\n\n private end(): void {\n if (this.finished) return;\n this.finished = true;\n this.ended();\n }\n}\n\n/**\n * A function the model may call while it answers (`Tool`): what it is\n * called and does, its arguments as a JSON schema (an object of properties:\n * strings, enums of strings, numbers, integers, booleans, arrays), and `call`,\n * whose answer the model reads (a string, or a value as JSON).\n */\nexport interface Tool<Arguments = Record<string, unknown>> {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n call(args: Arguments): unknown;\n}\n\nexport interface LanguageModelSessionOptions {\n model?: SystemLanguageModel;\n /** What the model is, does and avoids, followed over every prompt. */\n instructions?: string;\n /** Functions the model may call while it answers. */\n tools?: readonly Tool<never>[];\n}\n\n/**\n * A conversation with the model (`LanguageModelSession`): each prompt sees the\n * ones before it and their responses. One request at a time; another while it\n * responds fails with `concurrentRequests`.\n */\nexport class LanguageModelSession {\n readonly id = nextId++;\n readonly instructions: string | undefined;\n readonly tools: readonly Tool<never>[];\n private readonly opened: Promise<unknown>;\n private responses = 0;\n private closed = false;\n\n constructor(options: LanguageModelSessionOptions = {}) {\n this.instructions = options.instructions;\n this.tools = options.tools ?? [];\n const tools = this.tools.map(({ name, description, parameters }) => ({ name, description, parameters }));\n this.opened = perform({\n action: 'open',\n session: this.id,\n ...(options.instructions ? { instructions: options.instructions } : {}),\n ...(tools.length > 0 ? { tools } : {}),\n });\n this.opened.catch(() => {});\n if (tools.length > 0) void this.opened.then(() => this.serveTools()).catch(() => {});\n }\n\n /** Runs the model's tool calls as they come, until the session closes. */\n private async serveTools(): Promise<void> {\n while (!this.closed) {\n const request = await perform<{ call?: number; name?: string; arguments?: unknown; closed?: boolean }>({ action: 'toolCall', session: this.id });\n if (!request || request.closed || request.call === undefined) return;\n const tool = this.tools.find((candidate) => candidate.name === request.name);\n let answer: { output: string } | { error: string };\n try {\n if (!tool) throw new Error(`no tool named ${String(request.name)}`);\n const output = await (tool.call as (args: unknown) => unknown)(request.arguments ?? {});\n answer = { output: typeof output === 'string' ? output : JSON.stringify(output ?? null) };\n } catch (error) {\n answer = { error: error instanceof Error ? error.message : String(error) };\n }\n await perform({ action: 'toolResult', session: this.id, call: request.call, ...answer });\n }\n }\n\n /** Whether a response is under way. */\n get isResponding(): boolean {\n return this.responses > 0;\n }\n\n /** Loads the model ahead of the first prompt, so it answers sooner. */\n prewarm(): void {\n void this.opened.then(() => perform({ action: 'prewarm', session: this.id })).catch(() => {});\n }\n\n async respond(to: string, options?: GenerationOptionsSpec): Promise<Response> {\n this.responses += 1;\n try {\n await this.opened;\n return await perform<Response>({ action: 'respond', session: this.id, prompt: to, ...(options ? { options } : {}) });\n } finally {\n this.responses -= 1;\n }\n }\n\n streamResponse(to: string, options?: GenerationOptionsSpec): ResponseStream {\n this.responses += 1;\n return new ResponseStream(this, this.opened, to, options, () => {\n this.responses -= 1;\n });\n }\n\n /** Ends the session: the host lets its conversation go. */\n close(): void {\n if (this.closed) return;\n this.closed = true;\n void this.opened.then(() => perform({ action: 'close', session: this.id })).catch(() => {});\n }\n}\n","/**\n * `useWakeLock(active)`: the screen stays awake while `active` (a recording\n * under way, a recipe being followed), through the Screen Wake Lock API,\n * which a page has from the browser and a native app from the runtime\n * (`navigator.wakeLock` over the host's idle timer). A browser releases the\n * lock when the document hides; it is taken again when the document shows.\n * Returns whether a lock is held now; nothing happens, and false is\n * returned, where there is no `navigator.wakeLock`.\n */\n\nimport { useEffect, useState } from 'react';\n\ninterface WakeLockSentinelLike {\n released: boolean;\n release(): Promise<void>;\n addEventListener(type: 'release', listener: () => void): void;\n}\n\ninterface WakeLockLike {\n request(type: 'screen'): Promise<WakeLockSentinelLike>;\n}\n\n/** The API, from the page's or the runtime's `navigator`. */\nfunction wakeLockAPI(): WakeLockLike | null {\n const nav = (globalThis as { navigator?: { wakeLock?: WakeLockLike } }).navigator;\n return nav?.wakeLock ?? null;\n}\n\nexport function useWakeLock(active = true): boolean {\n const [held, setHeld] = useState(false);\n useEffect(() => {\n const api = wakeLockAPI();\n if (!active || !api) {\n setHeld(false);\n return;\n }\n let sentinel: WakeLockSentinelLike | null = null;\n let stopped = false;\n const acquire = (): void => {\n if (stopped || (sentinel && !sentinel.released)) return;\n api.request('screen').then(\n (next) => {\n if (stopped) {\n void next.release();\n return;\n }\n sentinel = next;\n setHeld(true);\n // The browser lets go when the document hides; `visibilitychange` below takes it back.\n next.addEventListener('release', () => {\n if (sentinel === next) setHeld(false);\n });\n },\n () => setHeld(false),\n );\n };\n const onVisible = (): void => {\n if (typeof document === 'undefined' || document.visibilityState === 'visible') acquire();\n };\n acquire();\n const doc = typeof document !== 'undefined' ? document : null;\n doc?.addEventListener('visibilitychange', onVisible);\n return () => {\n stopped = true;\n doc?.removeEventListener('visibilitychange', onVisible);\n if (sentinel && !sentinel.released) void sentinel.release();\n sentinel = null;\n setHeld(false);\n };\n }, [active]);\n return held;\n}\n","import type { ButtonRole, ButtonStyle, PickerStyle, SliderLabel, TextFieldStyle, ToggleStyle } from '@swiftbrowser/web/src/protocol';\nimport { Fragment, type ReactElement, type ReactNode } from 'react';\nimport { readBinding, type BindingValue } from '../binding';\nimport { useViewEnvironment, withEnvironment, type ControlSize } from '../environment';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, styled, takeModifier, toolbarPlacement, type ToolbarItemPlacementName, type ViewModifiers } from '../modifiers';\nimport { AttributedText, fromProtocolRuns, protocolRuns, type TextSelection } from '../attributedText';\nimport { color, opacity, type ColorValue } from '../values';\nimport { flattenChildren } from './stacks';\nimport { useKeyboardShortcut } from '../pointer';\nimport { Image, Text, type TextProps } from './text';\n\n// ---------------------------------------------------------------------------\n// Button\n// ---------------------------------------------------------------------------\n\nexport interface ButtonProps extends ViewModifiers {\n title?: string;\n role?: 'destructive' | 'cancel';\n action?: () => void;\n /** The label, when there is no `title`. */\n children?: ReactNode;\n /**\n * What `EditButton` sets: the edit mode the button shows and flips. The\n * `button` op carries it so a native renderer can draw the platform's edit\n * button (iOS's checkmark while editing); the web renderer draws the title.\n */\n editMode?: 'active' | 'inactive';\n}\n\nexport function Button(props: ButtonProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const environment = useViewEnvironment();\n const ownStyle = takeModifier(modifiers, 'buttonStyle');\n const ownSize = takeModifier(modifiers, 'controlSize');\n const style: ButtonStyle = ownStyle ?? environment.buttonStyle ?? 'automatic';\n const controlSize: ControlSize | undefined = ownSize ?? environment.controlSize;\n const buttonProps: Record<string, unknown> = { role: (own.role ?? null) as ButtonRole, style };\n if (controlSize !== undefined && controlSize !== 'regular') buttonProps['controlSize'] = controlSize;\n if (own.editMode !== undefined) buttonProps['editMode'] = own.editMode;\n const label = own.title !== undefined ? <Text>{own.title}</Text> : own.children;\n const tap = (): void => {\n own.action?.();\n environment.dismissAlert?.();\n };\n const shortcut = takeModifier(modifiers, 'keyboardShortcut');\n useKeyboardShortcut(typeof shortcut === 'string' ? { key: shortcut } : shortcut, () => {\n if (!buttonDisabled(modifiers)) tap();\n });\n return applyModifiers(sb('button', buttonProps, { tap }, label), modifiers);\n}\n\n// ---------------------------------------------------------------------------\n// Toggle\n// ---------------------------------------------------------------------------\n\nexport interface ToggleProps extends ViewModifiers {\n isOn: BindingValue<boolean>;\n onChange?: (isOn: boolean) => void;\n title?: string;\n children?: ReactNode;\n}\n\nexport function Toggle(props: ToggleProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const environment = useViewEnvironment();\n const style: ToggleStyle = takeModifier(modifiers, 'toggleStyle') ?? environment.toggleStyle ?? 'automatic';\n const [isOn, setOn] = readBinding(own.isOn, own.onChange);\n const label = own.title !== undefined ? <Text>{own.title}</Text> : own.children;\n const toggleProps: Record<string, unknown> = { isOn };\n if (style !== 'automatic') toggleProps['style'] = style;\n return applyModifiers(sb('toggle', toggleProps, { toggle: (event) => setOn(event.value) }, label), modifiers);\n}\n\n// ---------------------------------------------------------------------------\n// Picker\n// ---------------------------------------------------------------------------\n\nexport interface PickerOption<T> {\n label: string;\n tag: T;\n}\n\nexport interface PickerProps<T> extends ViewModifiers {\n label: string;\n selection: BindingValue<T>;\n onChange?: (value: T) => void;\n /** The options, or `<Text tag={…}>` children (a `Text` without a tag is tagged with its string). */\n options?: readonly (T | PickerOption<T>)[];\n children?: ReactNode;\n}\n\nexport function Picker<T>(props: PickerProps<T>): ReactNode {\n const { own, modifiers } = splitProps(props);\n const environment = useViewEnvironment();\n const ownStyle = takeModifier(modifiers, 'pickerStyle');\n const style: PickerStyle = ownStyle ?? environment.pickerStyle ?? 'menu';\n const [selection, setSelection] = readBinding(own.selection, own.onChange);\n const options = pickerOptions<T>(own.options, own.children);\n const selected = Math.max(\n 0,\n options.findIndex((option) => Object.is(option.tag, selection)),\n );\n return applyModifiers(\n sb(\n 'picker',\n { style, label: own.label, options: options.map((option) => option.label), selected },\n { select: (event) => options[event.value] && setSelection(options[event.value]!.tag) },\n ),\n modifiers,\n );\n}\n\nfunction pickerOptions<T>(options: readonly (T | PickerOption<T>)[] | undefined, children: ReactNode): PickerOption<T>[] {\n if (options) {\n return options.map((option) =>\n typeof option === 'object' && option !== null && 'label' in option && 'tag' in option\n ? (option as PickerOption<T>)\n : { label: String(option), tag: option as T },\n );\n }\n return flattenChildren(children).map((element) => {\n const label = plainText(element);\n const tag = (element.props as { tag?: T }).tag;\n return { label, tag: (tag !== undefined ? tag : label) as T };\n });\n}\n\n/** The string of a `<Text>` element (other elements read as their title, else \"\"). */\nexport function plainText(element: ReactElement): string {\n const props = element.props as TextProps & { title?: unknown };\n if (element.type === Text) return collectText(props.children);\n if (typeof props.title === 'string') return props.title;\n return '';\n}\n\nfunction collectText(node: ReactNode): string {\n if (node === null || node === undefined || typeof node === 'boolean') return '';\n if (typeof node === 'string' || typeof node === 'number') return String(node);\n if (Array.isArray(node)) return node.map(collectText).join('');\n if (typeof node === 'object' && 'props' in node) {\n const element = node as ReactElement<{ children?: ReactNode }>;\n if (element.type === Fragment || element.type === Text) return collectText(element.props.children);\n }\n return '';\n}\n\n// ---------------------------------------------------------------------------\n// Slider, Stepper\n// ---------------------------------------------------------------------------\n\nexport interface SliderProps extends ViewModifiers {\n value: BindingValue<number>;\n onChange?: (value: number) => void;\n /** `onEditingChanged`: true as a drag begins, false as it ends (a scrubber stops following the position while the thumb is held). */\n onEditingChanged?: (editing: boolean) => void;\n /** `in: 0...1` */\n range?: readonly [number, number];\n step?: number;\n /** What the slider is for: VoiceOver reads it; iOS (and so the page) does not draw it. */\n label?: ReactNode;\n /** Drawn at the track's leading end (an icon, a value). */\n minimumValueLabel?: ReactNode;\n maximumValueLabel?: ReactNode;\n}\n\nexport function Slider(props: SliderProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const environment = useViewEnvironment();\n const [value, setValue] = readBinding(own.value, own.onChange);\n const [min, max] = own.range ?? [0, 1];\n const labels: SliderLabel[] = [];\n const children: ReactNode[] = [];\n if (own.label !== undefined && !environment.labelsHidden) {\n labels.push('label');\n children.push(<Fragment key=\"label\">{own.label}</Fragment>);\n }\n if (own.minimumValueLabel !== undefined || own.maximumValueLabel !== undefined) {\n labels.push('min', 'max');\n children.push(<Fragment key=\"min\">{own.minimumValueLabel}</Fragment>, <Fragment key=\"max\">{own.maximumValueLabel}</Fragment>);\n }\n return applyModifiers(\n sb(\n 'slider',\n { value, min, max, step: own.step ?? null, labels },\n {\n slide: (event) => {\n if (event.editing === true) own.onEditingChanged?.(true);\n setValue(event.value);\n if (event.editing === false) own.onEditingChanged?.(false);\n },\n },\n children.length ? children : undefined,\n ),\n modifiers,\n );\n}\n\nexport interface StepperProps extends ViewModifiers {\n value: BindingValue<number>;\n onChange?: (value: number) => void;\n /** `in: 1...10` */\n range?: readonly [number, number];\n step?: number;\n title?: string;\n children?: ReactNode;\n}\n\nexport function Stepper(props: StepperProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const [value, setValue] = readBinding(own.value, own.onChange);\n const step = own.step ?? 1;\n const [min, max] = own.range ?? [-Infinity, Infinity];\n const label = own.title !== undefined ? <Text>{own.title}</Text> : own.children;\n return applyModifiers(\n sb(\n 'stepper',\n { canIncrement: value < max, canDecrement: value > min },\n { step: (event) => setValue(Math.min(max, Math.max(min, value + Math.sign(event.value) * step))) },\n label,\n ),\n modifiers,\n );\n}\n\n// ---------------------------------------------------------------------------\n// Text fields\n// ---------------------------------------------------------------------------\n\nexport interface TextFieldBaseProps extends ViewModifiers {\n /** The placeholder (SwiftUI's title). */\n placeholder?: string;\n text: BindingValue<string>;\n onChange?: (text: string) => void;\n onSubmit?: () => void;\n /**\n * Backspace with nothing selected and the caret at the start of the text\n * (an empty field included): there is nothing for the key to delete, so\n * the app hears it, to merge the field into what comes before it, say.\n */\n onDeleteBackward?: () => void;\n textFieldStyle?: TextFieldStyle;\n secure?: boolean;\n axis?: 'vertical';\n}\n\nexport type TextFieldProps<F extends FocusValue = FocusValue> = TextFieldBaseProps & FocusProps<F>;\n\n/**\n * `TextField(\"Name\", text:)`. Overloads for the two focus bindings\n * (`FocusProps`) rather than their union alone, so an inline binding's\n * setter still infers its type.\n */\nexport function TextField(props: TextFieldBaseProps & BoundFocusProps): ReactNode;\nexport function TextField<F extends FocusValue>(props: TextFieldBaseProps & SharedFocusProps<F>): ReactNode;\nexport function TextField(props: TextFieldProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const environment = useViewEnvironment();\n const ownSubmitLabel = takeModifier(modifiers, 'submitLabel');\n // The text input hints written on the field itself, over the environment's.\n const keyboardType = takeModifier(modifiers, 'keyboardType');\n const textContentType = takeModifier(modifiers, 'textContentType');\n const autocapitalization = takeModifier(modifiers, 'textInputAutocapitalization');\n const autocorrectionDisabled = takeModifier(modifiers, 'autocorrectionDisabled');\n const hints = {\n ...environment.textInputHints,\n ...(keyboardType !== undefined ? { keyboard: keyboardType } : {}),\n ...(textContentType !== undefined ? { contentType: textContentType ?? undefined } : {}),\n ...(autocapitalization !== undefined ? { autocapitalization: autocapitalization ?? undefined } : {}),\n ...(autocorrectionDisabled !== undefined ? { autocorrectionDisabled } : {}),\n };\n const [text, setText] = readBinding(own.text, own.onChange);\n const fieldProps: Record<string, unknown> = {\n text,\n placeholder: own.placeholder ?? '',\n style: own.textFieldStyle ?? 'plain',\n secure: own.secure ?? false,\n };\n if (own.onSubmit) fieldProps['submit'] = true;\n if (own.onDeleteBackward) fieldProps['deleteBackward'] = true;\n if (own.axis) fieldProps['axis'] = own.axis;\n const submitLabel = ownSubmitLabel ?? environment.submitLabel;\n if (submitLabel) fieldProps['submitLabel'] = submitLabel;\n if (hints.keyboard && hints.keyboard !== 'default') fieldProps['keyboard'] = hints.keyboard;\n if (hints.contentType) fieldProps['contentType'] = hints.contentType;\n if (hints.autocapitalization) fieldProps['autocapitalization'] = hints.autocapitalization;\n if (hints.autocorrectionDisabled) fieldProps['autocorrectionDisabled'] = true;\n const focus = focusBinding(own);\n if (focus) fieldProps['focused'] = focus[0];\n return applyModifiers(\n sb('textfield', fieldProps, {\n text: (event) => setText(event.value),\n submit: () => own.onSubmit?.(),\n deletebackward: () => own.onDeleteBackward?.(),\n focus: (event) => focus?.[1](event.value),\n }),\n modifiers,\n );\n}\n\nexport function SecureField(props: Omit<TextFieldBaseProps & BoundFocusProps, 'secure'>): ReactNode;\nexport function SecureField<F extends FocusValue>(props: Omit<TextFieldBaseProps & SharedFocusProps<F>, 'secure'>): ReactNode;\nexport function SecureField(props: Omit<TextFieldProps, 'secure'>): ReactNode {\n // The union is one of the overloads' props; the cast picks one for the spread.\n return <TextField {...(props as TextFieldBaseProps & BoundFocusProps)} secure />;\n}\n\n// ---------------------------------------------------------------------------\n// Focus\n// ---------------------------------------------------------------------------\n\n/** `@FocusState var field: Field?`: what stands for a field among those sharing one focus binding. */\nexport type FocusValue = string | number;\n\n/**\n * `.focused($isFocused)`: the field takes the focus while true, and sets it\n * as the viewer focuses or leaves it. A value the app sets from `onSubmit`\n * (true again) wins over the keyboard's dismissal, and a field that takes\n * the focus is scrolled into view.\n */\nexport interface BoundFocusProps {\n focused?: BindingValue<boolean>;\n focusedValue?: undefined;\n}\n\n/**\n * `.focused($field, equals: value)`: the binding holds the focused field's\n * value (null for none) and is shared by the fields, each naming its own\n * with `focusedValue`. A field taking the focus sets its value; one losing\n * it clears the value only while it is still its own, so a handler for\n * `onSubmit` that moved the focus to another field (or set this one's\n * again) wins over the keyboard's dismissal, and the field it names is\n * scrolled into view.\n */\nexport interface SharedFocusProps<F extends FocusValue> {\n focused: BindingValue<F | null>;\n focusedValue: F;\n}\n\nexport type FocusProps<F extends FocusValue = FocusValue> = BoundFocusProps | SharedFocusProps<F>;\n\n/**\n * A field's own focus over its `FocusProps` (read loosely: `splitProps`\n * flattens the union): whether it has the focus, and the setter for a change\n * the renderer reports; null when unbound.\n */\nexport function focusBinding<F extends FocusValue>(props: { focused?: BindingValue<boolean> | BindingValue<F | null> | undefined; focusedValue?: F | undefined }): [boolean, (on: boolean) => void] | null {\n if (props.focused === undefined) return null;\n if (props.focusedValue === undefined) return readBinding(props.focused as BindingValue<boolean>);\n const value = props.focusedValue;\n const [current, set] = readBinding(props.focused as BindingValue<F | null>);\n return [\n current === value,\n (on) => {\n if (on) set(value);\n else if (current === value) set(null);\n },\n ];\n}\n\n// ---------------------------------------------------------------------------\n// ProgressView\n// ---------------------------------------------------------------------------\n\nexport interface ProgressViewProps extends ViewModifiers {\n /** Determinate progress (`value / total`); absent: the spinning indicator. */\n value?: number;\n total?: number;\n label?: ReactNode;\n currentValueLabel?: ReactNode;\n /** The label, as children. */\n children?: ReactNode;\n}\n\nexport function ProgressView(props: ProgressViewProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n if (own.value === undefined) {\n return applyModifiers(\n styled({ foreground: { hierarchical: 2 } }, styled({ font: { size: 20 } }, <Image systemName=\"progress.indicator\" />)),\n modifiers,\n );\n }\n const label = own.label ?? own.children;\n const children: ReactNode[] = [];\n if (label !== undefined && label !== null) children.push(<Fragment key=\"label\">{label}</Fragment>);\n if (own.currentValueLabel !== undefined && own.currentValueLabel !== null) {\n children.push(<Fragment key=\"current\">{styled({ foreground: { hierarchical: 2 } }, own.currentValueLabel)}</Fragment>);\n }\n return applyModifiers(\n sb(\n 'gauge',\n { value: own.value / (own.total ?? 1), style: 'progress', hasLabel: true, hasCurrentValueLabel: true },\n undefined,\n children.length ? children : undefined,\n ),\n modifiers,\n );\n}\n\n// ---------------------------------------------------------------------------\n// Toolbar\n// ---------------------------------------------------------------------------\n\nexport interface ToolbarItemProps {\n placement?: ToolbarItemPlacementName;\n /** `.sharedBackgroundVisibility(_:)`: `hidden` draws the item without the bar's shared glass. */\n sharedBackgroundVisibility?: 'automatic' | 'visible' | 'hidden';\n children?: ReactNode;\n}\n\n/**\n * `ToolbarItem(placement:) { }`, inside a `toolbar` modifier. A `Label` in\n * it shows its icon alone, its title the icon's accessible name, as iOS\n * draws a bar's labels (and as the Swift shim's bars do); a `Label` given\n * `labelStyle=\"titleAndIcon\"` shows both, and a `Menu`'s items keep theirs,\n * as do `secondaryAction` items, which an iPhone lists in its More menu.\n */\nexport function ToolbarItem(props: ToolbarItemProps): ReactNode {\n const hidden = props.sharedBackgroundVisibility === 'hidden';\n const placement = toolbarPlacement(props.placement);\n // `.secondaryAction` items are the More button's menu rows on an iPhone, a Label's title beside its icon there:\n // they keep their Labels whole (the native renderer's SwiftUI draws a Label in a bar as its icon by itself).\n const items = placement === 'secondary' ? props.children : withEnvironment({ labelStyle: 'iconOnly' }, props.children);\n return sb('toolbar', hidden ? { placement, sharedBackground: 'hidden' } : { placement }, undefined, items);\n}\n\nexport const ToolbarItemGroup = ToolbarItem;\n\nexport interface ToolbarSpacerProps {\n /**\n * `flexible` (the default) shares the room the groups leave, pushing them\n * apart; `fixed` is a standard gap (8 in a bottom bar, 12 in the\n * navigation bar) and keeps the row centered.\n */\n sizing?: 'flexible' | 'fixed';\n placement?: ToolbarItemPlacementName;\n}\n\n/**\n * `ToolbarSpacer(_:placement:)` (iOS 26), inside a `toolbar` modifier: ends\n * the glass capsule of the items before it, so the items after it float on\n * a capsule of their own, in the navigation bar as in a bottom bar.\n */\nexport function ToolbarSpacer(props: ToolbarSpacerProps): ReactNode {\n return sb('toolbar', { placement: toolbarPlacement(props.placement), spacer: props.sizing ?? 'flexible' });\n}\n\n// ---------------------------------------------------------------------------\n// DatePicker, TextEditor\n// ---------------------------------------------------------------------------\n\nexport type DatePickerComponents = 'date' | 'hourAndMinute' | 'dateAndTime';\n\nexport interface DatePickerProps extends ViewModifiers {\n label?: string;\n selection: BindingValue<Date>;\n onChange?: (date: Date) => void;\n /** `displayedComponents:`; `date` by default. */\n displayedComponents?: DatePickerComponents;\n /** `in:` bounds. */\n range?: readonly [Date | null, Date | null];\n /** The IANA time zone the date and time are shown and edited in (`.environment(\\\\.timeZone)`); the viewer's when absent. */\n timeZone?: string;\n}\n\n/** `DatePicker(\"Date\", selection:)`: the compact style, with the browser's native pickers. */\nexport function DatePicker(props: DatePickerProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const environment = useViewEnvironment();\n const [date, setDate] = readBinding(own.selection, own.onChange);\n const labelsHidden = takeModifier(modifiers, 'labelsHidden') ?? environment.labelsHidden ?? false;\n const seconds = (value: Date | null | undefined): number | null => (value ? Math.floor(value.getTime() / 1000) : null);\n const pickerProps: Record<string, unknown> = {\n seconds: seconds(date) ?? 0,\n components: own.displayedComponents ?? 'date',\n min: seconds(own.range?.[0]),\n max: seconds(own.range?.[1]),\n };\n if (labelsHidden) pickerProps['labelsHidden'] = true;\n if (own.timeZone) pickerProps['timeZone'] = own.timeZone;\n const label = labelsHidden || own.label === undefined ? undefined : <Text>{own.label}</Text>;\n return applyModifiers(sb('datepicker', pickerProps, { date: (event) => setDate(new Date(event.value * 1000)) }, label), modifiers);\n}\n\ninterface TextEditorBaseProps extends ViewModifiers {\n /**\n * `TextEditor(text:selection:)`, on a plain editor or a rich one: the\n * editor writes the selection as the viewer moves the caret or selects\n * (UTF-16 offsets into the text), and one the app sets moves the caret\n * (when the app focuses the editor, if it is not focused).\n */\n selection?: BindingValue<TextSelection>;\n /**\n * Ranges drawn marked, a color behind their characters (UTF-16 offsets): a graph's selected node in its source, a\n * find's matches. They are the view's alone: the caret and the selection stay where they are, nothing takes the\n * focus (so no keyboard comes up), and the text the editor writes back carries none of them. Drawn by the rich\n * editor (`AttributedText`), on every renderer; a plain editor on a page has no way to draw them.\n */\n marks?: TextMark[];\n /** As a `TextField`'s: Backspace with the caret at the start of the text and nothing selected. */\n onDeleteBackward?: () => void;\n}\n\n/** A marked range of an editor's text: UTF-16 offsets, and the color behind it (the accent at a quarter, by default). */\nexport interface TextMark {\n start: number;\n end: number;\n color?: ColorValue;\n}\n\nexport interface PlainTextEditorProps extends TextEditorBaseProps {\n text: BindingValue<string>;\n onChange?: (text: string) => void;\n}\n\n/** A rich editor: its text is `AttributedText`, drawn with each run's attributes. */\nexport interface AttributedTextEditorProps extends TextEditorBaseProps {\n text: BindingValue<AttributedText>;\n onChange?: (text: AttributedText) => void;\n}\n\n/** The editor's props with a focus binding as a `TextField`'s (`FocusProps`). */\nexport type TextEditorProps<F extends FocusValue = FocusValue> = (PlainTextEditorProps | AttributedTextEditorProps) & FocusProps<F>;\n\n/**\n * `TextEditor(text:)`: a multi-line field filling its proposal (as tall as\n * its lines under `.scrollDisabled(true)`). Given `AttributedText` it is\n * the rich editor: what the viewer types takes the attributes of the text\n * around it (`AttributedText.replacingCharacters`). Overloads (the text,\n * then the focus binding) rather than the union alone, so an inline\n * binding's setter still infers its type.\n */\nexport function TextEditor(props: PlainTextEditorProps & BoundFocusProps): ReactNode;\nexport function TextEditor<F extends FocusValue>(props: PlainTextEditorProps & SharedFocusProps<F>): ReactNode;\nexport function TextEditor(props: AttributedTextEditorProps & BoundFocusProps): ReactNode;\nexport function TextEditor<F extends FocusValue>(props: AttributedTextEditorProps & SharedFocusProps<F>): ReactNode;\nexport function TextEditor(props: TextEditorProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const [text, setText] = readBinding(own.text as BindingValue<string | AttributedText>, own.onChange as ((text: string | AttributedText) => void) | undefined);\n const focus = focusBinding(own);\n const selection = own.selection !== undefined ? readBinding(own.selection) : null;\n const rich = typeof text !== 'string';\n const editor: Record<string, unknown> = { text: rich ? AttributedText.plain(text) : text };\n if (rich) editor['runs'] = protocolRuns(text);\n if (focus) editor['focused'] = focus[0];\n if (selection) editor['selection'] = { start: selection[0].start, end: selection[0].end };\n if (own.onDeleteBackward) editor['deleteBackward'] = true;\n if (own.marks && own.marks.length > 0) editor['marks'] = own.marks.map((mark) => ({ start: mark.start, end: mark.end, color: color(mark.color ?? MARK_COLOR) }));\n return applyModifiers(\n sb('texteditor', editor, {\n text: (event) => setText(rich ? AttributedText.replacingCharacters(text, event.value) : event.value),\n deletebackward: () => own.onDeleteBackward?.(),\n // The native editor's own Bold, Italic or Underline over the text (iOS 26's edit menu): the runs it now shows.\n runs: (event) => {\n if (rich) setText(fromProtocolRuns(event.value));\n },\n focus: (event) => focus?.[1](event.value),\n selection: (event) => selection?.[1](event.value),\n }),\n modifiers,\n );\n}\n\n/** A mark's color when it names none: the accent at a quarter. */\nconst MARK_COLOR: ColorValue = opacity('accent', 0.25);\n\n/** A `disabled` modifier on the button itself turns its shortcut off too. */\nfunction buttonDisabled(modifiers: readonly [string, unknown][]): boolean {\n return modifiers.some(([key, value]) => key === 'disabled' && value === true);\n}\n","import type { ShapeKind, Stroke } from '@swiftbrowser/web/src/protocol';\nimport { useRef, useState, type ReactNode } from 'react';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, type ShapeSpec, type ViewModifiers } from '../modifiers';\nimport { Path, type CGRect } from '../path';\nimport { ColorValues, color, shapeStyle, type ColorValue, type StyleValue } from '../values';\n\nexport interface StrokeSpec {\n style?: StyleValue;\n lineWidth?: number;\n dash?: number[];\n dashPhase?: number;\n lineCap?: 'butt' | 'round' | 'square';\n lineJoin?: 'miter' | 'round' | 'bevel';\n miterLimit?: number;\n}\n\nexport type StrokeValue = StyleValue | StrokeSpec;\n\nexport interface ShapeProps extends ViewModifiers {\n /** `.fill(_:)`; without a fill or stroke the shape draws in the foreground color. */\n fill?: StyleValue;\n /** `.stroke(_:lineWidth:)` */\n stroke?: StrokeValue;\n /** `.strokeBorder(_:style:)`: the stroke inside the bounds. */\n strokeBorder?: StrokeValue;\n trim?: { from: number; to: number };\n}\n\nconst STYLE_KEYS = ['r', 'name', 'named', 'hierarchical', 'linearGradient', 'radialGradient', 'angularGradient', 'colorGradient', 'material'];\n\nfunction strokeOf(value: StrokeValue | undefined, inset: boolean): Stroke | null {\n if (value === undefined) return null;\n const isSpec = typeof value === 'object' && value !== null && !STYLE_KEYS.some((key) => key in value);\n const spec: StrokeSpec = isSpec ? (value as StrokeSpec) : { style: value as StyleValue };\n const stroke: Stroke = { color: shapeStyle(spec.style ?? 'primary'), lineWidth: spec.lineWidth ?? 1 };\n if (inset) stroke.inset = true;\n if (spec.dash) stroke.dash = spec.dash;\n if (spec.dashPhase !== undefined) stroke.dashPhase = spec.dashPhase;\n if (spec.lineCap) stroke.lineCap = spec.lineCap;\n if (spec.lineJoin) stroke.lineJoin = spec.lineJoin;\n if (spec.miterLimit !== undefined) stroke.miterLimit = spec.miterLimit;\n return stroke;\n}\n\nfunction shape(kind: ShapeKind, cornerRadius: number, props: ShapeProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const shapeProps: Record<string, unknown> = {\n shape: kind,\n cornerRadius,\n fill: own.fill !== undefined ? shapeStyle(own.fill) : null,\n stroke: strokeOf(own.strokeBorder, true) ?? strokeOf(own.stroke, false),\n };\n if (own.trim) shapeProps['trim'] = own.trim;\n return applyModifiers(sb('shape', shapeProps), modifiers);\n}\n\n/** Capsules, circles and ellipses carry this radius, like the shim. */\nconst ROUND = 9999;\n\nexport function Rectangle(props: ShapeProps): ReactNode {\n return shape('rectangle', 0, props);\n}\nRectangle.shape = { kind: 'rectangle', cornerRadius: 0 } satisfies ShapeSpec;\n\nexport interface RoundedRectangleProps extends ShapeProps {\n cornerRadius: number;\n}\n\nexport function RoundedRectangle(props: RoundedRectangleProps): ReactNode {\n const { cornerRadius, ...rest } = props;\n return shape('roundedRectangle', cornerRadius, rest);\n}\nRoundedRectangle.shape = { kind: 'roundedRectangle', cornerRadius: null } satisfies ShapeSpec;\n\nexport function Circle(props: ShapeProps): ReactNode {\n return shape('circle', ROUND, props);\n}\nCircle.shape = { kind: 'circle', cornerRadius: ROUND } satisfies ShapeSpec;\n\nexport function Capsule(props: ShapeProps): ReactNode {\n return shape('capsule', ROUND, props);\n}\nCapsule.shape = { kind: 'capsule', cornerRadius: ROUND } satisfies ShapeSpec;\n\nexport function Ellipse(props: ShapeProps): ReactNode {\n return shape('ellipse', ROUND, props);\n}\nEllipse.shape = { kind: 'ellipse', cornerRadius: ROUND } satisfies ShapeSpec;\n\nexport interface ContainerRelativeShapeProps extends ShapeProps {\n /** The container's corner radius (a widget's, a card's). */\n cornerRadius?: number;\n}\n\n/** `ContainerRelativeShape`: a rounded rectangle with its container's corners. */\nexport function ContainerRelativeShape(props: ContainerRelativeShapeProps): ReactNode {\n const { cornerRadius, ...rest } = props;\n return shape('containerRelative', cornerRadius ?? 0, rest);\n}\nContainerRelativeShape.shape = { kind: 'containerRelative', cornerRadius: null } satisfies ShapeSpec;\n\n// ---------------------------------------------------------------------------\n// Custom shapes\n// ---------------------------------------------------------------------------\n\nexport interface CustomShapeProps extends Omit<ShapeProps, 'trim'> {\n /** `path(in:)`: the shape's path for a rectangle of the size it is laid out at. */\n path: (rect: CGRect) => Path;\n /** `FillStyle(eoFill: true)` */\n evenOdd?: boolean;\n}\n\n/**\n * A custom `Shape`. A path whose every number is affine in the rectangle's\n * size (a point a fraction of the way across, a margin in from an edge) is\n * sent once as that (`affinePath`), and the page draws it at whatever size the\n * shape is laid out at, from its first frame. Any other path waits for the\n * element to report its laid-out size, and is drawn for that size, as the\n * Swift shim does. A shape whose path was once not affine is not probed again\n * (the probe draws the path at six sizes, the most of a busy page's render):\n * it is drawn for its reported size from then on, which is right for any path.\n */\nexport function Shape(props: CustomShapeProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const [size, setSize] = useState<{ width: number; height: number } | null>(null);\n // Once not affine, drawn for its size for good: the probe is not run again.\n const sized = useRef(false);\n const affine = sized.current ? null : affinePath(own.path);\n if (affine === null) sized.current = true;\n const shapeProps: Record<string, unknown> = {\n shape: 'path',\n cornerRadius: 0,\n fill: own.fill !== undefined ? shapeStyle(own.fill) : null,\n // A custom shape's border is its path stroked as is (the shim insets an InsettableShape first).\n stroke: strokeOf(own.strokeBorder ?? own.stroke, false),\n reportsSize: affine === null,\n path: affine === null && size ? own.path({ x: 0, y: 0, width: size.width, height: size.height }).svg() : '',\n size: (affine === null && size) || { width: 0, height: 0 },\n };\n if (affine) shapeProps['affinePath'] = affine;\n if (own.evenOdd) shapeProps['fillRule'] = 'evenodd';\n return applyModifiers(\n sb(\n 'shape',\n shapeProps,\n affine\n ? undefined\n : {\n geometry: (event) => {\n if (!size || size.width !== event.width || size.height !== event.height) setSize({ width: event.width, height: event.height });\n },\n },\n ),\n modifiers,\n );\n}\n\n/**\n * A path as its numbers' parts: SVG path data with each number its value for\n * an empty rectangle, and how much each grows a point of the rectangle's width\n * and of its height.\n */\nexport interface AffinePath {\n path: string;\n width: number[];\n height: number[];\n}\n\n/** A number in SVG path data, as `Path` writes them. */\nconst NUMBER = /(-?(?:\\d+\\.?\\d*|\\.\\d+)(?:e[-+]?\\d+)?)/;\n/** The sizes a path's parts are worked out from (a large one, a point each way apart): */\nconst BASE = 1000;\n/** and the sizes they are checked at, a tiny one among them (where a clamp, as a corner's to half the side, shows). */\nconst CHECKS: readonly [number, number][] = [\n [613, 389],\n [257, 911],\n [3, 2],\n];\n\n/**\n * `path` as an `AffinePath`, or null where it is not one: where its commands\n * change with the size, or a number is not the same straight function of the\n * width and height at every size it is checked at (to the hundredth a point\n * the data is rounded to).\n */\nexport function affinePath(path: (rect: CGRect) => Path): AffinePath | null {\n try {\n const at = (width: number, height: number): string[] => path({ x: 0, y: 0, width, height }).svg().split(NUMBER);\n const base = at(BASE, BASE);\n const wider = at(2 * BASE, BASE);\n const taller = at(BASE, 2 * BASE);\n const same = (parts: string[]): boolean => parts.length === base.length && parts.every((part, i) => i % 2 === 1 || part === base[i]);\n if (!same(wider) || !same(taller)) return null;\n const round = (n: number, places: number): number => Math.round(n * 10 ** places) / 10 ** places || 0;\n const count = (base.length - 1) / 2;\n const width: number[] = [];\n const height: number[] = [];\n const constant: number[] = [];\n for (let i = 0; i < count; i += 1) {\n const n = Number(base[2 * i + 1]);\n width.push(round((Number(wider[2 * i + 1]) - n) / BASE, 6));\n height.push(round((Number(taller[2 * i + 1]) - n) / BASE, 6));\n constant.push(round(n - BASE * width[i]! - BASE * height[i]!, 4));\n }\n for (const [w, h] of CHECKS) {\n const parts = at(w, h);\n if (!same(parts)) return null;\n for (let i = 0; i < count; i += 1) {\n if (Math.abs(constant[i]! + w * width[i]! + h * height[i]! - Number(parts[2 * i + 1])) > 0.02) return null;\n }\n }\n const text = base.map((part, i) => (i % 2 === 1 ? String(constant[(i - 1) / 2]) : part)).join('');\n if (constant.some((n) => !Number.isFinite(n))) return null;\n return { path: text, width, height };\n } catch {\n return null;\n }\n}\n\nexport interface UnevenRoundedRectangleProps extends ShapeProps {\n topLeadingRadius?: number;\n bottomLeadingRadius?: number;\n bottomTrailingRadius?: number;\n topTrailingRadius?: number;\n}\n\n/** `UnevenRoundedRectangle`: a custom shape with a radius per corner. */\nexport function UnevenRoundedRectangle(props: UnevenRoundedRectangleProps): ReactNode {\n const { topLeadingRadius = 0, bottomLeadingRadius = 0, bottomTrailingRadius = 0, topTrailingRadius = 0, trim: _trim, ...rest } = props;\n const path = (rect: CGRect): Path => {\n const clamp = (radius: number): number => Math.max(0, Math.min(radius, rect.width / 2, rect.height / 2));\n const tl = clamp(topLeadingRadius);\n const tr = clamp(topTrailingRadius);\n const br = clamp(bottomTrailingRadius);\n const bl = clamp(bottomLeadingRadius);\n const { width: w, height: h } = rect;\n const p = new Path().move({ x: tl, y: 0 }).addLine({ x: w - tr, y: 0 });\n if (tr) p.addArc({ x: w - tr, y: tr }, tr, -90, 0, false);\n p.addLine({ x: w, y: h - br });\n if (br) p.addArc({ x: w - br, y: h - br }, br, 0, 90, false);\n p.addLine({ x: bl, y: h });\n if (bl) p.addArc({ x: bl, y: h - bl }, bl, 90, 180, false);\n p.addLine({ x: 0, y: tl });\n if (tl) p.addArc({ x: tl, y: tl }, tl, 180, 270, false);\n return p.closeSubpath();\n };\n return <Shape {...rest} path={path} />;\n}\n\n// ---------------------------------------------------------------------------\n// Color as a view\n// ---------------------------------------------------------------------------\n\nexport interface ColorViewProps extends ViewModifiers {\n color: ColorValue;\n}\n\n/** `Color.red` as a view: a box of the color that fills its proposal. */\nfunction ColorView(props: ColorViewProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n return applyModifiers(sb('color', { color: color(own.color) }), modifiers);\n}\n\n/**\n * `Color`: as a view, `<Color color=\"red\" />`; as values, `Color.red`,\n * `Color.opacity('black', 0.2)`, `Color.gradient('teal')`, `Color.hex('#336699')`.\n */\nexport const Color: typeof ColorView & typeof ColorValues = Object.assign(ColorView, ColorValues);\n","/**\n * Sign in with Apple: `signInWithApple()` asks the viewer and resolves with\n * the credential (`ASAuthorizationAppleIDCredential`'s fields: the stable\n * `user`, the name and email shared the first time, the identity token and\n * authorization code for the app's server), `appleCredentialState(user)` asks\n * what the credential is now, and `SignInWithAppleButton` is SwiftUI's\n * button, drawn from a button, the Apple logo and the label in the black,\n * white or white-outline style. Natively the system sheet answers; on a page\n * Apple's JS does, once the app named its Services ID and return URL with\n * `configureSignInWithApple` (both registered with Apple for the domain), and\n * without that the request fails `unsupported:`.\n */\n\nimport type { AppleCredentialState, AppleIDCredential } from '@swiftbrowser/web/src/hostRequests';\nimport { browserEnvironment } from '@swiftbrowser/web/src/hostRequests';\nimport { configureSignInWithApple } from '@swiftbrowser/web/src/appleSignIn';\nimport { type ReactNode } from 'react';\nimport { splitProps, type ViewModifiers } from './modifiers';\nimport { Button } from './components/controls';\nimport { HStack } from './components/stacks';\nimport { Image, Text } from './components/text';\nimport { RoundedRectangle } from './components/shapes';\nimport { system } from './values';\n\nexport type { AppleCredentialState, AppleIDCredential };\nexport { configureSignInWithApple };\n\nexport interface SignInWithAppleOptions {\n /** What to ask the viewer to share; both by default. Shared the first time only, as on iOS. */\n scopes?: ('fullName' | 'email')[];\n /** A nonce the identity token carries, for the app's server to check. */\n nonce?: string;\n /** Echoed back in the credential. */\n state?: string;\n}\n\n/** Whether this page or app can sign in with Apple (natively always; on a page once configured). */\nexport function canSignInWithApple(): boolean {\n return browserEnvironment.appleSignIn !== undefined;\n}\n\nexport async function signInWithApple(options: SignInWithAppleOptions = {}): Promise<AppleIDCredential> {\n const host = browserEnvironment.appleSignIn;\n if (!host) throw new Error('unsupported: Sign in with Apple is not available here (configureSignInWithApple on a page)');\n return host.signIn({ scopes: options.scopes ?? ['fullName', 'email'], ...(options.nonce ? { nonce: options.nonce } : {}), ...(options.state ? { state: options.state } : {}) });\n}\n\n/** `ASAuthorizationAppleIDProvider.credentialState(forUserID:)`; `unknown` where the host cannot ask (a page). */\nexport async function appleCredentialState(user: string): Promise<AppleCredentialState> {\n const host = browserEnvironment.appleSignIn;\n if (!host) return 'unknown';\n return host.credentialState(user);\n}\n\nexport type SignInWithAppleLabel = 'signIn' | 'signUp' | 'continue';\nexport type SignInWithAppleStyle = 'black' | 'white' | 'whiteOutline';\n\nexport interface SignInWithAppleButtonProps extends ViewModifiers {\n /** `.signIn` (\"Sign in with Apple\"), `.signUp` or `.continue`. */\n label?: SignInWithAppleLabel;\n /** `.signInWithAppleButtonStyle`: `black` by default. */\n style?: SignInWithAppleStyle;\n /** What to ask for: `onRequest` on iOS. Both scopes by default. */\n scopes?: ('fullName' | 'email')[];\n nonce?: string;\n state?: string;\n /** The credential, or the error (`cancelled: …` when the viewer dismissed the sheet). */\n onCompletion: (result: { credential: AppleIDCredential; error?: undefined } | { credential?: undefined; error: Error }) => void;\n}\n\nconst LABELS: Record<SignInWithAppleLabel, string> = { signIn: 'Sign in with Apple', signUp: 'Sign up with Apple', continue: 'Continue with Apple' };\n\nexport function SignInWithAppleButton(props: SignInWithAppleButtonProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const style = own.style ?? 'black';\n const background = style === 'black' ? 'black' : 'white';\n const foreground = style === 'black' ? 'white' : 'black';\n const action = (): void => {\n signInWithApple({ ...(own.scopes ? { scopes: own.scopes } : {}), ...(own.nonce ? { nonce: own.nonce } : {}), ...(own.state ? { state: own.state } : {}) }).then(\n (credential) => own.onCompletion({ credential }),\n (error: unknown) => own.onCompletion({ error: error instanceof Error ? error : new Error(String(error)) }),\n );\n };\n return (\n <Button\n action={action}\n buttonStyle=\"plain\"\n foregroundStyle={foreground}\n background={<RoundedRectangle cornerRadius={8} fill={background} />}\n {...(style === 'whiteOutline' ? { overlay: <RoundedRectangle cornerRadius={8} strokeBorder={{ style: 'black', lineWidth: 1 }} /> } : {})}\n {...Object.fromEntries(modifiers)}\n >\n <HStack spacing={6} frame={{ maxWidth: Infinity, height: 50 }} font={system(19, 'medium')}>\n <Image systemName=\"apple.logo\" />\n <Text>{LABELS[own.label ?? 'signIn']}</Text>\n </HStack>\n </Button>\n );\n}\n","/**\n * `useGeolocation(options)`: the viewer's position through the Geolocation\n * API, which a page has from the browser and a native app from the runtime\n * (`navigator.geolocation` over `CLLocationManager`; the app's Info.plist\n * names `NSLocationWhenInUseUsageDescription`). Nothing is asked until\n * `request()` (the first ask prompts the viewer), unless `immediate` is set;\n * `watch` keeps following the position until the view goes.\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\n\nexport interface GeolocationFix {\n latitude: number;\n longitude: number;\n /** Meters. */\n accuracy: number;\n altitude: number | null;\n heading: number | null;\n speed: number | null;\n /** Milliseconds since the epoch. */\n timestamp: number;\n}\n\nexport type GeolocationStatus = 'idle' | 'locating' | 'located' | 'denied' | 'failed';\n\nexport interface GeolocationOptions {\n /** Keep following the position (`watchPosition`) instead of asking once. */\n watch?: boolean;\n /** Ask as soon as the view appears. */\n immediate?: boolean;\n enableHighAccuracy?: boolean;\n /** Milliseconds to wait for a fix. */\n timeout?: number;\n maximumAge?: number;\n}\n\nexport interface GeolocationState {\n /** Whether the environment has `navigator.geolocation`. */\n available: boolean;\n status: GeolocationStatus;\n /** The latest fix, kept across a later failure. */\n position: GeolocationFix | null;\n error: string | null;\n /** Asks (again); with `watch`, starts following. */\n request(): void;\n /** Stops a watch; the position stays. */\n stop(): void;\n}\n\ninterface GeolocationLike {\n getCurrentPosition(success: (p: PositionLike) => void, failure?: (e: ErrorLike) => void, options?: object): void;\n watchPosition(success: (p: PositionLike) => void, failure?: (e: ErrorLike) => void, options?: object): number;\n clearWatch(id: number): void;\n}\ninterface PositionLike {\n coords: { latitude: number; longitude: number; accuracy: number; altitude: number | null; heading: number | null; speed: number | null };\n timestamp: number;\n}\ninterface ErrorLike {\n code: number;\n message: string;\n}\n\nfunction geolocationAPI(): GeolocationLike | null {\n const nav = (globalThis as { navigator?: { geolocation?: GeolocationLike } }).navigator;\n return nav?.geolocation ?? null;\n}\n\nexport function useGeolocation(options: GeolocationOptions = {}): GeolocationState {\n const { watch = false, immediate = false, enableHighAccuracy = false, timeout, maximumAge } = options;\n const api = geolocationAPI();\n const [status, setStatus] = useState<GeolocationStatus>('idle');\n const [position, setPosition] = useState<GeolocationFix | null>(null);\n const [error, setError] = useState<string | null>(null);\n const watching = useRef<number | null>(null);\n const mounted = useRef(true);\n\n const stop = useCallback((): void => {\n if (watching.current !== null) {\n geolocationAPI()?.clearWatch(watching.current);\n watching.current = null;\n }\n }, []);\n\n const request = useCallback((): void => {\n const geo = geolocationAPI();\n if (!geo) {\n setStatus('failed');\n setError('geolocation: not available');\n return;\n }\n stop();\n setStatus('locating');\n setError(null);\n const positionOptions = { enableHighAccuracy, ...(timeout !== undefined ? { timeout } : {}), ...(maximumAge !== undefined ? { maximumAge } : {}) };\n const onFix = (p: PositionLike): void => {\n if (!mounted.current) return;\n setPosition({\n latitude: p.coords.latitude,\n longitude: p.coords.longitude,\n accuracy: p.coords.accuracy,\n altitude: p.coords.altitude ?? null,\n heading: p.coords.heading ?? null,\n speed: p.coords.speed ?? null,\n timestamp: p.timestamp,\n });\n setStatus('located');\n setError(null);\n };\n const onError = (e: ErrorLike): void => {\n if (!mounted.current) return;\n setStatus(e.code === 1 ? 'denied' : 'failed');\n setError(e.message);\n if (e.code === 1) stop();\n };\n if (watch) watching.current = geo.watchPosition(onFix, onError, positionOptions);\n else geo.getCurrentPosition(onFix, onError, positionOptions);\n }, [watch, enableHighAccuracy, timeout, maximumAge, stop]);\n\n useEffect(() => {\n mounted.current = true;\n if (immediate) request();\n return () => {\n mounted.current = false;\n stop();\n };\n }, [immediate, request, stop]);\n\n return { available: api !== null, status, position, error, request, stop };\n}\n","/**\n * Speech through the Web Speech API, which a page has from the browser and a\n * native app from the runtime (`speechSynthesis` on `AVSpeechSynthesizer`,\n * `SpeechRecognition` on `SFSpeechRecognizer`): `useSpeechSynthesis()` reads\n * text aloud, `useSpeechRecognition()` turns the viewer's speech into text.\n * Each reads `available` where the environment lacks the API.\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\n\n// MARK: Synthesis\n\nexport interface SpeakOptions {\n /** A BCP 47 tag (`en-US`); the environment's voice for it. */\n lang?: string;\n /** A multiple of the normal rate (1). */\n rate?: number;\n pitch?: number;\n volume?: number;\n}\n\nexport interface SpeechSynthesisState {\n available: boolean;\n speaking: boolean;\n paused: boolean;\n /** Reads `text` aloud, after what is queued (`cancel()` first to interrupt). */\n speak(text: string, options?: SpeakOptions): void;\n /** Stops and empties the queue. */\n cancel(): void;\n pause(): void;\n resume(): void;\n}\n\ninterface UtteranceLike {\n text: string;\n lang: string;\n rate: number;\n pitch: number;\n volume: number;\n onstart: ((e: unknown) => void) | null;\n onend: ((e: unknown) => void) | null;\n onerror: ((e: unknown) => void) | null;\n onpause: ((e: unknown) => void) | null;\n onresume: ((e: unknown) => void) | null;\n}\ninterface SynthesisLike {\n speaking: boolean;\n paused: boolean;\n speak(utterance: UtteranceLike): void;\n cancel(): void;\n pause(): void;\n resume(): void;\n}\n\nfunction synthesisAPI(): { synthesis: SynthesisLike; Utterance: new (text: string) => UtteranceLike } | null {\n const g = globalThis as { speechSynthesis?: SynthesisLike; SpeechSynthesisUtterance?: new (text: string) => UtteranceLike };\n return g.speechSynthesis && g.SpeechSynthesisUtterance ? { synthesis: g.speechSynthesis, Utterance: g.SpeechSynthesisUtterance } : null;\n}\n\nexport function useSpeechSynthesis(): SpeechSynthesisState {\n const api = synthesisAPI();\n const [speaking, setSpeaking] = useState(false);\n const [paused, setPaused] = useState(false);\n const mounted = useRef(true);\n /** The utterances this hook queued and not yet done. */\n const queued = useRef(0);\n\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n // What this view was reading stops with it.\n if (queued.current > 0) synthesisAPI()?.synthesis.cancel();\n };\n }, []);\n\n const speak = useCallback((text: string, options: SpeakOptions = {}): void => {\n const current = synthesisAPI();\n if (!current) return;\n const utterance = new current.Utterance(text);\n if (options.lang) utterance.lang = options.lang;\n if (options.rate !== undefined) utterance.rate = options.rate;\n if (options.pitch !== undefined) utterance.pitch = options.pitch;\n if (options.volume !== undefined) utterance.volume = options.volume;\n queued.current++;\n const done = (): void => {\n queued.current = Math.max(0, queued.current - 1);\n if (!mounted.current) return;\n if (queued.current === 0) {\n setSpeaking(false);\n setPaused(false);\n }\n };\n utterance.onstart = () => {\n if (!mounted.current) return;\n setSpeaking(true);\n setPaused(false);\n };\n utterance.onpause = () => mounted.current && setPaused(true);\n utterance.onresume = () => mounted.current && setPaused(false);\n utterance.onend = done;\n utterance.onerror = done;\n current.synthesis.speak(utterance);\n }, []);\n\n const cancel = useCallback((): void => {\n synthesisAPI()?.synthesis.cancel();\n }, []);\n const pause = useCallback((): void => synthesisAPI()?.synthesis.pause(), []);\n const resume = useCallback((): void => synthesisAPI()?.synthesis.resume(), []);\n\n return { available: api !== null, speaking, paused, speak, cancel, pause, resume };\n}\n\n// MARK: Recognition\n\nexport interface SpeechRecognitionOptions {\n /** A BCP 47 tag; the environment's language by default. */\n lang?: string;\n /** Keep listening after a pause instead of ending at the first final result. */\n continuous?: boolean;\n /** Report what is heard as it is heard (`interim`), before it is final. */\n interimResults?: boolean;\n}\n\nexport interface SpeechRecognitionState {\n available: boolean;\n listening: boolean;\n /** The final transcripts of this session, joined. */\n transcript: string;\n /** What is being heard now, not yet final. */\n interim: string;\n /** `not-allowed`, `audio-capture`, `no-speech`, `network`, `aborted` … */\n error: string | null;\n start(): void;\n /** Stops listening; the last words still arrive. */\n stop(): void;\n /** Stops listening and keeps nothing more. */\n abort(): void;\n}\n\ninterface RecognitionLike {\n lang: string;\n continuous: boolean;\n interimResults: boolean;\n onstart: (() => void) | null;\n onresult: ((e: { resultIndex: number; results: ArrayLike<{ isFinal: boolean; 0: { transcript: string } }> }) => void) | null;\n onerror: ((e: { error: string }) => void) | null;\n onend: (() => void) | null;\n start(): void;\n stop(): void;\n abort(): void;\n}\n\nfunction recognitionAPI(): (new () => RecognitionLike) | null {\n const g = globalThis as { SpeechRecognition?: new () => RecognitionLike; webkitSpeechRecognition?: new () => RecognitionLike };\n return g.SpeechRecognition ?? g.webkitSpeechRecognition ?? null;\n}\n\nexport function useSpeechRecognition(options: SpeechRecognitionOptions = {}): SpeechRecognitionState {\n const { lang, continuous = false, interimResults = true } = options;\n const api = recognitionAPI();\n const [listening, setListening] = useState(false);\n const [transcript, setTranscript] = useState('');\n const [interim, setInterim] = useState('');\n const [error, setError] = useState<string | null>(null);\n const current = useRef<RecognitionLike | null>(null);\n const mounted = useRef(true);\n\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n current.current?.abort();\n current.current = null;\n };\n }, []);\n\n const start = useCallback((): void => {\n const Recognition = recognitionAPI();\n if (!Recognition) {\n setError('not-allowed');\n return;\n }\n if (current.current) return;\n const recognition = new Recognition();\n if (lang) recognition.lang = lang;\n recognition.continuous = continuous;\n recognition.interimResults = interimResults;\n setTranscript('');\n setInterim('');\n setError(null);\n recognition.onstart = () => mounted.current && setListening(true);\n recognition.onresult = (e) => {\n if (!mounted.current) return;\n const finals: string[] = [];\n let heard = '';\n for (let i = 0; i < e.results.length; i++) {\n const result = e.results[i]!;\n if (result.isFinal) finals.push(result[0].transcript.trim());\n else heard = result[0].transcript;\n }\n setTranscript(finals.filter(Boolean).join(' '));\n setInterim(heard);\n };\n recognition.onerror = (e) => mounted.current && setError(e.error);\n recognition.onend = () => {\n if (current.current === recognition) current.current = null;\n if (!mounted.current) return;\n setListening(false);\n setInterim('');\n };\n current.current = recognition;\n recognition.start();\n }, [lang, continuous, interimResults]);\n\n const stop = useCallback((): void => current.current?.stop(), []);\n const abort = useCallback((): void => current.current?.abort(), []);\n\n return { available: api !== null, listening, transcript, interim, error, start, stop, abort };\n}\n","/**\n * `useAppStorage(key, default)`: SwiftUI's `@AppStorage`. A value kept under a\n * key in the app's storage (`localStorage`: the browser's on a page, the\n * device's in a SwiftBrowser Native app) as JSON, read back at the next\n * launch, and shared by every view that reads the key: a write through any of\n * them re-renders them all. The default stands in while nothing is stored,\n * and setting `undefined` removes the key, as assigning nil does.\n *\n * The hook is the key's writer: it keeps what it read and re-reads storage\n * only when another tab writes the key (the window's `storage` event). A\n * write that storage refuses (a page's storage is full) still takes effect\n * in the app, for the session, and is reported to `onError`.\n */\n\nimport { useCallback, useState, useSyncExternalStore } from 'react';\n\n/** Where the values go: `localStorage`'s shape. */\nexport interface AppStorageStore {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n}\n\nexport interface AppStorageOptions<T> {\n /** The storage; `localStorage` by default (memory where a page has none, or refuses it). */\n store?: AppStorageStore;\n /**\n * What a stored value becomes on load: a migration from what an older\n * version of the app saved. A throw falls back to the default. The readers\n * of a key share one; the last to mount decides.\n */\n decode?: (stored: unknown) => T;\n /** A write storage refused (out of room). The value is kept in memory regardless. */\n onError?: (error: unknown) => void;\n}\n\n/** The new value, or a function of the current one, as `useState`'s setter takes. */\nexport type AppStorageSetter<T> = (value: T | ((current: T) => T)) => void;\n\ninterface Entry {\n /** The stored JSON, null for no value (or one that would not parse). */\n raw: string | null;\n /** What `raw` decodes to; meaningless while `raw` is null. */\n value: unknown;\n /** Whether `value` is current for `raw`. */\n decoded: boolean;\n decode: ((stored: unknown) => unknown) | undefined;\n listeners: Set<() => void>;\n}\n\nconst stores = new WeakMap<AppStorageStore, Map<string, Entry>>();\n\nfunction entryFor(store: AppStorageStore, key: string): Entry {\n let entries = stores.get(store);\n if (!entries) {\n entries = new Map();\n stores.set(store, entries);\n if (store === pageStorage) watchOtherTabs();\n }\n let entry = entries.get(key);\n if (!entry) {\n let raw: string | null = null;\n try {\n raw = store.getItem(key);\n } catch {\n // Unreadable (a private window, blocked site data): nothing is stored.\n }\n entry = { raw, value: undefined, decoded: false, decode: undefined, listeners: new Set() };\n entries.set(key, entry);\n }\n return entry;\n}\n\n/** The entry's value, decoding the stored JSON once; `absent` while nothing (that parses) is stored. */\nfunction valueOf(entry: Entry, absent: unknown): unknown {\n if (entry.raw === null) return absent;\n if (!entry.decoded) {\n try {\n const parsed: unknown = JSON.parse(entry.raw);\n entry.value = entry.decode ? entry.decode(parsed) : parsed;\n } catch {\n // Not JSON, or the decode refused it: as good as nothing stored.\n entry.raw = null;\n return absent;\n }\n entry.decoded = true;\n }\n return entry.value;\n}\n\nfunction notify(entry: Entry): void {\n for (const listener of [...entry.listeners]) listener();\n}\n\n/** Takes `raw` as the stored JSON (another tab wrote it), to decode on the next read. */\nfunction invalidate(entry: Entry, raw: string | null): void {\n if (entry.raw === raw && entry.decoded) return;\n entry.raw = raw;\n entry.decoded = false;\n notify(entry);\n}\n\n// ---------------------------------------------------------------------------\n// The default store: the page's localStorage, or memory\n// ---------------------------------------------------------------------------\n\n/** `localStorage` where the page has one and lets the app at it, else null. */\nfunction readPageStorage(): AppStorageStore | null {\n try {\n const storage = (globalThis as { localStorage?: AppStorageStore }).localStorage;\n return storage && typeof storage.getItem === 'function' ? storage : null;\n } catch {\n return null;\n }\n}\n\nconst memory = new Map<string, string>();\n\n/** For a page without `localStorage`: the values last the session. */\nconst memoryStorage: AppStorageStore = {\n getItem: (key) => memory.get(key) ?? null,\n setItem: (key, value) => void memory.set(key, value),\n removeItem: (key) => void memory.delete(key),\n};\n\nconst pageStorage = readPageStorage();\n\n/** The store `useAppStorage` uses when none is given. */\nexport const appStorage: AppStorageStore = pageStorage ?? memoryStorage;\n\nlet watching = false;\n\n/** Another tab's writes to `localStorage` reach this one as `storage` events. */\nfunction watchOtherTabs(): void {\n if (watching || !pageStorage) return;\n watching = true;\n const target = (globalThis as { addEventListener?: (type: string, listener: (event: StorageEvent) => void) => void });\n if (typeof target.addEventListener !== 'function') return;\n target.addEventListener('storage', (event: StorageEvent) => {\n if (event.storageArea !== pageStorage) return;\n const entries = stores.get(pageStorage);\n if (!entries) return;\n if (event.key === null) {\n for (const entry of entries.values()) invalidate(entry, null);\n } else {\n const entry = entries.get(event.key);\n if (entry) invalidate(entry, event.newValue);\n }\n });\n}\n\n// ---------------------------------------------------------------------------\n// The hook\n// ---------------------------------------------------------------------------\n\n/**\n * The value stored under `key`, or `defaultValue` (a value, or a function\n * making one, as `useState` takes) while there is none, and its setter. The\n * value must survive JSON: plain objects, arrays, strings, numbers,\n * booleans, null.\n */\nexport function useAppStorage<T>(key: string, defaultValue: T | (() => T), options: AppStorageOptions<T> = {}): [T, AppStorageSetter<T>] {\n const { store = appStorage, decode, onError } = options;\n const [fallback] = useState(defaultValue);\n const entry = entryFor(store, key);\n entry.decode = decode;\n const subscribe = useCallback(\n (listener: () => void) => {\n const subscribed = entryFor(store, key);\n subscribed.listeners.add(listener);\n return () => void subscribed.listeners.delete(listener);\n },\n [store, key],\n );\n const read = useCallback((): T => valueOf(entryFor(store, key), fallback) as T, [store, key, fallback]);\n const value = useSyncExternalStore(subscribe, read, read);\n const set = useCallback<AppStorageSetter<T>>(\n (next) => {\n const target = entryFor(store, key);\n const current = valueOf(target, fallback) as T;\n const value = typeof next === 'function' ? (next as (current: T) => T)(current) : next;\n const raw = value === undefined ? null : JSON.stringify(value);\n try {\n if (raw === null) store.removeItem(key);\n else store.setItem(key, raw);\n } catch (error) {\n onError?.(error);\n }\n // Decoded already: the value the app set is the one it reads back.\n target.raw = raw;\n target.value = value;\n target.decoded = raw !== null;\n notify(target);\n },\n [store, key, fallback, onError],\n );\n return [value, set];\n}\n","/**\n * `fileManager`: Foundation's `FileManager.default` for the app's own files,\n * with `URL.documentsDirectory` and its siblings. Paths are `file:` URLs. On\n * a page the files live in the app's IndexedDB database, the same iOS-like\n * home a Swift app has there (`/data`: `Documents`, `Library/Application\n * Support`, `Library/Caches`, and `/tmp` for the session); in a SwiftBrowser\n * Native app they are the app's sandbox. The calls are asynchronous on both,\n * since the page's storage is: the one departure from Swift.\n *\n * `loadURL` is what a `VideoPlayer`, an `AudioPlayer` or an `Image` loads a\n * file at; they call it themselves for a `file:` URL, so an app hands them\n * the file's URL as it would natively.\n */\n\nimport type { FileAttributes, FileDirectories, FilesHost } from '@swiftbrowser/web/src/files';\nimport { fileURL } from '@swiftbrowser/web/src/files';\nimport { browserEnvironment } from '@swiftbrowser/web/src/hostRequests';\n\nexport type { FileAttributes, FileDirectories };\n\n/**\n * What `write` takes: bytes, a Blob or a File, or text (written as UTF-8). A\n * Blob or File is handed to the host as it is, so a picked or dropped file\n * is kept without passing through memory (IndexedDB stores the Blob; the\n * native app copies the file on disk).\n */\nexport type FileContents = Uint8Array | ArrayBuffer | Blob | string;\n\n/** A byte range of a file: from `start` up to `end` (exclusive, clamped to the file's size). */\nexport interface FileRange {\n start: number;\n end: number;\n}\n\nexport interface FileManager {\n /** Whether this page or app keeps files; the calls below fail `unsupported: …` where it does not. */\n readonly available: boolean;\n /** `URL.documentsDirectory`: the app's documents, kept across launches. */\n readonly documentsDirectory: string;\n /** `URL.applicationSupportDirectory`: the app's own data, kept across launches. */\n readonly applicationSupportDirectory: string;\n /** `URL.cachesDirectory`: what can be made again. */\n readonly cachesDirectory: string;\n /** `FileManager.temporaryDirectory`: empty at every launch. */\n readonly temporaryDirectory: string;\n /** `url.appending(path:)`: the `file:` URL of `path` below `directory`. */\n url(directory: string, path: string): string;\n /**\n * `Data(contentsOf:)`: the file's bytes; with `range`, only those from\n * `range.start` up to `range.end`, read without the rest where the host can\n * (`FileHandle` natively, a `Blob` slice on a page), so a large file is read\n * a piece at a time.\n */\n contents(url: string, range?: FileRange): Promise<Uint8Array>;\n /** `String(contentsOf:)`: the file as UTF-8 text. */\n text(url: string): Promise<string>;\n /**\n * `Data.write(to:)`: writes the file, replacing one there; its directory\n * must exist. A `Blob` or `File` is kept as it is (see `FileContents`).\n */\n write(url: string, contents: FileContents): Promise<void>;\n /** `contentsOfDirectory(at:)`: the URLs of what the directory holds, by name. */\n contentsOfDirectory(url: string): Promise<string[]>;\n /** `createDirectory(at:withIntermediateDirectories: true)`. */\n createDirectory(url: string): Promise<void>;\n /** `fileExists(atPath:)`. */\n fileExists(url: string): Promise<boolean>;\n /** `attributesOfItem(atPath:)`: the size, the modification and creation times where known, whether it is a directory, and the MIME type its extension names; fails `notFound: …`. */\n attributesOfItem(url: string): Promise<FileAttributes>;\n /** `moveItem(at:to:)`: to a URL nothing is at, in a directory that exists. */\n moveItem(from: string, to: string): Promise<void>;\n /** `copyItem(at:to:)`: to a URL nothing is at, in a directory that exists. */\n copyItem(from: string, to: string): Promise<void>;\n /** `removeItem(at:)`: a file, or a directory and all it holds. */\n removeItem(url: string): Promise<void>;\n /** A URL the page can load the file at (an object URL of its bytes; natively the URL itself, downloaded from iCloud Drive first). */\n loadURL(url: string): Promise<string>;\n /**\n * `FileManager.url(forUbiquityContainerIdentifier:)`, then `Documents`: the\n * app's folder in iCloud Drive, where the app has the iCloud entitlement\n * (`swiftbrowser native init --icloud`) and the viewer iCloud Drive. The\n * files there follow the viewer to their other devices and show in the\n * Files app. Null without it, and on a page. Reading a file another device\n * wrote downloads it first.\n */\n iCloudDirectory(): Promise<string | null>;\n /**\n * Calls `listener` with the URLs that changed: what this app wrote, and\n * natively what another device wrote to iCloud Drive. Returns a function\n * that stops listening. `useFileStorage` reads a file again on it.\n */\n watch(listener: (urls: string[]) => void): () => void;\n}\n\n/** The directories a page without a files host would have, for the properties to answer something. */\nconst NONE: FileDirectories = {\n documents: 'file:///data/Documents',\n applicationSupport: 'file:///data/Library/Application%20Support',\n caches: 'file:///data/Library/Caches',\n temporary: 'file:///tmp',\n};\n\n/** What the host is given for `write`: bytes, or the Blob itself. */\nfunction hostData(contents: FileContents): Uint8Array | Blob {\n if (typeof contents === 'string') return new TextEncoder().encode(contents);\n if (contents instanceof Uint8Array) return contents;\n if (contents instanceof ArrayBuffer) return new Uint8Array(contents);\n return contents;\n}\n\n/** A file manager over the host `host` answers (the environment's, looked up at each call, for the default). */\nexport function createFileManager(host: () => FilesHost | undefined): FileManager {\n const required = (): FilesHost => {\n const files = host();\n if (!files) throw new Error('unsupported: this page keeps no files');\n return files;\n };\n const directories = (): FileDirectories => host()?.directories ?? NONE;\n return {\n get available() {\n return host() !== undefined;\n },\n get documentsDirectory() {\n return directories().documents;\n },\n get applicationSupportDirectory() {\n return directories().applicationSupport;\n },\n get cachesDirectory() {\n return directories().caches;\n },\n get temporaryDirectory() {\n return directories().temporary;\n },\n url: (directory, path) => fileURL(directory, path),\n contents: async (url, range) => {\n const files = required();\n if (!range) return files.read(url);\n if (files.readRange) return files.readRange(url, range.start, range.end);\n const all = await files.read(url);\n const start = Math.min(Math.max(0, range.start), all.byteLength);\n return all.subarray(start, Math.min(Math.max(start, range.end), all.byteLength));\n },\n text: async (url) => new TextDecoder().decode(await required().read(url)),\n write: async (url, contents) => required().write(url, hostData(contents)),\n contentsOfDirectory: async (url) => required().list(url),\n createDirectory: async (url) => required().createDirectory(url),\n fileExists: async (url) => (await required().attributes(url)) !== null,\n attributesOfItem: async (url) => {\n const attributes = await required().attributes(url);\n if (!attributes) throw new Error(`notFound: nothing at ${url}`);\n return attributes;\n },\n moveItem: async (from, to) => required().move(from, to),\n copyItem: async (from, to) => required().copy(from, to),\n removeItem: async (url) => required().remove(url),\n loadURL: async (url) => required().loadURL(url),\n iCloudDirectory: async () => (await host()?.iCloud?.()) ?? null,\n watch: (listener) => host()?.watch?.(listener) ?? (() => {}),\n };\n}\n\n/** `FileManager.default`: the app's files through the renderer environment's host. */\nexport const fileManager: FileManager = createFileManager(() => browserEnvironment.files);\n","/**\n * `useFileStorage(url, default)`: a value kept as a JSON file through\n * `fileManager`, the way `useAppStorage` keeps one under a key. The file is\n * read when the URL is given (the default stands in until then, and where\n * there is no file yet), written on each set, and read again when\n * `fileManager.watch` says it changed: another view wrote it, or another\n * device did, in iCloud Drive. A document app keeps its documents this way:\n * put the file in `iCloudDirectory()` where there is one, in\n * `documentsDirectory` elsewhere, and it is the same code on both.\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { fileManager, type FileManager } from './fileManager';\n\nexport interface FileStorageOptions<T> {\n /** What a stored value becomes on load: a migration from what an older version wrote. A throw falls back to the default. */\n decode?: (stored: unknown) => T;\n /** A read or write that failed (the file could not be downloaded, the storage is full). */\n onError?: (error: unknown) => void;\n /** The file manager; `fileManager` by default. */\n manager?: FileManager;\n}\n\n/** The new value, or a function of the current one, as `useState`'s setter takes. */\nexport type FileStorageSetter<T> = (value: T | ((current: T) => T)) => void;\n\n/** `loading` until the file was read (or found missing); `ready` after; `error` when the read failed (the default stands). */\nexport type FileStorageStatus = 'loading' | 'ready' | 'error';\n\nexport function useFileStorage<T>(url: string | null, defaultValue: T | (() => T), options: FileStorageOptions<T> = {}): [T, FileStorageSetter<T>, FileStorageStatus] {\n const manager = options.manager ?? fileManager;\n const [value, setValue] = useState<T>(defaultValue);\n const [status, setStatus] = useState<FileStorageStatus>(url === null ? 'ready' : 'loading');\n const latest = useRef({ value, options, url, defaultValue });\n latest.current = { value, options, url, defaultValue };\n /** The URL the state is for; another one starts from the default again. */\n const shown = useRef(url);\n /** The JSON last read or written, to tell a change of ours from another writer's. */\n const known = useRef<string | null>(null);\n /** Writes in flight, in order. */\n const writing = useRef<Promise<void>>(Promise.resolve());\n\n const load = useCallback(\n async (target: string): Promise<void> => {\n let text: string | null;\n try {\n text = await manager.text(target);\n } catch (error) {\n if (latest.current.url !== target) return;\n if (error instanceof Error && error.message.startsWith('notFound:')) {\n known.current = null;\n setStatus('ready');\n return;\n }\n latest.current.options.onError?.(error);\n setStatus('error');\n return;\n }\n if (latest.current.url !== target) return;\n if (text !== known.current) {\n known.current = text;\n try {\n const stored: unknown = JSON.parse(text);\n setValue(latest.current.options.decode ? latest.current.options.decode(stored) : (stored as T));\n } catch (error) {\n latest.current.options.onError?.(error);\n }\n }\n setStatus('ready');\n },\n [manager],\n );\n\n useEffect(() => {\n known.current = null;\n if (shown.current !== url) {\n shown.current = url;\n const fresh = latest.current.defaultValue;\n const value = typeof fresh === 'function' ? (fresh as () => T)() : fresh;\n latest.current.value = value;\n setValue(value);\n }\n if (url === null) {\n setStatus('ready');\n return;\n }\n setStatus('loading');\n void load(url);\n return manager.watch((urls) => {\n if (urls.includes(url)) void load(url);\n });\n }, [url, load, manager]);\n\n const set = useCallback<FileStorageSetter<T>>(\n (next) => {\n const resolved = typeof next === 'function' ? (next as (current: T) => T)(latest.current.value) : next;\n latest.current.value = resolved;\n setValue(resolved);\n const target = latest.current.url;\n if (target === null) return;\n const text = JSON.stringify(resolved);\n known.current = text;\n writing.current = writing.current.then(async () => {\n try {\n await manager.write(target, text);\n } catch (error) {\n latest.current.options.onError?.(error);\n }\n });\n },\n [manager],\n );\n\n return [value, set, status];\n}\n","import type { ListStyle } from '@swiftbrowser/web/src/protocol';\nimport { Fragment, isValidElement, useContext, type ReactElement, type ReactNode } from 'react';\nimport { SplitSelectionContext, useReportSplitSelection } from './split';\nimport { readBinding, type BindingValue } from '../binding';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, takeModifier, type ViewModifiers } from '../modifiers';\nimport { plainText } from './controls';\nimport { NavigationLink } from './navigation';\nimport { ListSelectionContext, Row, type ListSelection, type RowProps } from './row';\nimport { PinnedContext, flattenChildren, providingScrollSettings, takeScrollSettings, useRefreshable } from './stacks';\nimport { edgeEffectProp, useScrollSettings } from '../scrollEnvironment';\nimport { LazyContext, LazyGroup, type LazyGroupProps, LazyStackContext } from '../lazy';\nimport { Text } from './text';\n\nconst NO_CLEAR = (): void => {};\n\n/** A selection: one value (or `null`), or a `Set` of values. */\nexport type Selection<T> = T | null | Set<T>;\n\nexport interface ListProps<T = unknown> extends ViewModifiers {\n listStyle?: ListStyle;\n /** A `Form`: on a Mac the rows are laid out in the columns style (labels in a column before their controls). */\n form?: boolean;\n /** `.formStyle(_:)` on a `Form`: on a Mac `grouped` lays it out in grouped sections, `columns` (and the default) in the columns style. */\n formStyle?: 'automatic' | 'grouped' | 'columns';\n /**\n * This list's rows are at least this tall, over the\n * `defaultMinListRowHeight` set above it (the modifier, which every list\n * below inherits; set it once at an app's top). Absent both, the\n * platform's default (44 on iOS, 24 on a Mac).\n */\n minRowHeight?: number;\n /** Edit mode (`EditButton`). */\n editing?: BindingValue<boolean>;\n /** `List(selection:)`: rows with a `tag` (or a `NavigationLink` value) become selectable; a `Set` selects several. */\n selection?: BindingValue<Set<T>> | BindingValue<T | null> | undefined;\n onSelectionChange?: ((selection: Selection<T>) => void) | undefined;\n children?: ReactNode;\n}\n\nexport function List<T = unknown>(props: ListProps<T>): ReactNode {\n const { own, modifiers } = splitProps(props);\n const [editing] = own.editing !== undefined ? readBinding(own.editing) : [false];\n const listProps: Record<string, unknown> = { style: own.listStyle ?? 'insetGrouped' };\n if (own.form) listProps['form'] = true;\n if (own.form && own.formStyle && own.formStyle !== 'automatic') listProps['formStyle'] = own.formStyle;\n if (own.minRowHeight !== undefined && Number.isFinite(own.minRowHeight)) listProps['minRowHeight'] = Math.max(0, own.minRowHeight);\n if (editing) listProps['editing'] = true;\n let selection: ListSelection | null = null;\n const split = useContext(SplitSelectionContext);\n /** Set below to tell the split of a tap's selection in the same update. */\n let reportNow: (selected: boolean, clear: () => void) => void = () => {};\n let selected = false;\n let clearSelection = NO_CLEAR;\n if (own.selection !== undefined) {\n const [value, setValue] = readBinding(own.selection as BindingValue<Selection<T>>, own.onSelectionChange);\n // A `Set` chooses several: in edit mode the native list shows its checkmark circles.\n if (value instanceof Set) listProps['multiSelect'] = true;\n selected = value instanceof Set ? value.size > 0 : value !== null && value !== undefined;\n clearSelection = () => setValue(value instanceof Set ? new Set<T>() : null);\n selection = {\n editing,\n isSelected: (tag) => (value instanceof Set ? value.has(tag as T) : value !== null && Object.is(value, tag)),\n select: (tag) => {\n if (value instanceof Set) {\n const next = new Set(value);\n if (next.has(tag as T)) next.delete(tag as T);\n else next.add(tag as T);\n setValue(next);\n reportNow(next.size > 0, () => setValue(new Set<T>()));\n } else {\n const next = editing && Object.is(value, tag) ? null : (tag as T);\n setValue(next);\n reportNow(next !== null, () => setValue(null));\n }\n },\n };\n }\n reportNow = useReportSplitSelection(split, selected, clearSelection, own.selection !== undefined);\n const refresh = useRefreshable(takeModifier(modifiers, 'refreshable'));\n Object.assign(listProps, refresh.props);\n // `.scrollEdgeEffectStyle` / `.scrollEdgeEffectHidden` (content margins are a scroll view's).\n const ownSettings = takeScrollSettings(modifiers);\n const edgeEffect = edgeEffectProp(useScrollSettings(ownSettings));\n if (edgeEffect) listProps['edgeEffect'] = edgeEffect;\n const element = (\n <LazyContext.Provider value=\"vertical\">\n <LazyStackContext.Provider value={false}>{sb('list', listProps, refresh.handlers, providingScrollSettings(ownSettings, wrapRows(own.children)))}</LazyStackContext.Provider>\n </LazyContext.Provider>\n );\n return applyModifiers(\n selection ? <ListSelectionContext.Provider value={selection}>{element}</ListSelectionContext.Provider> : element,\n modifiers,\n );\n}\n\n/** `Form { }`: an inset grouped list, as the shim draws it; on a Mac its rows are laid out in the columns style. */\nexport function Form(props: Omit<ListProps, 'listStyle' | 'selection' | 'onSelectionChange' | 'form'>): ReactNode {\n return <List {...props} form />;\n}\n\nexport interface SectionProps extends ViewModifiers {\n /** A string or a `<Text>` becomes the section's header text; any other view is a view header. */\n header?: ReactNode;\n footer?: ReactNode;\n /** `Section(isExpanded:)`: the section collapses, in a sidebar-style list (as on iOS); its header's chevron toggles it. */\n isExpanded?: BindingValue<boolean>;\n onExpandedChange?: (expanded: boolean) => void;\n children?: ReactNode;\n}\n\nexport function Section(props: SectionProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const pinned = useContext(PinnedContext);\n const [expanded, setExpanded] = own.isExpanded !== undefined ? readBinding(own.isExpanded, own.onExpandedChange) : [true, (): void => {}];\n const collapsible = own.isExpanded !== undefined;\n let header = supplement(own.header);\n let footer = supplement(own.footer);\n // In a lazy stack that pins its headers (footers), a string one is a view, so it can pin: outside a list the text would not draw.\n if (pinned?.includes('sectionHeaders') && header.text !== null && !header.view) header = { text: null, view: <Text>{header.text}</Text> };\n if (pinned?.includes('sectionFooters') && footer.text !== null && !footer.view) footer = { text: null, view: <Text>{footer.text}</Text> };\n // Keyed, so React does not take the header, the rows and the footer for a list of its own.\n const children: ReactNode[] = [];\n if (header.view) children.push(<Fragment key=\"header\">{sb('sectionheader', {}, undefined, header.view)}</Fragment>);\n if (own.children !== undefined) children.push(<Fragment key=\"rows\">{wrapRows(own.children)}</Fragment>);\n if (footer.view) children.push(<Fragment key=\"footer\">{sb('sectionfooter', {}, undefined, footer.view)}</Fragment>);\n // The rows go whatever the state: the renderers hide them collapsed, as SwiftUI does.\n return applyModifiers(\n sb(\n 'section',\n collapsible ? { header: header.text, footer: footer.text, collapsible: true, expanded } : { header: header.text, footer: footer.text },\n collapsible ? { tap: () => setExpanded(!expanded) } : undefined,\n children,\n ),\n modifiers,\n );\n}\n\n/**\n * Rows with a tag (`.tag`, or a `NavigationLink` value) become `Row`s, so a\n * `List(selection:)` can select them; a `Row` from `ForEach`'s `onDelete`\n * keeps its own. Sections pass through (they wrap their own rows).\n */\nfunction wrapRows(children: ReactNode): ReactNode {\n // Lazy groups stay groups (they build their rows as they scroll in); the\n // rows before one count it as one child, the rows after as its rows.\n let offset = 0;\n return flattenChildren(children, { keepLazy: true }).map((element, index) => {\n const at = index + offset;\n if (element.type === LazyGroup) {\n const group = element.props as LazyGroupProps;\n offset += group.rows.length - 1;\n return { ...withKey(element, index), props: { ...group, start: at, wrap: wrapRow } };\n }\n return wrapRow(withKey(element, index), at);\n });\n}\n\n/** A row as its container holds it: a `Row` knows its index; a tagged view becomes a selectable `Row`. */\nfunction wrapRow(row: ReactElement, containerIndex: number): ReactElement {\n // A lazy group's `ForEach` row is still in its fragments (flattenChildren took the others out): the one view inside carries the tag.\n const inner = row.type === Fragment ? flattenChildren(row) : null;\n const element = inner?.length === 1 ? { ...inner[0]!, key: row.key } : row;\n if (element.type === Section) return element;\n if (element.type === Row) return { ...element, props: { ...(element.props as RowProps), containerIndex } };\n const props = element.props as { tag?: unknown; value?: unknown };\n const tag = props.tag !== undefined ? props.tag : element.type === NavigationLink ? props.value : undefined;\n if (tag === undefined) return element;\n return (\n <Row key={element.key ?? containerIndex} tag={tag} containerIndex={containerIndex}>\n {element}\n </Row>\n );\n}\n\nfunction withKey(element: ReactElement, index: number): ReactElement {\n return element.key !== null ? element : { ...element, key: String(index) };\n}\n\nfunction supplement(node: ReactNode): { text: string | null; view: ReactElement | null } {\n if (node === undefined || node === null || node === false) return { text: null, view: null };\n if (typeof node === 'string' || typeof node === 'number') return { text: String(node), view: null };\n if (isValidElement(node) && node.type === Text) {\n const props = node.props as { children?: ReactNode };\n const only = Object.keys(props).every((key) => key === 'children');\n if (only) return { text: plainText(node), view: null };\n }\n return { text: null, view: isValidElement(node) ? node : null };\n}\n","import { useState, type ReactNode } from 'react';\nimport { readBinding, type BindingValue } from '../binding';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, takeModifier, type ViewModifiers } from '../modifiers';\nimport { flattenChildren } from './stacks';\n\nexport interface TabViewProps<T> extends ViewModifiers {\n selection?: BindingValue<T>;\n onChange?: (value: T) => void;\n /** `<Tab>` children. */\n children?: ReactNode;\n}\n\nexport function TabView<T = number>(props: TabViewProps<T>): ReactNode {\n const { own, modifiers } = splitProps(props);\n const tabs = flattenChildren(own.children);\n const tags = tabs.map((tab, index) => {\n const tag = (tab.props as { tag?: T }).tag;\n return (tag !== undefined ? tag : index) as T;\n });\n const [internal, setInternal] = useState<T>(tags[0] as T);\n const [selection, setSelection] = own.selection !== undefined ? readBinding(own.selection, own.onChange) : [internal, setInternal];\n const selected = Math.max(\n 0,\n tags.findIndex((tag) => Object.is(tag, selection)),\n );\n return applyModifiers(\n sb('tabview', { selected }, { select: (event) => tags[event.value] !== undefined && setSelection(tags[event.value] as T) }, tabs),\n modifiers,\n );\n}\n\nexport interface TabProps<T> extends ViewModifiers {\n title: string;\n systemImage?: string;\n /** An asset catalog image (a custom symbol), as `Tab(\"Backyards\", image: \"fountain\")`; used when there is no `systemImage`. */\n image?: string;\n role?: 'search';\n tag?: T;\n children?: ReactNode;\n}\n\n/** `Tab(\"Library\", systemImage: \"books.vertical\") { }`, or `Tab(\"Backyards\", image: \"fountain\") { }` */\nexport function Tab<T>(props: TabProps<T>): ReactNode {\n const { own, modifiers } = splitProps(props);\n const badge = takeModifier(modifiers, 'badge');\n const tabProps: Record<string, unknown> = { title: own.title, systemImage: own.systemImage ?? null };\n if (badge !== undefined && badge !== null) tabProps['badge'] = String(badge);\n if (own.role) tabProps['role'] = own.role;\n if (own.image && !own.systemImage) tabProps['image'] = own.image;\n return applyModifiers(sb('tab', tabProps, undefined, own.children), modifiers);\n}\n","/**\n * `Host`: ordinary React DOM inside a SwiftUI tree. The children render in a\n * react-dom root of their own, inside a `host` element the layout engine\n * sizes (docs/ops-protocol.md, \"Host elements\"): by its content, like text,\n * or filling its proposal. The DOM content sees this package's contexts\n * (`useDismiss`, `useNavigation`, the environment) and any it names.\n */\n\nimport { notifyHostContentChange, registerHostContent, unregisterHostContent } from '@swiftbrowser/web/src/hostContent';\nimport { useEffect, useId, useLayoutEffect, useRef, useState, type CSSProperties, type Context, type ReactNode } from 'react';\nimport { createRoot, type Root } from 'react-dom/client';\nimport { flushSync } from 'react-dom';\nimport { useContextBridge } from '../bridge';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, type ViewModifiers } from '../modifiers';\n\nexport interface HostProps extends ViewModifiers {\n /**\n * `content` (the default): the box is as wide as the content wants, at most\n * the proposed width, and as tall as the content at that width. `fill`:\n * the box takes the proposal (combine with `frame`); the content fills it.\n */\n sizing?: 'fill' | 'content';\n /** Contexts of the SwiftUI tree the DOM content reads (this package's own always cross). */\n contexts?: readonly Context<unknown>[];\n className?: string;\n style?: CSSProperties;\n children?: ReactNode;\n}\n\nexport function Host(props: HostProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const key = useId();\n // The content element, one per mount. It is registered from the effects\n // below, not here: StrictMode runs this initializer twice and keeps one\n // result, and a registration made here would name the other.\n const [content] = useState<HTMLElement | null>(() => {\n if (typeof document === 'undefined') return null;\n const element = document.createElement('div');\n element.className = 'sb-host-content';\n return element;\n });\n const bridge = useContextBridge(own.contexts);\n const root = useRef<Root | null>(null);\n const mounted = useRef(false);\n // In `fill` sizing the wrapper is as tall as the box, so percentage\n // heights in the content (`height: 100%`) reach it.\n const sizing = own.sizing ?? 'content';\n const style: CSSProperties | undefined = sizing === 'fill' ? { height: '100%', ...own.style } : own.style;\n const tree = bridge(\n <div className={own.className} style={style}>\n {own.children}\n </div>,\n );\n\n useLayoutEffect(() => {\n if (!content) return;\n mounted.current = true;\n // After the commit that created the `host` element: the renderer adopts a\n // content registered late at the change notice below. Registered again\n // after StrictMode's simulated unmount, which unregistered it.\n registerHostContent(key, content);\n root.current ??= createRoot(content);\n const current = root.current;\n // In a microtask: still before the browser paints, but outside any commit\n // react-dom may be in the middle of (a `SwiftUIView` is one of its\n // components). The synchronous render lets the engine measure the new\n // content right away, and the tree is laid out again around it.\n queueMicrotask(() => {\n if (root.current !== current) return;\n flushSync(() => current.render(tree));\n notifyHostContentChange(key);\n });\n });\n\n useEffect(\n () => () => {\n mounted.current = false;\n unregisterHostContent(key);\n // Not inside the SwiftUI root's commit; and not at all when the host\n // mounted again meanwhile (StrictMode's simulated remount keeps the root).\n queueMicrotask(() => {\n if (mounted.current) return;\n const current = root.current;\n root.current = null;\n current?.unmount();\n });\n },\n [key],\n );\n\n return applyModifiers(sb('host', { content: key, sizing }), modifiers);\n}\n","/**\n * `RegisteredView`: a view a package draws itself, named as the package\n * registered it with `ViewRegistry`: in a native app a SwiftUI view\n * (SwiftBrowserNative's `ViewRegistry.register(name) { context in … }`), on\n * a page the package's own DOM (`ViewRegistry.register(name, (context) =>\n * …)`, from @swiftbrowser/web). One element on both, for what a package\n * draws from data that never crosses the bridge: an audio node's frames\n * (`ScopeView` in @swiftbrowser/dsp), a map's tiles, a camera's preview.\n * It takes the size it is given (`frame`, a stack's proposal), as\n * `GeometryReader` does.\n *\n * ```tsx\n * <RegisteredView name=\"Meter\" props={{ level }} onEvent={(value) => …} frame={{ height: 40 }} />\n * ```\n */\n\nimport type { ReactNode } from 'react';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, type ViewModifiers } from '../modifiers';\n\nexport { ViewRegistry, type RegisteredViewBuilder, type RegisteredViewContext, type RegisteredViewInstance } from '@swiftbrowser/web/src/viewRegistry';\n\nexport interface RegisteredViewProps extends ViewModifiers {\n /** The name the view is registered under, on each platform. */\n name: string;\n /** JSON-serializable props for the view. */\n props?: Record<string, unknown>;\n /** A value the view sent (`context.send(value)`). */\n onEvent?: (value: unknown) => void;\n /** Views for the native view to place (`context.content`); a page's view has none. */\n children?: ReactNode;\n}\n\nexport function RegisteredView(all: RegisteredViewProps): ReactNode {\n const { own, modifiers } = splitProps(all);\n const on = own.onEvent ? { registered: (event: { value: unknown }) => own.onEvent!(event.value) } : undefined;\n return applyModifiers(sb('registered', { name: own.name, props: own.props ?? {} }, on, own.children), modifiers);\n}\n","import { Fragment, type ReactNode } from 'react';\nimport { readBinding, type BindingValue } from '../binding';\nimport { withEnvironment } from '../environment';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, type ViewModifiers } from '../modifiers';\nimport { Button } from './controls';\nimport { Text } from './text';\n\nexport interface MenuProps extends ViewModifiers {\n /** The label: a title, or any view. */\n title?: string;\n label?: ReactNode;\n /** The items: buttons, pickers, dividers, sections, texts, nested menus. */\n children?: ReactNode;\n}\n\n/** `Menu(\"Sort\") { … }`: the label opens a popover of the items. */\nexport function Menu(props: MenuProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const label = own.title !== undefined ? <Text>{own.title}</Text> : own.label;\n // The items' labels show title and icon even in a bar, whose own labels\n // are icons (a filter menu's checked entries), as a menu's do on iOS.\n const items = withEnvironment({ labelStyle: 'automatic' }, own.children);\n return applyModifiers(\n sb('menu', {}, undefined, [\n <Fragment key=\"label\">{sb('zstack', { alignment: 'center' }, undefined, label)}</Fragment>,\n <Fragment key=\"items\">{items}</Fragment>,\n ]),\n modifiers,\n );\n}\n\nexport interface EditButtonProps extends ViewModifiers {\n /** The list's edit mode (`List editing={…}`). */\n editMode: BindingValue<boolean>;\n onChange?: (editing: boolean) => void;\n}\n\n/** `EditButton()`: \"Edit\" / \"Done\", flipping the edit mode it is given. */\nexport function EditButton(props: EditButtonProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const [editing, setEditing] = readBinding(own.editMode, own.onChange);\n return applyModifiers(<Button title={editing ? 'Done' : 'Edit'} editMode={editing ? 'active' : 'inactive'} action={() => setEditing(!editing)} />, modifiers);\n}\n","import { loadableURL } from '@swiftbrowser/web/src/hostRequests';\nimport { useEffect, useState, type ReactNode } from 'react';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, type ViewModifiers } from '../modifiers';\nimport { ZStack } from './stacks';\n\n/** How long a load runs before `loadingIndicator` shows. */\nexport const LOADING_INDICATOR_DELAY_MS = 300;\n\nexport interface AsyncImageProps extends ViewModifiers {\n url: string;\n /** `.resizable()` on the loaded image. */\n resizable?: boolean;\n /**\n * Shown until the image loaded (nothing by default). The image's modifiers\n * (its frame, aspect ratio, corner radius) apply to it as they do to the\n * picture, as a SwiftUI `AsyncImage`'s do in every phase: a framed image\n * keeps its box while it loads, so the row beside it does not move.\n */\n placeholder?: ReactNode;\n /** Shown when the image failed to load (the placeholder by default), under the same modifiers. */\n failure?: ReactNode;\n /**\n * Shown over the placeholder once a load has run for `loadingIndicatorDelay`\n * ms (300 by default): a `<ProgressView />` for a big picture on a slow\n * connection, nothing for one that comes quickly or from the cache.\n */\n loadingIndicator?: ReactNode;\n loadingIndicatorDelay?: number;\n /**\n * Keep the browser's own image interactions: a long press's Save / Share /\n * Copy on iOS, dragging the image out, the right-click menu. Off by\n * default, as a SwiftUI image is inert; for an image with no tap, gesture\n * or context menu of its own.\n */\n webInteractions?: boolean;\n /** `.accessibilityLabel(_:)`: what the picture shows (alt text). */\n accessibilityLabel?: string | undefined;\n}\n\ninterface Loaded {\n url: string;\n width: number;\n height: number;\n}\n\nconst loaded = new Map<string, Loaded | 'failed'>();\n\n/**\n * In a SwiftBrowser Native app: JavaScriptCore with the native bridge and no\n * DOM, so no `Image` to load with. (A page has `Image`, the native round\n * trip's included; a server render or a test has no bridge.)\n */\nfunction inNativeApp(): boolean {\n return typeof Image === 'undefined' && (globalThis as { __sbNative?: unknown }).__sbNative !== undefined;\n}\n\n/**\n * `AsyncImage(url:)`: the page loads the image to learn its size (the\n * engine lays a remote image out by its pixel size, as the Swift core does\n * after its `image` request), then shows it. A SwiftBrowser Native app's\n * runtime gives it an `Image` too (@swiftbrowser/native's image.ts, over\n * the host's image loader), so the placeholder shows there as well; on a\n * host without one the URL goes to the renderer at once and SwiftUI's own\n * `AsyncImage` loads it.\n */\nexport function AsyncImage(props: AsyncImageProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const [state, setState] = useState<Loaded | 'failed' | null>(() => loaded.get(own.url) ?? null);\n useEffect(() => {\n const cached = loaded.get(own.url);\n if (cached) {\n setState(cached);\n return;\n }\n if (typeof Image === 'undefined') return;\n let live = true;\n const image = new Image();\n image.onload = () => {\n const result: Loaded = { url: own.url, width: image.naturalWidth, height: image.naturalHeight };\n loaded.set(own.url, result);\n if (live) setState(result);\n };\n image.onerror = () => {\n loaded.set(own.url, 'failed');\n if (live) setState('failed');\n };\n // A `file:` URL of the app's files probes at its object URL.\n const src = loadableURL(own.url);\n if (typeof src === 'string') image.src = src;\n else void src.then((resolved) => live && (image.src = resolved));\n return () => {\n live = false;\n };\n }, [own.url]);\n // The indicator, once a load has taken its while.\n const hasIndicator = own.loadingIndicator !== undefined && own.loadingIndicator !== null;\n const delay = own.loadingIndicatorDelay ?? LOADING_INDICATOR_DELAY_MS;\n const [slow, setSlow] = useState(false);\n useEffect(() => {\n if (state !== null || !hasIndicator) {\n setSlow(false);\n return;\n }\n const timer = setTimeout(() => setSlow(true), delay);\n return () => clearTimeout(timer);\n }, [state, hasIndicator, delay]);\n if (inNativeApp()) {\n return applyModifiers(sb('image', { ...imageProps(own), url: own.url, width: 0, height: 0 }), modifiers);\n }\n // Before the picture: what the app shows for the phase, or an empty stack\n // (no size of its own), under the image's modifiers, so a frame or an\n // aspect ratio holds the picture's box.\n if (state === null) {\n const placeholder = own.placeholder ?? <ZStack />;\n const shown =\n slow && hasIndicator ? (\n <ZStack>\n {placeholder}\n {own.loadingIndicator}\n </ZStack>\n ) : (\n placeholder\n );\n return applyModifiers(shown, modifiers);\n }\n if (state === 'failed') return applyModifiers(own.failure ?? own.placeholder ?? <ZStack />, modifiers);\n return applyModifiers(sb('image', { ...imageProps(own), url: state.url, width: state.width, height: state.height }), modifiers);\n}\n\n/** The `image` element's props besides its URL and size. */\nfunction imageProps(own: AsyncImageProps): Record<string, unknown> {\n return {\n resizable: own.resizable ?? false,\n ...(own.webInteractions ? { webInteractions: true } : {}),\n ...(own.accessibilityLabel ? { accessibilityLabel: own.accessibilityLabel } : {}),\n };\n}\n","/**\n * Swift Charts: `Chart` with bar, line, area, point and rule marks. The\n * marks are declarations; `Chart` reads them, builds the scales (bands for\n * categories, \"nice\" numeric domains, calendar strides for dates), turns\n * every value into the protocol's unit coordinates and emits one `chart`\n * element with its axes and legend, as Sources/SwiftUI/Charts does.\n */\n\nimport type {\n ChartAxis,\n ChartInterpolation,\n ChartLegend,\n ChartMark,\n ChartSymbol,\n FrameAlignment,\n ShapeStyle,\n} from '@swiftbrowser/web/src/protocol';\nimport { Fragment, type ReactElement, type ReactNode } from 'react';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, type ViewModifiers } from '../modifiers';\nimport { shapeStyle, type StyleValue } from '../values';\nimport { flattenChildren } from './stacks';\n\nexport type ChartValue = number | Date | string;\n\nexport interface AnnotationSpec {\n position?: 'top' | 'bottom' | 'leading' | 'trailing' | 'overlay';\n alignment?: FrameAlignment;\n spacing?: number;\n content: ReactNode;\n}\n\ninterface MarkCommon {\n foregroundStyle?: StyleValue;\n /** `.foregroundStyle(by:)`: a series name; the palette colors it and the legend lists it. */\n foregroundStyleBy?: string;\n opacity?: number;\n /** `.annotation(position:alignment:spacing:) { }` */\n annotation?: AnnotationSpec;\n}\n\nexport interface BarMarkProps extends MarkCommon {\n x: ChartValue;\n y: ChartValue;\n /** `yStart:` (0 by default). */\n yStart?: number;\n cornerRadius?: number;\n /** `width: .fixed(points)` */\n width?: number;\n /**\n * `.position(by:)`: bars at the same `x` side by side, one slot of the\n * band per value (in first-seen order across the chart's bars).\n */\n positionBy?: string;\n}\nexport interface LineMarkProps extends MarkCommon {\n x: ChartValue;\n y: number;\n series?: string;\n interpolation?: ChartInterpolation;\n lineWidth?: number;\n symbol?: ChartSymbol;\n symbolSize?: number;\n}\nexport interface AreaMarkProps extends MarkCommon {\n x: ChartValue;\n y: number;\n yStart?: number;\n series?: string;\n interpolation?: ChartInterpolation;\n}\nexport interface PointMarkProps extends MarkCommon {\n x: ChartValue;\n y: number;\n symbol?: ChartSymbol;\n symbolSize?: number;\n}\nexport interface RuleMarkProps extends MarkCommon {\n /** A vertical rule at `x`, or a horizontal one at `y`. */\n x?: ChartValue;\n y?: number;\n xStart?: ChartValue;\n xEnd?: ChartValue;\n yStart?: number;\n yEnd?: number;\n lineWidth?: number;\n}\n\n/** The marks render nothing themselves; `Chart` reads them. */\nexport function BarMark(_props: BarMarkProps): null {\n return null;\n}\nexport function LineMark(_props: LineMarkProps): null {\n return null;\n}\nexport function AreaMark(_props: AreaMarkProps): null {\n return null;\n}\nexport function PointMark(_props: PointMarkProps): null {\n return null;\n}\nexport function RuleMark(_props: RuleMarkProps): null {\n return null;\n}\n\nexport interface ChartProps extends ViewModifiers {\n /** `.chartXAxis(.hidden)` is `null`; the position otherwise. */\n xAxis?: 'bottom' | 'top' | null;\n yAxis?: 'trailing' | 'leading' | null;\n /** `.chartLegend`: the position, or `null` to hide it. Shown at the top when a series exists. */\n legend?: 'top' | 'bottom' | 'leading' | 'trailing' | null;\n /** `.chartXScale(domain:)`: numbers, dates or the categories in order. */\n xScale?: { domain?: readonly [ChartValue, ChartValue] | readonly string[] };\n /** `.chartYScale(domain:)`; `includesZero` is true by default, as in Swift Charts. */\n yScale?: { domain?: readonly [number, number]; includesZero?: boolean };\n /** `.chartYAxis { AxisMarks(format:) }`: the text of a numeric axis's labels (`(v) => `$${v}``). */\n yAxisFormat?: (value: number) => string;\n children?: ReactNode;\n}\n\nconst PALETTE = ['blue', 'green', 'orange', 'purple', 'red', 'teal', 'yellow', 'pink', 'indigo', 'mint', 'cyan', 'brown'] as const;\nconst SYMBOLS: ChartSymbol[] = ['circle', 'square', 'triangle', 'diamond', 'cross', 'plus', 'asterisk'];\n\ntype MarkKind = 'bar' | 'line' | 'area' | 'point' | 'rule';\ninterface Declared {\n kind: MarkKind;\n props: BarMarkProps & LineMarkProps & AreaMarkProps & PointMarkProps & RuleMarkProps;\n}\n\nfunction declaredMarks(children: ReactNode): Declared[] {\n const kinds = new Map<unknown, MarkKind>([\n [BarMark, 'bar'],\n [LineMark, 'line'],\n [AreaMark, 'area'],\n [PointMark, 'point'],\n [RuleMark, 'rule'],\n ]);\n const result: Declared[] = [];\n for (const element of flattenChildren(children)) {\n const kind = kinds.get(element.type);\n if (kind) result.push({ kind, props: element.props as Declared['props'] });\n }\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Scales\n// ---------------------------------------------------------------------------\n\ninterface Scale {\n /** Unit position of a value along the axis (0 → 1 left to right / bottom to top). */\n unit(value: ChartValue): number;\n /** The band of a category, or the band around a continuous center. */\n band(value: ChartValue): [number, number];\n ticks: number[];\n gridLines: number[];\n labels: { at: number; text: string; anchor?: 'leading' }[];\n domain: [number, number];\n kind: 'band' | 'number' | 'time';\n}\n\nconst asNumber = (value: ChartValue): number => (value instanceof Date ? value.getTime() : typeof value === 'number' ? value : NaN);\n\nfunction bandScale(categories: string[]): Scale {\n const n = Math.max(categories.length, 1);\n const index = new Map(categories.map((c, i) => [c, i]));\n const center = (value: ChartValue): number => ((index.get(String(value)) ?? 0) + 0.5) / n;\n return {\n kind: 'band',\n unit: center,\n band: (value) => {\n const i = index.get(String(value)) ?? 0;\n return [i / n, (i + 1) / n];\n },\n ticks: categories.map((_, i) => (i + 0.5) / n),\n gridLines: [],\n labels: categories.map((text, i) => ({ at: (i + 0.5) / n, text })),\n domain: [0, n],\n };\n}\n\n/** Steps of 1, 2, 2.5, 5 × 10ᵏ, the one nearest `span / (desired − 1)`. */\nexport function niceStep(span: number, desired = 5): number {\n if (!(span > 0)) return 1;\n const raw = span / Math.max(desired - 1, 1);\n const magnitude = 10 ** Math.floor(Math.log10(raw));\n let best = magnitude;\n // A tie goes to the larger step (fewer ticks).\n for (const candidate of [1, 2, 2.5, 5, 10].map((m) => m * magnitude)) {\n if (Math.abs(candidate - raw) <= Math.abs(best - raw)) best = candidate;\n }\n return best;\n}\n\nfunction decimalsOf(step: number): number {\n const text = step.toString();\n const dot = text.indexOf('.');\n return dot < 0 ? 0 : text.length - dot - 1;\n}\n\nfunction numberScale(values: number[], options: { includesZero?: boolean | undefined; domain?: readonly [number, number] | undefined } = {}): Scale {\n let min = Math.min(...values);\n let max = Math.max(...values);\n if (!Number.isFinite(min) || !Number.isFinite(max)) {\n min = 0;\n max = 1;\n }\n if (options.includesZero) {\n min = Math.min(min, 0);\n max = Math.max(max, 0);\n }\n if (min === max) {\n if (min === 0) max = 1;\n else {\n min = Math.min(min, 0);\n max = Math.max(max, 0);\n if (min === max) max = min + 1;\n }\n }\n const step = niceStep(max - min);\n let lo: number;\n let hi: number;\n if (options.domain) [lo, hi] = options.domain;\n else {\n lo = Math.floor(min / step + 1e-9) * step;\n hi = Math.ceil(max / step - 1e-9) * step;\n }\n const ticks: number[] = [];\n const first = Math.ceil(lo / step - 1e-9) * step;\n for (let value = first; value <= hi + 1e-9; value += step) ticks.push(Number(value.toFixed(10)));\n const decimals = decimalsOf(step);\n const unit = (value: ChartValue): number => (asNumber(value) - lo) / (hi - lo || 1);\n const format = new Intl.NumberFormat('en-US', { maximumFractionDigits: decimals });\n return {\n kind: 'number',\n unit,\n band: (value) => [unit(value), unit(value)],\n ticks: ticks.map(unit),\n gridLines: ticks.map(unit),\n labels: ticks.map((value) => ({ at: unit(value), text: format.format(value) })),\n domain: [lo, hi],\n };\n}\n\nconst HOUR = 3_600_000;\nconst DAY = 24 * HOUR;\nconst MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\n\n/** Calendar ticks in UTC, with the stride that gives at most `desired + 1` intervals. */\nexport function timeTicks(min: number, max: number, desired = 8): { ticks: number[]; format: (ms: number) => string } {\n const span = Math.max(max - min, 1);\n const pick = (strides: number[], unit: number): number => strides.find((s) => span / (s * unit) <= desired + 1) ?? strides[strides.length - 1]!;\n const ticks: number[] = [];\n if (span <= 3 * DAY) {\n const hours = pick([1, 3, 6, 12], HOUR);\n const start = Math.floor(min / (hours * HOUR)) * hours * HOUR;\n for (let t = start; t <= max; t += hours * HOUR) if (t >= min) ticks.push(t);\n return {\n ticks,\n format: (ms) => {\n const h = new Date(ms).getUTCHours();\n const minute = new Date(ms).getUTCMinutes();\n const suffix = h < 12 ? 'AM' : 'PM';\n const hour12 = h % 12 === 0 ? 12 : h % 12;\n return minute === 0 ? `${hour12} ${suffix}` : `${hour12}:${String(minute).padStart(2, '0')} ${suffix}`;\n },\n };\n }\n if (span <= 45 * DAY) {\n const days = pick([1, 2, 7, 14], DAY);\n const start = Math.floor(min / DAY) * DAY;\n for (let t = start; t <= max; t += days * DAY) if (t >= min) ticks.push(t);\n return { ticks, format: (ms) => `${MONTHS[new Date(ms).getUTCMonth()]} ${new Date(ms).getUTCDate()}` };\n }\n const months = span / (30.4 * DAY);\n if (months <= 6 * (desired + 1)) {\n const stride = pick([1, 2, 3, 6], 30.4 * DAY);\n const first = new Date(min);\n let year = first.getUTCFullYear();\n let month = Math.floor(first.getUTCMonth() / stride) * stride;\n for (;;) {\n const t = Date.UTC(year, month, 1);\n if (t > max) break;\n if (t >= min) ticks.push(t);\n month += stride;\n if (month >= 12) {\n month -= 12;\n year += 1;\n }\n }\n const years = new Set(ticks.map((t) => new Date(t).getUTCFullYear()));\n return {\n ticks,\n format: (ms) => {\n const d = new Date(ms);\n return years.size > 1 ? `${MONTHS[d.getUTCMonth()]} ${d.getUTCFullYear()}` : MONTHS[d.getUTCMonth()]!;\n },\n };\n }\n const stride = pick([1, 2, 5, 10], 365.25 * DAY);\n const startYear = Math.floor(new Date(min).getUTCFullYear() / stride) * stride;\n for (let year = startYear; ; year += stride) {\n const t = Date.UTC(year, 0, 1);\n if (t > max) break;\n if (t >= min) ticks.push(t);\n }\n return { ticks, format: (ms) => String(new Date(ms).getUTCFullYear()) };\n}\n\nfunction timeScale(values: number[], domain?: readonly [ChartValue, ChartValue]): Scale {\n let lo = domain ? asNumber(domain[0]) : Math.min(...values);\n let hi = domain ? asNumber(domain[1]) : Math.max(...values);\n if (!Number.isFinite(lo) || !Number.isFinite(hi)) {\n lo = 0;\n hi = DAY;\n }\n if (lo === hi) hi = lo + DAY;\n const { ticks, format } = timeTicks(lo, hi);\n const unit = (value: ChartValue): number => (asNumber(value) - lo) / (hi - lo);\n return {\n kind: 'time',\n unit,\n band: (value) => [unit(value), unit(value)],\n ticks: ticks.map(unit),\n gridLines: ticks.map(unit),\n labels: ticks.map((t) => ({ at: unit(t), text: format(t), anchor: 'leading' as const })),\n domain: [lo, hi],\n };\n}\n\nfunction scaleFor(values: ChartValue[], options: { includesZero?: boolean | undefined; domain?: (ChartProps['xScale'] extends infer S ? (S extends { domain?: infer D } ? D : never) : never) | undefined }): Scale {\n const domain = options.domain;\n if (domain && domain.length > 2) return bandScale([...(domain as readonly string[])]);\n if (domain && domain.length === 2 && typeof domain[0] === 'string') return bandScale([...(domain as readonly string[])]);\n if (values.some((v) => typeof v === 'string')) {\n const categories: string[] = [];\n for (const v of values) if (!categories.includes(String(v))) categories.push(String(v));\n return bandScale(categories);\n }\n if (values.some((v) => v instanceof Date)) return timeScale(values.map(asNumber), domain as readonly [ChartValue, ChartValue] | undefined);\n return numberScale(values.map(asNumber), { includesZero: options.includesZero, domain: domain as readonly [number, number] | undefined });\n}\n\n// ---------------------------------------------------------------------------\n// Chart\n// ---------------------------------------------------------------------------\n\nexport function Chart(props: ChartProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const marks = declaredMarks(own.children);\n\n // Series, in first-seen order, colored from the palette.\n const series: string[] = [];\n for (const mark of marks) {\n const key = mark.props.foregroundStyleBy;\n if (key !== undefined && !series.includes(key)) series.push(key);\n }\n const styleOf = (mark: Declared): ShapeStyle => {\n if (mark.props.foregroundStyle !== undefined) return shapeStyle(mark.props.foregroundStyle);\n const key = mark.props.foregroundStyleBy;\n if (key !== undefined) return { name: PALETTE[series.indexOf(key) % PALETTE.length]! };\n return { name: 'blue' };\n };\n\n // Scales from every value a mark touches.\n const xValues: ChartValue[] = [];\n const yValues: ChartValue[] = [];\n for (const { kind, props: p } of marks) {\n if (p.x !== undefined) xValues.push(p.x);\n if (p.xStart !== undefined) xValues.push(p.xStart);\n if (p.xEnd !== undefined) xValues.push(p.xEnd);\n if (p.y !== undefined) yValues.push(p.y);\n if (p.yStart !== undefined) yValues.push(p.yStart);\n if (p.yEnd !== undefined) yValues.push(p.yEnd);\n if (kind === 'bar' || kind === 'area') yValues.push(p.yStart ?? 0);\n }\n const xScale = scaleFor(xValues, { domain: own.xScale?.domain });\n const yScale = scaleFor(yValues, { includesZero: own.yScale?.includesZero ?? true, domain: own.yScale?.domain });\n if (own.yAxisFormat && yScale.kind === 'number') {\n const [lo, hi] = yScale.domain;\n const format = own.yAxisFormat;\n yScale.labels = yScale.labels.map((label) => ({ ...label, text: format(Number((lo + label.at * (hi - lo)).toFixed(10))) }));\n }\n // Unit coordinates, rounded so equal values compare equal.\n const round = (n: number): number => Math.round(n * 1e6) / 1e6;\n const ux = (v: ChartValue): number => round(xScale.unit(v));\n const uy = (v: ChartValue): number => round(1 - yScale.unit(v));\n\n // Bars on a continuous x axis: the band is the smallest gap between centers.\n let continuousBand = 1;\n if (xScale.kind !== 'band') {\n const centers = [...new Set(marks.filter((m) => m.kind === 'bar').map((m) => ux(m.props.x)))].sort((a, b) => a - b);\n for (let i = 1; i < centers.length; i++) continuousBand = Math.min(continuousBand, centers[i]! - centers[i - 1]!);\n }\n\n // `.position(by:)`: each value a slot of the bar's band, in first-seen order.\n const positions: string[] = [];\n for (const mark of marks) {\n const key = mark.kind === 'bar' ? mark.props.positionBy : undefined;\n if (key !== undefined && !positions.includes(key)) positions.push(key);\n }\n\n const encoded: ChartMark[] = [];\n const items: ReactElement[] = [];\n const annotate = (mark: Declared, rect: { x0: number; x1: number; y0: number; y1: number }): void => {\n const annotation = mark.props.annotation;\n if (!annotation) return;\n items.push(\n <Fragment key={items.length}>\n {sb(\n 'chartitem',\n {\n role: 'annotation',\n ...rect,\n position: annotation.position ?? 'top',\n alignment: annotation.alignment ?? 'center',\n spacing: annotation.spacing ?? 4,\n },\n undefined,\n annotation.content,\n )}\n </Fragment>,\n );\n };\n const common = (mark: Declared): { style: ShapeStyle; opacity?: number } => {\n const base: { style: ShapeStyle; opacity?: number } = { style: styleOf(mark) };\n if (mark.props.opacity !== undefined) base.opacity = mark.props.opacity;\n return base;\n };\n\n // Lines and areas group by series key, in first-seen order, points in x order.\n const groups = new Map<string, Declared[]>();\n for (const mark of marks) {\n if (mark.kind !== 'line' && mark.kind !== 'area') continue;\n const key = `${mark.kind}:${mark.props.series ?? mark.props.foregroundStyleBy ?? ''}`;\n const group = groups.get(key);\n if (group) group.push(mark);\n else groups.set(key, [mark]);\n }\n const emittedGroups = new Set<string>();\n\n for (const mark of marks) {\n const p = mark.props;\n switch (mark.kind) {\n case 'bar': {\n const style = common(mark);\n let [b0, b1] = xScale.kind === 'band' ? xScale.band(p.x) : [ux(p.x) - continuousBand / 2, ux(p.x) + continuousBand / 2];\n if (p.positionBy !== undefined && positions.length > 1) {\n // The bars of a group share 80% of the band, each 90% of its slot.\n const slot = ((b1 - b0) * 0.8) / positions.length;\n const start = b0 + (b1 - b0) * 0.1 + slot * positions.indexOf(p.positionBy);\n [b0, b1] = [start - slot / 16, start + slot + slot / 16];\n }\n const center = round((b0 + b1) / 2);\n const half = round(((b1 - b0) * 0.8) / 2);\n const top = uy(Math.max(asNumber(p.y), p.yStart ?? 0));\n const bottom = uy(Math.min(asNumber(p.y), p.yStart ?? 0));\n const rect: ChartMark = {\n kind: 'rect',\n ...style,\n x0: p.width !== undefined ? center : round(center - half),\n x1: p.width !== undefined ? center : round(center + half),\n y0: top,\n y1: bottom,\n cornerRadius: p.cornerRadius ?? 0,\n fixedWidth: p.width ?? null,\n };\n encoded.push(rect);\n annotate(mark, { x0: rect.x0, x1: rect.x1, y0: top, y1: bottom });\n break;\n }\n case 'line':\n case 'area': {\n const key = `${mark.kind}:${p.series ?? p.foregroundStyleBy ?? ''}`;\n if (emittedGroups.has(key)) {\n annotate(mark, { x0: ux(p.x), x1: ux(p.x), y0: uy(p.y), y1: uy(p.y) });\n break;\n }\n emittedGroups.add(key);\n const group = [...groups.get(key)!].sort((a, b) => ux(a.props.x) - ux(b.props.x));\n const first = group[0]!;\n if (mark.kind === 'line') {\n const line: ChartMark = {\n kind: 'line',\n ...common(first),\n points: group.map((m) => ({ x: ux(m.props.x), y: uy(m.props.y) })),\n lineWidth: first.props.lineWidth ?? 2,\n interpolation: first.props.interpolation ?? 'linear',\n symbol: first.props.symbol ?? (first.props.foregroundStyleBy !== undefined && marks.some((m) => m.props.symbol) ? SYMBOLS[series.indexOf(first.props.foregroundStyleBy) % SYMBOLS.length]! : null),\n symbolSize: first.props.symbolSize ?? 8,\n };\n encoded.push(line);\n } else {\n const area: ChartMark = {\n kind: 'area',\n ...common(first),\n points: group.map((m) => ({\n x: ux(m.props.x),\n y0: uy(Math.max(m.props.y, m.props.yStart ?? 0)),\n y1: uy(Math.min(m.props.y, m.props.yStart ?? 0)),\n })),\n interpolation: first.props.interpolation ?? 'linear',\n };\n encoded.push(area);\n }\n annotate(mark, { x0: ux(p.x), x1: ux(p.x), y0: uy(p.y), y1: uy(p.y) });\n break;\n }\n case 'point': {\n const point: ChartMark = { kind: 'point', ...common(mark), x: ux(p.x), y: uy(p.y), symbol: p.symbol ?? 'circle', symbolSize: p.symbolSize ?? 8 };\n encoded.push(point);\n annotate(mark, { x0: point.x, x1: point.x, y0: point.y, y1: point.y });\n break;\n }\n case 'rule': {\n const vertical = p.x !== undefined;\n const rule: ChartMark = {\n kind: 'rule',\n ...common(mark),\n x0: vertical ? ux(p.x!) : p.xStart !== undefined ? ux(p.xStart) : 0,\n x1: vertical ? ux(p.x!) : p.xEnd !== undefined ? ux(p.xEnd) : 1,\n y0: vertical ? (p.yEnd !== undefined ? uy(p.yEnd) : 0) : uy(p.y ?? 0),\n y1: vertical ? (p.yStart !== undefined ? uy(p.yStart) : 1) : uy(p.y ?? 0),\n lineWidth: p.lineWidth ?? 1,\n };\n encoded.push(rule);\n annotate(mark, { x0: rule.x0, x1: rule.x1, y0: rule.y0, y1: rule.y1 });\n break;\n }\n default:\n break;\n }\n }\n\n const axis = (scale: Scale, position: ChartAxis['position'], flipY: boolean): ChartAxis => {\n const flip = (u: number): number => round(flipY ? 1 - u : u);\n return {\n position,\n gridLines: scale.gridLines.map(flip),\n ticks: scale.ticks.map(flip),\n labels: scale.labels.map((label) => ({ ...label, at: flip(label.at) })),\n // Swift Charts dashes a date axis's grid lines.\n ...(scale.kind === 'time' ? { dashed: true as const } : {}),\n };\n };\n const chartProps = {\n marks: encoded,\n xAxis: own.xAxis === null ? null : axis(xScale, own.xAxis ?? 'bottom', false),\n yAxis: own.yAxis === null ? null : axis(yScale, own.yAxis ?? 'trailing', true),\n legend:\n own.legend === null || series.length === 0\n ? null\n : ({\n position: own.legend ?? 'top',\n items: series.map((label, index) => ({ label, style: { name: PALETTE[index % PALETTE.length]! }, symbol: null })),\n } satisfies ChartLegend),\n };\n return applyModifiers(sb('chart', chartProps, undefined, items.length ? items : undefined), modifiers);\n}\n","/**\n * Gauges, `ViewThatFits`, lazy stacks, and the composite containers the\n * shim builds from other views: `ContentUnavailableView`, `GroupBox`,\n * `ControlGroup`, `DisclosureGroup`.\n */\n\nimport type { GaugeStyle, HStackAlignment, VStackAlignment } from '@swiftbrowser/web/src/protocol';\nimport { Fragment, useState, type ReactNode } from 'react';\nimport { LazyContext, LazyStackContext } from '../lazy';\nimport { readBinding, type BindingValue } from '../binding';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, styled, type ViewModifiers } from '../modifiers';\nimport { withAnimation } from '../host/root';\nimport { RoundedRectangle } from './shapes';\nimport { HStack, VStack, type PinnedViews } from './stacks';\nimport { Image, Text } from './text';\n\n// ---------------------------------------------------------------------------\n// Gauge\n// ---------------------------------------------------------------------------\n\nexport interface GaugeProps extends ViewModifiers {\n value: number;\n /** `in: 0...1` */\n range?: readonly [number, number];\n label?: ReactNode;\n currentValueLabel?: ReactNode;\n gaugeStyle?: Exclude<GaugeStyle, 'progress'>;\n}\n\n/** `Gauge(value:in:) { label } currentValueLabel: { }` */\nexport function Gauge(props: GaugeProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const [min, max] = own.range ?? [0, 1];\n const value = (own.value - min) / (max - min || 1);\n const children: ReactNode[] = [];\n const asView = (node: ReactNode): ReactNode => (typeof node === 'string' || typeof node === 'number' ? <Text>{node}</Text> : node);\n if (own.label !== undefined) children.push(<Fragment key=\"label\">{asView(own.label)}</Fragment>);\n if (own.currentValueLabel !== undefined) children.push(<Fragment key=\"current\">{asView(own.currentValueLabel)}</Fragment>);\n return applyModifiers(\n sb(\n 'gauge',\n {\n value: Math.min(1, Math.max(0, value)),\n style: own.gaugeStyle ?? 'automatic',\n hasLabel: own.label !== undefined,\n hasCurrentValueLabel: own.currentValueLabel !== undefined,\n },\n undefined,\n children.length ? children : undefined,\n ),\n modifiers,\n );\n}\n\n// ---------------------------------------------------------------------------\n// ViewThatFits\n// ---------------------------------------------------------------------------\n\nexport interface ViewThatFitsProps extends ViewModifiers {\n /** The axes a candidate must fit on (`in:`); both by default. */\n axes?: 'horizontal' | 'vertical' | 'both';\n /** The candidates, preferred first. */\n children?: ReactNode;\n}\n\n/** `ViewThatFits`: the first child whose ideal size fits, else the last. */\nexport function ViewThatFits(props: ViewThatFitsProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n return applyModifiers(sb('viewthatfits', { axes: own.axes ?? 'both' }, undefined, own.children), modifiers);\n}\n\n// ---------------------------------------------------------------------------\n// Lazy stacks\n// ---------------------------------------------------------------------------\n\n\nexport interface LazyVStackProps extends ViewModifiers {\n alignment?: VStackAlignment;\n spacing?: number | null;\n /** `.scrollTargetLayout()`: the children are the scroll view's snap points. */\n scrollTargetLayout?: boolean;\n /** `pinnedViews: [.sectionHeaders]`: each `Section`'s header stays at the top while its rows scroll by. */\n pinnedViews?: PinnedViews;\n children?: ReactNode;\n}\n\n/** `LazyVStack`: a `VStack` whose long `ForEach`es build their rows as they scroll into view. */\nexport function LazyVStack(props: LazyVStackProps): ReactNode {\n return (\n <LazyContext.Provider value=\"vertical\">\n <LazyStackContext.Provider value={true}>\n <VStack {...props} />\n </LazyStackContext.Provider>\n </LazyContext.Provider>\n );\n}\n\nexport interface LazyHStackProps extends ViewModifiers {\n alignment?: HStackAlignment;\n spacing?: number | null;\n scrollTargetLayout?: boolean;\n /** `pinnedViews: [.sectionHeaders]`: each `Section`'s header stays at the leading edge while its cells scroll by. */\n pinnedViews?: PinnedViews;\n children?: ReactNode;\n}\n\nexport function LazyHStack(props: LazyHStackProps): ReactNode {\n return (\n <LazyContext.Provider value=\"horizontal\">\n <LazyStackContext.Provider value={true}>\n <HStack {...props} />\n </LazyStackContext.Provider>\n </LazyContext.Provider>\n );\n}\n\n// ---------------------------------------------------------------------------\n// Composites\n// ---------------------------------------------------------------------------\n\nexport interface ContentUnavailableViewProps extends ViewModifiers {\n title: ReactNode;\n systemImage?: string;\n /** A string or a view. */\n description?: ReactNode;\n actions?: ReactNode;\n}\n\n/** `ContentUnavailableView(_:systemImage:description:)`: the empty state iOS shows, filling its space. */\nexport function ContentUnavailableView(props: ContentUnavailableViewProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const title = typeof own.title === 'string' ? <Text>{own.title}</Text> : own.title;\n const description = typeof own.description === 'string' ? <Text>{own.description}</Text> : own.description;\n return applyModifiers(\n <VStack spacing={16} padding={['horizontal', 32]} frame={{ maxWidth: Infinity, maxHeight: Infinity }}>\n <VStack spacing={8}>\n <VStack spacing={12}>\n {own.systemImage !== undefined && <Image systemName={own.systemImage} font={{ size: 48 }} foregroundStyle=\"secondary\" />}\n {styled({ multilineTextAlignment: 'center' }, styled({ font: { textStyle: 'title2', weight: 'bold' } }, title))}\n </VStack>\n {description !== undefined &&\n styled({ multilineTextAlignment: 'center' }, styled({ foreground: { hierarchical: 2 } }, styled({ font: { textStyle: 'callout' } }, description)))}\n </VStack>\n {own.actions}\n </VStack>,\n modifiers,\n );\n}\n\n/** `ContentUnavailableView.search(text:)` */\nContentUnavailableView.search = (text?: string): ReactNode => (\n <ContentUnavailableView\n title={text ? `No Results for “${text}”` : 'No Results'}\n systemImage=\"magnifyingglass\"\n description=\"Check the spelling or try a new search.\"\n />\n);\n\nexport interface GroupBoxProps extends ViewModifiers {\n label?: ReactNode;\n children?: ReactNode;\n}\n\n/** `GroupBox`: the label (headline) over the content, in a padded rounded box. */\nexport function GroupBox(props: GroupBoxProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const label = typeof own.label === 'string' ? <Text>{own.label}</Text> : own.label;\n return applyModifiers(\n <VStack\n alignment=\"leading\"\n spacing={8}\n padding={16}\n background={{ fill: 'secondarySystemBackground', in: <RoundedRectangle cornerRadius={8} /> }}\n >\n {label !== undefined && styled({ font: { textStyle: 'headline' } }, label)}\n {own.children}\n </VStack>,\n modifiers,\n );\n}\n\n/** `ControlGroup`: its controls, flowing in the enclosing stack (or items of their own in a menu). Its label is not drawn. */\nexport function ControlGroup(props: { label?: ReactNode; children?: ReactNode } & ViewModifiers): ReactNode {\n const { own, modifiers } = splitProps(props);\n return modifiers.length ? applyModifiers(<>{own.children}</>, modifiers) : own.children;\n}\n\nexport interface DisclosureGroupProps extends ViewModifiers {\n label: ReactNode;\n isExpanded?: BindingValue<boolean>;\n onExpandedChange?: (expanded: boolean) => void;\n children?: ReactNode;\n}\n\n/**\n * `DisclosureGroup`: a row with the label and a chevron that turns down as\n * the content opens below it. The `disclosuregroup` element carries\n * `expanded`, its label (first, in a `zstack`) and its content, which the\n * renderers show when expanded (the web renderer lays out the label alone\n * otherwise; the native renderer draws SwiftUI's own); a `tap` toggles.\n */\nexport function DisclosureGroup(props: DisclosureGroupProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const [internal, setInternal] = useState(false);\n const [expanded, setExpanded] = own.isExpanded !== undefined ? readBinding(own.isExpanded, own.onExpandedChange) : [internal, setInternal];\n const label = typeof own.label === 'string' ? <Text>{own.label}</Text> : own.label;\n const toggle = (): void => withAnimation({ type: 'easeInOut', duration: 0.25 }, () => setExpanded(!expanded));\n return applyModifiers(\n sb('disclosuregroup', { expanded }, { tap: toggle }, [\n <Fragment key=\"label\">{sb('zstack', { alignment: 'center' }, undefined, label)}</Fragment>,\n <Fragment key=\"content\">{own.children}</Fragment>,\n ]),\n modifiers,\n );\n}\n","/**\n * `Table`, drawn as iOS draws one: a list. In a compact width each row shows\n * the first column; in a regular width every column under a row of the\n * column titles, a sortable title a button with the sort's chevron.\n */\n\nimport { type Key, type ReactNode } from 'react';\nimport { readBinding, type BindingValue } from '../binding';\nimport { useHorizontalSizeClass } from '../environment';\nimport { applyModifiers, splitProps, styled, type ViewModifiers } from '../modifiers';\nimport { Button } from './controls';\nimport { List, type Selection } from './lists';\nimport { ForEach, HStack, VStack } from './stacks';\nimport { Image, Text } from './text';\n\nexport interface TableColumn<T> {\n title: string;\n /** The cell for a row; a function of the row, or a key whose value is shown as text. */\n content: ((row: T) => ReactNode) | keyof T;\n /** A fixed width; the other columns share the rest. */\n width?: number;\n minWidth?: number;\n maxWidth?: number;\n /** A sortable column: the key its title sorts by (the app sorts the rows by `sortOrder`). */\n sortKey?: string;\n}\n\nexport interface SortDescriptor {\n key: string;\n ascending: boolean;\n}\n\nexport interface TableProps<T, K extends Key = Key> extends ViewModifiers {\n data: readonly T[];\n columns: readonly TableColumn<T>[];\n /** Each row's identity (its `id` property by default), what the selection holds. */\n id?: (row: T, index: number) => K;\n selection?: BindingValue<Set<K>> | BindingValue<K | null>;\n onSelectionChange?: (selection: Selection<K>) => void;\n /** The sort order, first descriptor first; tapping a sortable title puts it first or reverses it. */\n sortOrder?: BindingValue<readonly SortDescriptor[]>;\n}\n\nconst COLUMN_SPACING = 12;\n\nfunction cell<T>(column: TableColumn<T>, content: ReactNode): ReactNode {\n if (column.width !== undefined) return styled({ layoutPriority: 0 }, styled({ frame: { width: column.width, alignment: 'leading' } }, content));\n return styled(\n { layoutPriority: 0 },\n styled({ frame: { minWidth: column.minWidth ?? 0, maxWidth: column.maxWidth ?? 'infinity', alignment: 'leading' } }, content),\n );\n}\n\nfunction cellContent<T>(column: TableColumn<T>, row: T): ReactNode {\n if (typeof column.content === 'function') return column.content(row);\n return <Text>{String(row[column.content] ?? '')}</Text>;\n}\n\nexport function Table<T, K extends Key = Key>(props: TableProps<T, K>): ReactNode {\n const { own, modifiers } = splitProps(props);\n const compact = useHorizontalSizeClass() !== 'regular';\n const sort = own.sortOrder !== undefined ? readBinding(own.sortOrder) : null;\n const keyOf = (row: T, index: number): K => {\n if (own.id) return own.id(row, index);\n const id = (row as { id?: unknown }).id;\n return (typeof id === 'string' || typeof id === 'number' ? id : index) as K;\n };\n const row = (value: T): ReactNode => {\n const first = own.columns[0];\n if (!first) return null;\n if (compact) return cellContent(first, value);\n return (\n <HStack spacing={COLUMN_SPACING}>\n {own.columns.map((column, index) => (\n <ColumnCell key={index}>{cell(column, cellContent(column, value))}</ColumnCell>\n ))}\n </HStack>\n );\n };\n const title = (column: TableColumn<T>): ReactNode => {\n if (!sort || column.sortKey === undefined) return <Text>{column.title}</Text>;\n const [order, setOrder] = sort;\n const current = order[0]?.key === column.sortKey ? order[0] : null;\n const tap = (): void => {\n const rest = order.filter((descriptor) => descriptor.key !== column.sortKey);\n setOrder([{ key: column.sortKey!, ascending: current ? !current.ascending : true }, ...rest]);\n };\n return (\n <Button action={tap} buttonStyle=\"plain\">\n <HStack spacing={4}>\n <Text>{column.title}</Text>\n {current && <Image systemName={current.ascending ? 'chevron.up' : 'chevron.down'} font={{ textStyle: 'caption2', weight: 'bold' }} />}\n </HStack>\n </Button>\n );\n };\n const list = (\n <List<K> selection={own.selection as BindingValue<Set<K>>} onSelectionChange={own.onSelectionChange}>\n <ForEach data={own.data} id={keyOf}>\n {(value, index) => <TableRow tag={keyOf(value, index)}>{row(value)}</TableRow>}\n </ForEach>\n </List>\n );\n if (compact) return applyModifiers(list, modifiers);\n return applyModifiers(\n <VStack spacing={0}>\n <HStack\n spacing={COLUMN_SPACING}\n font={{ textStyle: 'subheadline', weight: 'semibold' }}\n foregroundStyle=\"secondary\"\n padding={['horizontal', 20]}\n modifiers={[{ padding: ['vertical', 8] }]}\n >\n {own.columns.map((column, index) => (\n <ColumnCell key={index}>{cell(column, title(column))}</ColumnCell>\n ))}\n </HStack>\n {list}\n </VStack>,\n modifiers,\n );\n}\n\nfunction ColumnCell({ children }: { children?: ReactNode }): ReactNode {\n return children;\n}\n\n/** A table row: its content, tagged for the list's selection. */\nfunction TableRow({ children }: { tag: Key; children?: ReactNode }): ReactNode {\n return children;\n}\n","/** `ColorPicker` and `ShareLink`: controls that open the browser's own chooser and share sheet. */\n\nimport { chooseColor } from '@swiftbrowser/web/src/colorPicker';\nimport { base64Encode } from '@swiftbrowser/web/src/base64';\nimport { browserEnvironment, performHostRequest } from '@swiftbrowser/web/src/hostRequests';\nimport type { RGBAColor, SharedFile, ShareRequestParams } from '@swiftbrowser/web/src/protocol';\nimport type { ReactNode } from 'react';\nimport { readBinding, type BindingValue } from '../binding';\nimport { applyModifiers, splitProps, type ViewModifiers } from '../modifiers';\nimport { Color, Circle } from './shapes';\nimport { Button } from './controls';\nimport { HStack, Spacer } from './stacks';\nimport { Label, Text } from './text';\n\nexport interface ColorPickerProps extends ViewModifiers {\n title?: string;\n label?: ReactNode;\n selection: BindingValue<RGBAColor>;\n onChange?: (color: RGBAColor) => void;\n}\n\nconst hexOf = (c: RGBAColor): string =>\n '#' + [c.r, c.g, c.b].map((v) => Math.round(Math.min(1, Math.max(0, v)) * 255).toString(16).padStart(2, '0')).join('');\n\n/** `ColorPicker(\"Tint\", selection:)`: the label and a swatch; tapping opens the browser's color chooser. */\nexport function ColorPicker(props: ColorPickerProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const [selection, setSelection] = readBinding(own.selection, own.onChange);\n const label = own.label ?? (own.title !== undefined ? <Text>{own.title}</Text> : null);\n const pick = (): void => {\n chooseColor(hexOf(selection))\n .then((chosen) => {\n if (chosen) setSelection({ ...Color.hex(chosen), a: selection.a });\n })\n .catch((error: unknown) => console.error(error));\n };\n return applyModifiers(\n <Button action={pick} buttonStyle=\"plain\">\n <HStack>\n {label}\n <Spacer />\n <Circle\n fill={selection}\n frame={{ width: 28, height: 28 }}\n overlay={<Circle strokeBorder={{ style: Color.opacity('secondary', 0.3), lineWidth: 1 }} />}\n />\n </HStack>\n </Button>,\n modifiers,\n );\n}\n\n/** A file to share: its name, its MIME type (from the name's extension when left out) and its bytes. */\nexport interface SharedFileItem {\n name: string;\n type?: string;\n data: string | ArrayBuffer | Uint8Array | Blob;\n}\n\nexport interface ShareLinkProps extends ViewModifiers {\n /** What is shared: a URL, text, or a file (`ShareLink(item: document)` with a `FileRepresentation`). */\n item: string | URL | SharedFileItem;\n /** More files shared with it. */\n files?: SharedFileItem[];\n subject?: string;\n message?: string;\n /** The label; \"Share\" with the share symbol by default. */\n title?: string;\n children?: ReactNode;\n}\n\nconst isFile = (item: ShareLinkProps['item']): item is SharedFileItem => typeof item === 'object' && !(item instanceof URL) && 'data' in item;\n\nconst MIME_BY_EXTENSION: Record<string, string> = {\n txt: 'text/plain',\n md: 'text/markdown',\n csv: 'text/csv',\n json: 'application/json',\n html: 'text/html',\n pdf: 'application/pdf',\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n gif: 'image/gif',\n svg: 'image/svg+xml',\n m4a: 'audio/mp4',\n mp3: 'audio/mpeg',\n mp4: 'video/mp4',\n mov: 'video/quicktime',\n zip: 'application/zip',\n};\n\nasync function sharedFile(file: SharedFileItem): Promise<SharedFile> {\n const bytes =\n typeof file.data === 'string'\n ? new TextEncoder().encode(file.data)\n : file.data instanceof Uint8Array\n ? file.data\n : file.data instanceof ArrayBuffer\n ? new Uint8Array(file.data)\n : new Uint8Array(await file.data.arrayBuffer());\n const extension = file.name.includes('.') ? file.name.slice(file.name.lastIndexOf('.') + 1).toLowerCase() : '';\n return { name: file.name, type: file.type ?? MIME_BY_EXTENSION[extension] ?? 'application/octet-stream', data: base64Encode(bytes) };\n}\n\n/** The `share` request a `ShareLink` sends: the title, the text (the message, then a text item), the URL, and the files (an item file first). */\nexport async function shareParamsOf(props: Pick<ShareLinkProps, 'item' | 'files' | 'subject' | 'message'>): Promise<ShareRequestParams> {\n const item = props.item;\n const isURL = item instanceof URL || (typeof item === 'string' && /^[a-z][a-z0-9+.-]*:\\/\\//i.test(item));\n const params: ShareRequestParams = {};\n if (props.subject) params.title = props.subject;\n if (isURL) params.url = String(item);\n const text = [props.message, typeof item === 'string' && !isURL ? item : null].filter(Boolean).join('\\n');\n if (text) params.text = text;\n const files = [...(isFile(item) ? [item] : []), ...(props.files ?? [])];\n if (files.length) params.files = await Promise.all(files.map(sharedFile));\n return params;\n}\n\n/** `ShareLink(item:)`: the Web Share API where the browser has it (files too), else a download; natively the share sheet. */\nexport function ShareLink(props: ShareLinkProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const share = (): void => {\n // Within the tap (the files' bytes read first), so the browser lets the share sheet open.\n shareParamsOf(own)\n .then((params) => performHostRequest({ op: 'request', id: 0, kind: 'share', params }, browserEnvironment))\n .catch((error: unknown) => console.error(error));\n };\n return applyModifiers(\n <Button action={share}>{own.children ?? <Label title={own.title ?? 'Share'} systemImage=\"square.and.arrow.up\" />}</Button>,\n modifiers,\n );\n}\n","/**\n * `Canvas`: a `GeometryReader` whose content, at the reported size, is a\n * `canvas` element. The renderer function draws into a `GraphicsContext`\n * that records commands, as Sources/SwiftUI/API/Canvas.swift does; the page\n * draws them as SVG.\n */\n\nimport type { CanvasCommand, CanvasFilter, CanvasShading, CanvasState, Font, GradientStop } from '@swiftbrowser/web/src/protocol';\nimport { Fragment, useState, type ReactNode } from 'react';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, styled, type ViewModifiers } from '../modifiers';\nimport type { Path, Point } from '../path';\nimport { color, font, shapeStyle, unitPoint, type ColorValue, type FontValue, type StyleValue, type UnitPointValue } from '../values';\n\ntype Matrix = [number, number, number, number, number, number];\nconst IDENTITY: Matrix = [1, 0, 0, 1, 0, 0];\n\nfunction multiply(m: Matrix, n: Matrix): Matrix {\n // Applies `n` first, then `m` (CGAffineTransform concatenation order).\n const [a, b, c, d, tx, ty] = m;\n const [a2, b2, c2, d2, tx2, ty2] = n;\n return [a2 * a + b2 * c, a2 * b + b2 * d, c2 * a + d2 * c, c2 * b + d2 * d, tx2 * a + ty2 * c + tx, tx2 * b + ty2 * d + ty];\n}\n\n/** A shading in the drawing's coordinates: a style, or a gradient between two points. */\nexport type Shading =\n | StyleValue\n | { linearGradient: { colors?: ColorValue[]; stops?: { color: ColorValue; location: number }[]; start: Point; end: Point } }\n | { radialGradient: { colors?: ColorValue[]; stops?: { color: ColorValue; location: number }[]; center: Point; startRadius: number; endRadius: number } };\n\nfunction stops(spec: { colors?: ColorValue[]; stops?: { color: ColorValue; location: number }[] }): GradientStop[] {\n if (spec.stops) return spec.stops.map((s) => ({ color: color(s.color), location: s.location }));\n const colors = spec.colors ?? [];\n const last = Math.max(colors.length - 1, 1);\n return colors.map((c, i) => ({ color: color(c), location: i / last }));\n}\n\n/** In a drawing `.primary` / `.secondary`… are the label colors, as `.color(.primary)` is. */\nconst LABEL_COLORS: Record<string, CanvasShading> = {\n primary: { name: 'primary' },\n secondary: { name: 'secondary' },\n tertiary: { name: 'tertiaryLabel' },\n quaternary: { name: 'quaternaryLabel' },\n};\n\nfunction shading(value: Shading): CanvasShading {\n if (typeof value === 'string' && value in LABEL_COLORS) return LABEL_COLORS[value]!;\n if (typeof value === 'object' && value !== null) {\n if ('linearGradient' in value) {\n const g = value.linearGradient as { start: Point & { x: number }; end: Point } & Parameters<typeof stops>[0];\n // `LinearGradient(...)` styles carry stops of protocol colors and unit points; canvas gradients carry `colors` or ColorValue stops in points.\n if (isCanvasGradient(g)) return { canvasLinearGradient: { stops: stops(g), start: g.start, end: g.end } };\n }\n if ('radialGradient' in value) {\n const g = value.radialGradient as { center: Point; startRadius: number; endRadius: number } & Parameters<typeof stops>[0];\n if (isCanvasGradient(g)) return { canvasRadialGradient: { stops: stops(g), center: g.center, startRadius: g.startRadius, endRadius: g.endRadius } };\n }\n }\n return shapeStyle(value as StyleValue);\n}\n\n/** A canvas gradient is written with `colors`, or with stops whose colors are names or `#hex` strings. */\nfunction isCanvasGradient(g: { colors?: unknown; stops?: { color: unknown }[] }): boolean {\n if (Array.isArray(g.colors)) return true;\n return Array.isArray(g.stops) && g.stops.some((s) => typeof s.color === 'string');\n}\n\nexport interface StrokeOptions {\n lineWidth?: number;\n lineCap?: 'butt' | 'round' | 'square';\n lineJoin?: 'miter' | 'round' | 'bevel';\n miterLimit?: number;\n dash?: number[];\n dashPhase?: number;\n}\n\n/** What a canvas image is: a symbol, a catalog image, or a remote image of a known size. */\nexport type CanvasImage = { systemName: string } | { name: string } | { url: string; width: number; height: number };\n\ninterface State {\n transform: Matrix;\n opacity: number;\n blendMode: string | undefined;\n clips: string[];\n filters: CanvasFilter[];\n}\n\n/** A view passed in `Canvas`'s `symbols`, resolved by its id. */\nexport interface ResolvedSymbol {\n symbol: string;\n}\n\n/** Where a symbol was drawn: the point (the context's transform applied) and the look at that moment. */\nexport interface SymbolDraw {\n id: string;\n x: number;\n y: number;\n rotation: number;\n scale: { x: number; y: number };\n opacity: number;\n}\n\n/** `GraphicsContext`: what `Canvas`'s renderer draws with. Methods return the context for chaining. */\nexport class GraphicsContext {\n readonly commands: CanvasCommand[] = [];\n readonly symbolDraws: SymbolDraw[] = [];\n private symbolIds: ReadonlySet<string> = new Set();\n\n /** @internal The ids `symbols` gave the canvas. */\n setSymbols(ids: Iterable<string>): void {\n this.symbolIds = new Set(ids);\n }\n\n /** `resolveSymbol(id:)`: the view the canvas was given under `id`, or null. */\n resolveSymbol(id: string): ResolvedSymbol | null {\n return this.symbolIds.has(id) ? { symbol: id } : null;\n }\n\n /**\n * `draw(symbol, at:)`: the symbol's view centered on the point. Symbols are\n * views laid over the drawing, so they draw above its other commands.\n */\n drawSymbol(symbol: ResolvedSymbol, at: Point): this {\n const [a, b, c, d, tx, ty] = this.state.transform;\n const scaleX = Math.hypot(a, b);\n const scaleY = scaleX > 0 ? (a * d - b * c) / scaleX : Math.hypot(c, d);\n this.symbolDraws.push({\n id: symbol.symbol,\n x: a * at.x + c * at.y + tx,\n y: b * at.x + d * at.y + ty,\n rotation: (Math.atan2(b, a) * 180) / Math.PI,\n scale: { x: scaleX, y: scaleY },\n opacity: this.state.opacity,\n });\n return this;\n }\n private state: State = { transform: IDENTITY, opacity: 1, blendMode: undefined, clips: [], filters: [] };\n\n constructor(readonly size: { width: number; height: number }) {}\n\n get opacity(): number {\n return this.state.opacity;\n }\n set opacity(value: number) {\n this.state.opacity = value;\n }\n get blendMode(): string | undefined {\n return this.state.blendMode;\n }\n set blendMode(value: string | undefined) {\n this.state.blendMode = value;\n }\n\n translateBy(x: number, y: number): this {\n this.state.transform = multiply(this.state.transform, [1, 0, 0, 1, x, y]);\n return this;\n }\n scaleBy(x: number, y: number = x): this {\n this.state.transform = multiply(this.state.transform, [x, 0, 0, y, 0, 0]);\n return this;\n }\n /** Degrees, clockwise on screen. */\n rotate(degrees: number): this {\n const r = (degrees * Math.PI) / 180;\n this.state.transform = multiply(this.state.transform, [Math.cos(r), Math.sin(r), -Math.sin(r), Math.cos(r), 0, 0]);\n return this;\n }\n concatenate(matrix: Matrix): this {\n this.state.transform = multiply(this.state.transform, matrix);\n return this;\n }\n clip(to: Path): this {\n this.state.clips = [...this.state.clips, to.svg()];\n return this;\n }\n addFilter(filter: CanvasFilter): this {\n this.state.filters = [...this.state.filters, filter];\n return this;\n }\n\n /** `drawLayer { }`: draws with a copy of the state, restored after. */\n drawLayer(body: (context: GraphicsContext) => void): this {\n const saved = { ...this.state, clips: [...this.state.clips], filters: [...this.state.filters] };\n body(this);\n this.state = saved;\n return this;\n }\n\n fill(path: Path, with_: Shading, options: { eoFill?: boolean } = {}): this {\n this.push({ op: 'fill', path: path.svg(), shading: shading(with_), ...(options.eoFill ? { evenOdd: true } : {}) });\n return this;\n }\n\n stroke(path: Path, with_: Shading, options: StrokeOptions | number = {}): this {\n const o = typeof options === 'number' ? { lineWidth: options } : options;\n const command: CanvasCommand = { op: 'stroke', path: path.svg(), shading: shading(with_), lineWidth: o.lineWidth ?? 1 };\n if (o.lineCap) command.lineCap = o.lineCap;\n if (o.lineJoin) command.lineJoin = o.lineJoin;\n if (o.miterLimit !== undefined) command.miterLimit = o.miterLimit;\n if (o.dash) command.dash = o.dash;\n if (o.dashPhase !== undefined) command.dashPhase = o.dashPhase;\n this.push(command);\n return this;\n }\n\n /** `draw(Text(...), at:anchor:)` */\n drawText(text: string, at: Point, options: { anchor?: UnitPointValue; font?: FontValue; color?: StyleValue } = {}): this {\n const command: CanvasCommand = {\n op: 'text',\n text,\n x: at.x,\n y: at.y,\n anchor: unitPoint(options.anchor ?? 'center'),\n shading: shading(options.color ?? 'primary'),\n };\n if (options.font !== undefined) (command as { font?: Font }).font = font(options.font);\n this.push(command);\n return this;\n }\n\n /** `draw(Image(...), at:anchor:)` or `draw(_:in:)` with `size`. */\n drawImage(image: CanvasImage, at: Point, options: { anchor?: UnitPointValue; size?: { width: number; height: number }; color?: StyleValue } = {}): this {\n const props = 'url' in image ? { ...image, resizable: true } : 'name' in image ? { name: image.name, resizable: true } : image;\n const command = {\n op: 'image' as const,\n image: props,\n x: at.x,\n y: at.y,\n anchor: unitPoint(options.anchor ?? (options.size ? 'topLeading' : 'center')),\n ...(options.size ? { width: options.size.width, height: options.size.height } : {}),\n ...(options.color !== undefined ? { shading: shading(options.color) } : {}),\n };\n this.push(command as CanvasCommand);\n return this;\n }\n\n private push(command: CanvasCommand): void {\n const state: CanvasState = {};\n if (this.state.transform.some((v, i) => v !== IDENTITY[i])) state.transform = this.state.transform.map((v) => Math.round(v * 1e4) / 1e4) as Matrix;\n if (this.state.opacity !== 1) state.opacity = this.state.opacity;\n if (this.state.blendMode) state.blendMode = this.state.blendMode;\n if (this.state.clips.length) state.clips = [...this.state.clips];\n if (this.state.filters.length) state.filters = [...this.state.filters];\n this.commands.push({ ...state, ...command } as CanvasCommand);\n }\n}\n\nexport interface CanvasProps extends ViewModifiers {\n /** `Canvas { context, size in }` */\n renderer: (context: GraphicsContext, size: { width: number; height: number }) => void;\n /** `Canvas(renderer:symbols:)`: views the renderer draws by id (`resolveSymbol`, `drawSymbol`). */\n symbols?: Record<string, ReactNode>;\n}\n\nexport function Canvas(props: CanvasProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const [size, setSize] = useState<{ width: number; height: number } | null>(null);\n let canvas: ReactNode = null;\n let draws: SymbolDraw[] = [];\n if (size) {\n const context = new GraphicsContext(size);\n if (own.symbols) context.setSymbols(Object.keys(own.symbols));\n own.renderer(context, size);\n canvas = sb('canvas', { width: size.width, height: size.height, commands: context.commands });\n draws = context.symbolDraws;\n }\n const reader = sb(\n 'geometry',\n {},\n {\n geometry: (event) => {\n if (!size || size.width !== event.width || size.height !== event.height) setSize({ width: event.width, height: event.height });\n },\n },\n canvas,\n );\n if (!own.symbols) return applyModifiers(reader, modifiers);\n // The drawn symbols, each its view centered on the point it was drawn at.\n const symbols = draws.map((draw, index) => {\n let view: ReactNode = own.symbols![draw.id];\n if (draw.scale.x !== 1 || draw.scale.y !== 1) view = styled({ scale: draw.scale }, view);\n if (Math.abs(draw.rotation) > 1e-6) view = styled({ rotation: draw.rotation }, view);\n if (draw.opacity !== 1) view = styled({ opacity: draw.opacity }, view);\n return <Fragment key={index}>{styled({ position: { x: draw.x, y: draw.y } }, view)}</Fragment>;\n });\n return applyModifiers(\n sb('zstack', { alignment: 'topLeading' }, undefined, [<Fragment key=\"canvas\">{reader}</Fragment>, ...symbols]),\n modifiers,\n );\n}\n","/** `TimelineView`, and `VideoPlayer` and `AudioPlayer` with `useAVPlayer` and `AVQueuePlayer`. */\n\nimport type { RendererEvent } from '@swiftbrowser/web/src/protocol';\nimport { Fragment, useEffect, useRef, useState, useSyncExternalStore, type ReactNode } from 'react';\nimport { sb } from '../host/sb';\nimport { applyModifiers, splitProps, type ViewModifiers } from '../modifiers';\n\n// ---------------------------------------------------------------------------\n// TimelineView\n// ---------------------------------------------------------------------------\n\nexport type TimelineSchedule =\n | 'animation'\n | 'everyMinute'\n | { animation: { minimumInterval?: number; paused?: boolean } }\n | { periodic: { from?: Date; by: number } };\n\nexport interface TimelineViewProps {\n schedule: TimelineSchedule;\n children: (context: { date: Date }) => ReactNode;\n}\n\n/** `TimelineView(.periodic(from:by:)) { context in }`: the content renders again at each date of the schedule. */\nexport function TimelineView({ schedule, children }: TimelineViewProps): ReactNode {\n const [date, setDate] = useState(() => new Date());\n const key = typeof schedule === 'string' ? schedule : JSON.stringify(schedule);\n useEffect(() => {\n if (schedule === 'everyMinute') {\n let interval: ReturnType<typeof setInterval> | undefined;\n const timeout = setTimeout(() => {\n setDate(new Date());\n interval = setInterval(() => setDate(new Date()), 60_000);\n }, 60_000 - (Date.now() % 60_000));\n return () => {\n clearTimeout(timeout);\n if (interval) clearInterval(interval);\n };\n }\n if (typeof schedule === 'object' && 'periodic' in schedule) {\n const every = Math.max(schedule.periodic.by, 0.01) * 1000;\n const from = schedule.periodic.from?.getTime() ?? Date.now();\n // Aligned to the schedule's dates (from + k × interval).\n let timer: ReturnType<typeof setTimeout>;\n const tick = (): void => {\n const now = Date.now();\n const next = from + Math.ceil((now - from + 1) / every) * every;\n timer = setTimeout(() => {\n setDate(new Date(next));\n tick();\n }, Math.max(0, next - now));\n };\n tick();\n return () => clearTimeout(timer);\n }\n const options = typeof schedule === 'object' ? schedule.animation : {};\n if (options.paused) return;\n const minimum = (options.minimumInterval ?? 1 / 20) * 1000;\n let last = 0;\n let frame = 0;\n const loop = (time: number): void => {\n if (time - last >= minimum) {\n last = time;\n setDate(new Date());\n }\n frame = requestAnimationFrame(loop);\n };\n frame = requestAnimationFrame(loop);\n return () => cancelAnimationFrame(frame);\n // The schedule's identity is its JSON.\n }, [key]);\n return children({ date });\n}\n\n// ---------------------------------------------------------------------------\n// AVPlayer\n// ---------------------------------------------------------------------------\n\ntype VideoEvent = Extract<RendererEvent, { type: 'video' }>;\n\ninterface PlayerState {\n url: string | null;\n rate: number;\n muted: boolean;\n volume: number;\n loop: boolean;\n seek: { time: number; serial: number };\n duration: number | null;\n size: { width: number; height: number } | null;\n status: 'playing' | 'waiting' | 'paused';\n failed: string | null;\n}\n\nexport interface AVPlayerOptions {\n loop?: boolean;\n /**\n * `addPeriodicTimeObserver(forInterval:)`: how often, in seconds, the\n * position is reported while playing (`onTime`); four times a second\n * without it. A scrubber that moves with the sound asks for a frame\n * (`1 / 60`): the page reports once per animation frame, the native app\n * sixty times a second.\n */\n report?: number;\n}\n\n/**\n * `AVPlayer`: what plays, the rate, mute and volume, seeks. A view showing\n * it re-renders when those change; the position (`currentTime`, several\n * reports a second, or as often as `report` asks) re-renders nothing: read\n * it or listen with `onTime`.\n */\nexport class AVPlayer {\n protected state: PlayerState;\n private listeners = new Set<() => void>();\n private timeListeners = new Set<(time: number) => void>();\n private time = 0;\n private serial = 0;\n /** @internal The `report` interval for the views showing this player. */\n readonly report: number | undefined;\n\n constructor(url: string | null = null, options: AVPlayerOptions = {}) {\n this.report = options.report;\n this.state = {\n url,\n rate: 0,\n muted: false,\n volume: 1,\n loop: options.loop ?? false,\n seek: { time: 0, serial: 0 },\n duration: null,\n size: null,\n status: 'paused',\n failed: null,\n };\n }\n\n get url(): string | null {\n return this.state.url;\n }\n get rate(): number {\n return this.state.rate;\n }\n get isPlaying(): boolean {\n return this.state.rate > 0;\n }\n get isMuted(): boolean {\n return this.state.muted;\n }\n get volume(): number {\n return this.state.volume;\n }\n get duration(): number | null {\n return this.state.duration;\n }\n get presentationSize(): { width: number; height: number } | null {\n return this.state.size;\n }\n get timeControlStatus(): PlayerState['status'] {\n return this.state.status;\n }\n get error(): string | null {\n return this.state.failed;\n }\n get currentTime(): number {\n return this.time;\n }\n /** @internal */\n get snapshot(): PlayerState {\n return this.state;\n }\n\n play(): void {\n this.update({ rate: 1 });\n }\n pause(): void {\n this.update({ rate: 0 });\n }\n seek(time: number): void {\n this.time = time;\n this.update({ seek: { time, serial: ++this.serial } });\n }\n replaceCurrentItem(url: string | null): void {\n this.time = 0;\n this.update({ url, duration: null, size: null, failed: null, seek: { time: 0, serial: ++this.serial } });\n }\n set isMuted(muted: boolean) {\n this.update({ muted });\n }\n set volume(volume: number) {\n this.update({ volume: Math.min(1, Math.max(0, volume)) });\n }\n set rate(rate: number) {\n this.update({ rate });\n }\n set loop(loop: boolean) {\n this.update({ loop });\n }\n\n subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n };\n\n /** `addPeriodicTimeObserver`: told the position as the page reports it. */\n onTime(listener: (time: number) => void): () => void {\n this.timeListeners.add(listener);\n return () => this.timeListeners.delete(listener);\n }\n\n /** @internal The page's report for a view showing this player. */\n handle(event: VideoEvent): void {\n if (event.time !== undefined) {\n this.time = event.time;\n for (const listener of this.timeListeners) listener(event.time);\n }\n switch (event.event) {\n case 'ready':\n this.update({\n duration: event.duration ?? null,\n size: event.width && event.height ? { width: event.width, height: event.height } : this.state.size,\n });\n break;\n case 'status':\n if (event.status) this.update({ status: event.status });\n break;\n case 'play':\n if (this.state.rate === 0) this.update({ rate: 1 });\n break;\n case 'pause':\n if (this.state.rate !== 0) this.update({ rate: 0 });\n break;\n case 'volume':\n this.update({ muted: event.muted ?? this.state.muted, volume: event.volume ?? this.state.volume });\n break;\n case 'rate':\n if (event.rate !== undefined) this.update({ rate: event.rate });\n break;\n case 'ended':\n this.ended();\n break;\n case 'error':\n this.update({ failed: event.message ?? 'error', rate: 0 });\n break;\n default:\n break;\n }\n }\n\n /** The item played to its end: a looping player plays on, the others pause (`actionAtItemEnd: .pause`; a queue advances). */\n protected ended(): void {\n if (!this.state.loop) this.update({ rate: 0 });\n }\n\n protected update(changes: Partial<PlayerState>): void {\n this.state = { ...this.state, ...changes };\n for (const listener of this.listeners) listener();\n }\n}\n\n/**\n * `AVQueuePlayer`: a player with the items to play after the current one.\n * When the current item ends the next plays (`actionAtItemEnd: .advance`),\n * at the same rate; with none left the player pauses at the end. `items()`\n * is the current item and the rest; `insert` and `remove` edit the rest.\n */\nexport class AVQueuePlayer extends AVPlayer {\n private upcoming: string[] = [];\n\n constructor(urls: readonly string[] = [], options: AVPlayerOptions = {}) {\n super(urls[0] ?? null, options);\n this.upcoming = urls.slice(1);\n }\n\n /** The current item (if any) and the items after it. */\n items(): string[] {\n return this.url === null ? [...this.upcoming] : [this.url, ...this.upcoming];\n }\n\n /** Plays the next item, or ends with nothing (`currentItem` null, paused) when there is none. */\n advanceToNextItem(): void {\n const next = this.upcoming.shift();\n if (next === undefined) {\n this.replaceCurrentItem(null);\n this.update({ rate: 0 });\n return;\n }\n this.replaceCurrentItem(next);\n }\n\n /** Adds `url` after `after` (an item in the queue), or at the end; `after` null puts it first, as `insert(_:after: nil)` does. */\n insert(url: string, after: string | null = null): void {\n if (after === null) {\n this.upcoming.unshift(url);\n } else {\n const at = this.upcoming.indexOf(after);\n if (at === -1) this.upcoming.push(url);\n else this.upcoming.splice(at + 1, 0, url);\n }\n this.update({});\n }\n\n /** Removes a queued item, or the current one, which advances. */\n remove(url: string): void {\n if (url === this.url) {\n this.advanceToNextItem();\n return;\n }\n const at = this.upcoming.indexOf(url);\n if (at !== -1) this.upcoming.splice(at, 1);\n this.update({});\n }\n\n removeAllItems(): void {\n this.upcoming = [];\n this.replaceCurrentItem(null);\n this.update({ rate: 0 });\n }\n\n protected override ended(): void {\n if (this.state.loop) return;\n this.advanceToNextItem();\n }\n}\n\n/** A player kept for the component's life, re-rendering it when what it plays changes. */\nexport function useAVPlayer(url: string | null = null, options: AVPlayerOptions = {}): AVPlayer {\n const ref = useRef<AVPlayer | null>(null);\n ref.current ??= new AVPlayer(url, options);\n const player = ref.current;\n useSyncExternalStore(player.subscribe, () => player.snapshot, () => player.snapshot);\n useEffect(() => {\n if (player.url !== url) player.replaceCurrentItem(url);\n }, [player, url]);\n return player;\n}\n\nexport interface VideoPlayerProps extends ViewModifiers {\n player: AVPlayer | null;\n /** `videoGravity`: fit (default), fill, or stretch. */\n gravity?: 'resizeAspect' | 'resizeAspectFill' | 'resize';\n /** The browser's native controls; true by default, as `VideoPlayer` shows them. */\n controls?: boolean;\n /** `VideoPlayer(player:) { videoOverlay }`: drawn over the video. */\n videoOverlay?: ReactNode;\n}\n\n/** The `video` element showing `player` in `state` (docs/ops-protocol.md, \"Video and audio\"). */\nfunction videoElement(player: AVPlayer, state: PlayerState & { url: string }, options: { gravity: VideoPlayerProps['gravity']; controls: boolean }): ReactNode {\n return sb(\n 'video',\n {\n url: state.url,\n playing: state.rate > 0 && !state.failed,\n muted: state.muted,\n volume: state.volume,\n rate: state.rate > 0 ? state.rate : 1,\n loop: state.loop,\n gravity: options.gravity ?? 'resizeAspect',\n controls: options.controls,\n seek: state.seek,\n ...(player.report !== undefined && player.report > 0 ? { report: player.report } : {}),\n ...(state.size ? { width: state.size.width, height: state.size.height } : {}),\n },\n { video: (event) => player.handle(event) },\n );\n}\n\n/** `VideoPlayer(player:)`: the page's `<video>` showing the player, or black without one. */\nexport function VideoPlayer(props: VideoPlayerProps): ReactNode {\n const { own, modifiers } = splitProps(props);\n const player = own.player;\n const state = useSyncExternalStore(\n player?.subscribe ?? NO_SUBSCRIBE,\n () => player?.snapshot ?? null,\n () => player?.snapshot ?? null,\n );\n if (!player || !state || !state.url) return applyModifiers(sb('color', { color: { r: 0, g: 0, b: 0, a: 1 } }), modifiers);\n const video = videoElement(player, { ...state, url: state.url }, { gravity: own.gravity, controls: own.controls ?? true });\n if (own.videoOverlay === undefined) return applyModifiers(video, modifiers);\n return applyModifiers(\n sb('zstack', { alignment: 'center' }, undefined, [<Fragment key=\"video\">{video}</Fragment>, <Fragment key=\"overlay\">{own.videoOverlay}</Fragment>]),\n modifiers,\n );\n}\n\nconst NO_SUBSCRIBE = (): (() => void) => () => {};\n\n/**\n * A player that plays with no view: the element at no size and out of the\n * way of taps, so an audio player (a playlist, a podcast)\n * keeps playing wherever the app's screens go. Put one anywhere in the\n * tree that stays mounted (the root), since a player shown by no\n * `VideoPlayer` or `AudioPlayer` plays nothing. iOS plays a player's sound\n * with no layer the same way.\n */\nexport function AudioPlayer({ player }: { player: AVPlayer | null }): ReactNode {\n const state = useSyncExternalStore(\n player?.subscribe ?? NO_SUBSCRIBE,\n () => player?.snapshot ?? null,\n () => player?.snapshot ?? null,\n );\n if (!player || !state || !state.url) return null;\n return applyModifiers(videoElement(player, { ...state, url: state.url }, { gravity: 'resizeAspect', controls: false }), [\n ['frame', { width: 0, height: 0 }],\n ['clipped', true],\n ['opacity', 0],\n ['allowsHitTesting', false],\n ]);\n}\n","/**\n * `PhaseAnimator` and `KeyframeAnimator`. A phase animator moves its content\n * through phases, each change in one animated pass that the renderer tweens\n * (as the shim does); a keyframe animator computes its values frame by frame\n * along tracks of keyframes and renders them, as SwiftUI evaluates its\n * content per frame.\n */\n\nimport type { Animation } from '@swiftbrowser/web/src/protocol';\nimport { timingFor } from '@swiftbrowser/web/src/animation';\nimport { useEffect, useRef, useState, type ReactNode } from 'react';\nimport { withAnimation } from '../host/root';\n\n// ---------------------------------------------------------------------------\n// PhaseAnimator\n// ---------------------------------------------------------------------------\n\nexport interface PhaseAnimatorProps<Phase> {\n phases: readonly Phase[];\n /** Each change runs through the phases once, back to the first; without one the phases cycle while shown. */\n trigger?: unknown;\n /** The animation into a phase (`default` by default). */\n animation?: (phase: Phase) => Animation;\n children: (phase: Phase) => ReactNode;\n}\n\nexport function PhaseAnimator<Phase>({ phases, trigger, animation, children }: PhaseAnimatorProps<Phase>): ReactNode {\n const [index, setIndex] = useState(0);\n const hasTrigger = trigger !== undefined;\n const latest = useRef({ phases, animation });\n latest.current = { phases, animation };\n const first = useRef(true);\n\n useEffect(() => {\n if (hasTrigger && first.current) {\n first.current = false;\n return;\n }\n first.current = false;\n let cancelled = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let step = 0;\n const count = latest.current.phases.length;\n if (count < 2) return;\n const advance = (): void => {\n if (cancelled) return;\n step += 1;\n const next = step % count;\n const { phases: current, animation: animationFor } = latest.current;\n const into = animationFor?.(current[next] as Phase) ?? { type: 'default' };\n withAnimation(into, () => setIndex(next));\n // A trigger runs through the phases once, ending on the first.\n if (hasTrigger && next === 0) return;\n const timing = timingFor(into);\n timer = setTimeout(advance, timing.duration + timing.delay);\n };\n // The first phase holds for a moment before the cycle starts, as the first change waits for a render.\n timer = setTimeout(advance, 0);\n return () => {\n cancelled = true;\n if (timer) clearTimeout(timer);\n };\n }, [hasTrigger, trigger]);\n\n return children(phases[index % Math.max(phases.length, 1)] as Phase);\n}\n\n// ---------------------------------------------------------------------------\n// KeyframeAnimator\n// ---------------------------------------------------------------------------\n\nexport type KeyframeCurve = 'linear' | 'cubic' | 'spring' | 'move';\n\n/** One keyframe of a track: the value it reaches, in how long (seconds), along which curve. */\nexport interface Keyframe {\n to: number;\n duration: number;\n curve?: KeyframeCurve;\n}\n\nexport type KeyframeTracks<Value extends Record<string, number>> = { [K in keyof Value]?: readonly Keyframe[] };\n\nexport interface KeyframeAnimatorProps<Value extends Record<string, number>> {\n initialValue: Value;\n keyframes: KeyframeTracks<Value>;\n /** Each change plays the keyframes once; without one they repeat while shown (`repeating`). */\n trigger?: unknown;\n repeating?: boolean;\n children: (value: Value) => ReactNode;\n}\n\nfunction ease(curve: KeyframeCurve, t: number): number {\n switch (curve) {\n case 'move':\n return 1;\n case 'cubic':\n return t * t * (3 - 2 * t);\n case 'spring': {\n // A critically damped spring that settles within the keyframe.\n const omega = 7;\n return 1 - (1 + omega * t) * Math.exp(-omega * t);\n }\n default:\n return t;\n }\n}\n\n/** The tracks' values `elapsed` seconds in (each track from the initial value through its keyframes). */\nexport function keyframeValues<Value extends Record<string, number>>(initial: Value, tracks: KeyframeTracks<Value>, elapsed: number): Value {\n const value: Record<string, number> = { ...initial };\n for (const key of Object.keys(tracks) as (keyof Value & string)[]) {\n const frames = tracks[key] ?? [];\n let from = initial[key] as number;\n let start = 0;\n let current: number = from;\n for (const frame of frames) {\n const end = start + frame.duration;\n if (elapsed >= end) {\n current = frame.to;\n } else {\n const t = frame.duration > 0 ? Math.max(0, (elapsed - start) / frame.duration) : 1;\n current = from + (frame.to - from) * ease(frame.curve ?? 'spring', t);\n break;\n }\n from = frame.to;\n start = end;\n }\n value[key] = current;\n }\n return value as Value;\n}\n\nfunction totalDuration(tracks: Record<string, readonly Keyframe[] | undefined>): number {\n return Math.max(0, ...Object.values(tracks).map((frames) => (frames ?? []).reduce((sum, frame) => sum + frame.duration, 0)));\n}\n\nexport function KeyframeAnimator<Value extends Record<string, number>>({\n initialValue,\n keyframes,\n trigger,\n repeating,\n children,\n}: KeyframeAnimatorProps<Value>): ReactNode {\n const [value, setValue] = useState<Value>(initialValue);\n const latest = useRef({ initialValue, keyframes });\n latest.current = { initialValue, keyframes };\n const first = useRef(true);\n const hasTrigger = trigger !== undefined;\n\n useEffect(() => {\n if (hasTrigger && first.current) {\n first.current = false;\n return;\n }\n first.current = false;\n if (!hasTrigger && !repeating) return;\n let frame = 0;\n let start: number | null = null;\n const tick = (now: number): void => {\n start ??= now;\n const { initialValue: initial, keyframes: tracks } = latest.current;\n const total = totalDuration(tracks as Record<string, readonly Keyframe[] | undefined>);\n let elapsed = (now - start) / 1000;\n if (!hasTrigger && repeating && total > 0) elapsed %= total;\n setValue(keyframeValues(initial, tracks, elapsed));\n if (hasTrigger && elapsed >= total) return;\n frame = requestAnimationFrame(tick);\n };\n frame = requestAnimationFrame(tick);\n return () => cancelAnimationFrame(frame);\n }, [hasTrigger, trigger, repeating]);\n\n return children(value);\n}\n"],"names":["r","detach","notify","keyOf","document","stops","wrap","runFont","Image","imageProps","plain","Fragment","clear","active","frame","size","round","IDENTITY","opacity","command","perform","font","fontOf","width","insets","host","exports","nextId","hostNow","roots","height","clamp","watching","value","placeholder","stride","styleOf","row","every"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAwDO,MAAM,yBAAyB,cAA+B,EAAE;AAEhE,SAAS,qBAAsC;AACpD,SAAO,WAAW,sBAAsB;AAC1C;AAGO,SAAS,gBAAgB,QAAyB,UAAgC;AACvF,SAAO,cAAc,qBAAqB,EAAE,OAAA,GAAU,QAAQ;AAChE;AAEA,SAAS,oBAAoB,EAAE,QAAQ,YAA0E;AAC/G,QAAM,SAAS,WAAW,sBAAsB;AAChD,SAAO,cAAc,uBAAuB,UAAU,EAAE,OAAO,EAAE,GAAG,QAAQ,GAAG,SAAO,GAAK,QAAQ;AACr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