Skip to main content

day_toolkit_dom/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-toolkit-dom — the `web-dom` backend (DESIGN.md §9): the DOM is the toolkit. A `<button>` is
5//! the web's native button, `<input type="range">` its slider, `<dialog>` its modal surface —
6//! semantic HTML plus ARIA, never a canvas-painted imitation (§0.3).
7//!
8//! Architecture: the same trampoline shape as day-toolkit-arkui, with JavaScript in place of C. A
9//! small shim owns every real DOM call, keyed by numeric element ids; Rust passes ids and
10//! UTF-8 (ptr, len) pairs across plain `extern "C"` imports, and the shim calls back through
11//! a handful of exports (`day_dom_event`, `day_dom_posted`, …). No wasm-bindgen, no bundler:
12//! the host page is a plain ES module that instantiates the wasm.
13//!
14//! **The shim lives in `crates/day-cli/resources/web/`** (`shim.js`, `index.html`, `day.css`),
15//! not here: `day-cli` embeds the trio with `include_str!` so an installed CLI serves a
16//! self-contained `dist/`, and `include_str!` may not reach outside its own package. Every
17//! `extern "C"` import below has its implementation there — change one, change both, and
18//! rebuild the CLI for the edit to reach a served page.
19//!
20//! Layout stays day-core-owned: `set_frame` writes absolute positions, exactly like the Qt
21//! and ArkUI backends. The exceptions are nav/tab pages, whose panes are CSS-managed and
22//! report their size back through a `ResizeObserver` (`Event::FrameChanged`) — the `DayNavPage`
23//! contract (docs/navigation.md).
24#![cfg(target_arch = "wasm32")]
25
26mod controls;
27
28mod transfer;
29
30use std::cell::{Cell, RefCell};
31use std::collections::{BTreeSet, HashMap, VecDeque};
32
33use day_spec::props::*;
34use day_spec::{
35    A11yProps, AnimSpec, Builtin, Cap, Cursor, Curve, DrawOp, Event, EventSink, Font, FontSpec,
36    FontWeight, GestureKind, Lifecycle, ListSource, MenuItem, NodeId, Paint, PieceKind, Platform,
37    Point, Proposal, Rect, Registry, Renderer, Shape, Size, Support, Toolkit, Transform,
38    WindowOptions, kinds,
39    present::{PresentButton, PresentResult, PresentSpec},
40};
41
42// ---------------------------------------------------------------------------
43// Shim imports: every real DOM call. `el` values are shim-side element ids.
44// The attribute makes these wasm imports from the instantiation's `env` object
45// (shim.js supplies them) rather than link-time-resolved symbols.
46// ---------------------------------------------------------------------------
47
48#[link(wasm_import_module = "env")]
49unsafe extern "C" {
50    fn day_dom_create(kind: u32) -> u32;
51    /// Create an element by TAG NAME — the escape hatch piece renderers build on, since day-toolkit-dom's
52    /// own `EL_*` kind codes only cover the built-in vocabulary.
53    fn day_dom_create_tag(tag: *const u8, tag_len: usize) -> u32;
54    /// Invoke a zero-argument method on an element (`play`, `pause`, `load`, …).
55    fn day_dom_call(el: u32, method: *const u8, method_len: usize);
56    /// Replace an element's markup, keeping the caret (docs/texteditor.md). The HTML comes from
57    /// Day's own serializer, which escapes every character of app text.
58    fn day_dom_set_html(el: u32, html: *const u8, html_len: usize);
59    /// Put the selection at a BYTE range in a contenteditable element's flattened text.
60    fn day_dom_editor_select(el: u32, start: u32, end: u32);
61    /// Insert text at a BYTE offset of a contenteditable element's flattened text through the
62    /// browser's editing command, so undo records it and the `input` event reports it.
63    fn day_dom_editor_insert(el: u32, at: u32, text: *const u8, text_len: usize);
64    fn day_dom_set_app_badge(count: i32);
65    /// Enter (`on` = 1) or leave (0) fullscreen through the Fullscreen API on the document
66    /// element (docs/windows.md "Window properties"). Returns -1 when a request is in flight,
67    /// whose outcome comes back through `day_dom_window_state`; otherwise nothing was asked of
68    /// the browser (no Fullscreen API, or already in that state) and the answer is the state the
69    /// page is in, as a `WindowState` code.
70    fn day_dom_set_fullscreen(on: u32) -> i32;
71    /// The primary window's chrome, once at boot (docs/window-chrome.md): `overlay` 1 runs the
72    /// content under an installed app's window-controls overlay, answers its height now (0 while
73    /// hidden) and reports every later change through `day_dom_titlebar_inset`; 0 keeps the
74    /// content below it. Also installs the drag-region rules `set_drag_region`'s class relies on.
75    fn day_dom_window_chrome(overlay: u32) -> f64;
76    /// The browser window's outer frame (`screenX`, `screenY`, `outerWidth`, `outerHeight`) into
77    /// `out[0..4]`, in CSS px on the desktop. Returns 0 when the browser reports no frame.
78    fn day_dom_window_frame(out: *mut f64) -> u32;
79    /// The screen the page is on into `out[0..9]`: its frame (`screen.left`/`top`, else 0, then
80    /// `width`, `height`), its work area (`availLeft`/`availTop`, else the frame's origin, then
81    /// `availWidth`, `availHeight`), and `devicePixelRatio`.
82    fn day_dom_screen(out: *mut f64);
83    /// Speak `text` through the shim's ARIA live regions (docs/accessibility.md); `urgent`
84    /// picks the assertive one, which interrupts, over the polite one, which queues.
85    fn day_dom_announce(ptr: *const u8, len: usize, urgent: u32);
86    fn day_dom_insert(parent: u32, child: u32, index: u32);
87    fn day_dom_remove(child: u32);
88    fn day_dom_release(el: u32);
89    fn day_dom_set_frame(el: u32, x: f64, y: f64, w: f64, h: f64);
90    fn day_dom_set_text(el: u32, ptr: *const u8, len: usize);
91    fn day_dom_set_style(el: u32, p: *const u8, pl: usize, v: *const u8, vl: usize);
92    fn day_dom_set_attr(el: u32, a: *const u8, al: usize, v: *const u8, vl: usize);
93    fn day_dom_set_class(el: u32, ptr: *const u8, len: usize, on: u32);
94    /// Wire a run anchor's click to `owner`'s node (docs/text-runs.md): the spans are not nodes,
95    /// so the LABEL element is what the event reports against.
96    fn day_dom_link(el: u32, owner: u32, p: *const u8, l: usize);
97    fn day_dom_set_value(el: u32, v: f64);
98    fn day_dom_set_checked(el: u32, on: u32);
99    /// Select characters (Unicode scalar values) `start..end` of a text field's `<input>`,
100    /// held to its value, caret at `end` (docs/textfield.md "Selection").
101    fn day_dom_field_select(el: u32, start: u32, end: u32);
102    /// Text entry traits on a text field's `<input>` (docs/textfield.md): `json` is one object
103    /// of attribute name to value, where an empty value removes the attribute and `type` is
104    /// assigned as the property, keeping the caret. Any other element is left alone.
105    fn day_dom_input_traits(el: u32, json: *const u8, len: usize);
106    /// Attach shim listeners; `mask` bits: 1 click, 2 input, 4 change, 8 focus, 16 submit,
107    /// 32 resize-observer, 64 scroll, 128 pointer-tap, 256 pointer-drag, 512 contenteditable.
108    fn day_dom_listen(el: u32, mask: u32);
109    /// Set an animatable property (0 opacity, 1 transform, 2 background, 3 frame) to the
110    /// numbers at `to`, animated over one cycle of `samples` (`[offset, progress]` pairs) when
111    /// `duration_ms` is positive; `iterations` -1 for ever (docs/tween.md).
112    fn day_dom_animate(
113        el: u32,
114        prop: u32,
115        to: *const f64,
116        to_len: usize,
117        samples: *const f64,
118        samples_len: usize,
119        duration_ms: f64,
120        delay_ms: f64,
121        iterations: f64,
122        alternate: u32,
123    );
124    /// What `el` displays now: `[opacity, x, y, w, h, tx, ty, r, g, b, a]` into `out`; returns 1
125    /// when it shows a background color of its own.
126    fn day_dom_displayed(el: u32, out: *mut f64) -> u32;
127    /// A scroll view's preferences: `flags` bit 0 hidden indicators, bit 1 no bounce, bit 2
128    /// phase reports; `snap` 0 none, 1 page, 2 every `interval` points.
129    fn day_dom_scroll_setup(el: u32, flags: u32, snap: u32, interval: f64);
130    /// `navigator.maxTouchPoints`.
131    fn day_dom_touch_points() -> u32;
132    /// Measure a label element in its own computed style (font, letter spacing, line height,
133    /// line clamp, wrapping): its own content when `text_len` is 0, else `text` in its place.
134    /// `max_w` caps the width (a huge value for none); `out` receives `[width, height]`.
135    fn day_dom_measure_label(el: u32, text: *const u8, text_len: usize, max_w: f64, out: *mut f64);
136    /// The browser's default font size against the one Day's ramp is drawn for (docs/text.md
137    /// "Text size").
138    fn day_dom_text_scale() -> f64;
139    /// Grow `el`'s pointer hit area by the four insets, in PHYSICAL sides (top, left, bottom,
140    /// right); zeros restore its bounds (docs/gestures.md "Hit slop").
141    fn day_dom_hit_slop(el: u32, top: f64, left: f64, bottom: f64, right: f64);
142    /// The axis `el`'s drag follows: 0 any, 1 horizontal, 2 vertical.
143    fn day_dom_drag_axis(el: u32, axis: u32);
144    /// One disabled group around `el` more (`on` 0) or fewer (`on` 1).
145    fn day_dom_subtree_enabled(el: u32, on: u32);
146    /// The kind of pointer last used: 0 touch, 1 mouse, 2 stylus.
147    fn day_dom_pointer_kind() -> u32;
148    /// Make a pass-through element a pointer target (docs/gestures.md "Pass-through").
149    fn day_dom_takes_pointer(el: u32);
150    fn day_dom_measure_text(
151        t: *const u8,
152        tl: usize,
153        f: *const u8,
154        fl: usize,
155        max_w: f64,
156        out: *mut f64,
157    );
158    fn day_dom_width(el: u32) -> f64;
159    /// First text baseline from the element's top for a box `box_h` tall; `-1` ⇒ no text
160    /// (docs/baseline.md).
161    fn day_dom_baseline(el: u32, box_h: f64) -> f64;
162    fn day_dom_scroll_to(el: u32, x: f64, y: f64, animated: u32);
163    fn day_dom_scroll_edge(el: u32, edge: u32, animated: u32);
164    /// Arm the shim's pointer-drag reorder on a list host (docs/list.md): the drag calls back
165    /// into `day_dom_list_can_move`/`day_dom_list_move` synchronously.
166    fn day_dom_list_reorder(el: u32);
167    fn day_dom_scroll_offset(el: u32, out: *mut f64);
168    /// The emulated list's scrolled offset and visible height — which rows have to exist.
169    fn day_dom_list_viewport(el: u32, out: *mut f64);
170    /// 1 while the list's own smooth scroll is still moving toward where Day sent it; one that
171    /// has not moved for half a second no longer counts (`Toolkit::ui_idle`).
172    fn day_dom_list_gliding(el: u32) -> u32;
173    /// Report this list's scrolling into `day_dom_list_scrolled`, so rows coming into view build,
174    /// and the scrolls the reader starts into `day_dom_list_reader`.
175    fn day_dom_list_on_scroll(el: u32);
176    /// Give the emulated list a tab stop, the listbox role, and the arrow/Home/End route back
177    /// into `day_dom_list_key` (docs/list.md). A browser has no native list to inherit keyboard
178    /// selection from, so the one the app sees is the one this builds.
179    fn day_dom_list_keynav(el: u32, multi: u32);
180    /// Give a canvas a tab stop, focus-on-press, and the arrow route back into
181    /// `day_dom_canvas_key` (docs/menus.md) — the web half of "keys follow focus".
182    fn day_dom_canvas_keynav(el: u32);
183    fn day_dom_scroll_content(el: u32, w: f64, h: f64);
184    fn day_dom_focus(el: u32, focused: u32);
185    fn day_dom_canvas_replay(
186        el: u32,
187        ops: *const f64,
188        ops_len: usize,
189        strs: *const u8,
190        strs_len: usize,
191        w: f64,
192        h: f64,
193    );
194    // Raster images from bytes (docs/images.md). A browser decodes AND encodes asynchronously —
195    // the only backend here where that is true — so neither call answers; the shim calls the
196    // exported `day_dom_image_decoded` / `day_dom_image_encoded` when it resolves. Ids ride as
197    // `f64`: a wasm `i64` reaches JS as a `BigInt`, and an f64 carries a minted id exactly well
198    // past any count a page can reach.
199    fn day_dom_image_decode(req: u32, id: f64, ptr: *const u8, len: usize);
200    fn day_dom_image_encode(
201        req: u32,
202        id: f64,
203        fmt: *const u8,
204        fmt_len: usize,
205        quality: f64,
206        fit_w: f64,
207        fit_h: f64,
208    );
209    fn day_dom_image_release(id: f64);
210    /// Paint `ops` into a detached `pw` × `ph` pixel canvas scaled by `scale`, and keep the
211    /// result under `id` beside the decoded bitmaps (docs/canvas.md "Exporting"). The shim
212    /// answers through the exported `day_dom_bitmap_rendered` once `createImageBitmap` resolves.
213    fn day_dom_canvas_render_bitmap(
214        req: u32,
215        id: f64,
216        ops: *const f64,
217        ops_len: usize,
218        strs: *const u8,
219        strs_len: usize,
220        pw: f64,
221        ph: f64,
222        scale: f64,
223    );
224    /// Whether the engine writes this MIME type — `toBlob` would otherwise substitute PNG.
225    fn day_dom_image_can_encode(fmt: *const u8, fmt_len: usize) -> u32;
226    /// Point a realized `<img>` at a decoded bitmap's object URL.
227    fn day_dom_image_set_bitmap(el: u32, id: f64);
228    /// Point a realized `<img>` at raw encoded bytes, through a blob URL the shim owns.
229    fn day_dom_image_set_bytes(el: u32, ptr: *const u8, len: usize);
230    /// Revoke the blob URL an element made, when the element goes.
231    fn day_dom_image_revoke(el: u32);
232    /// Turn an image element's mask on or off for a source whose URL the shim owns (bytes, a
233    /// decoded bitmap): on, the mask is cut from that URL now and again at each source swap.
234    fn day_dom_image_mask(el: u32, on: u32);
235    fn day_dom_present(req: u32, json: *const u8, len: usize);
236    /// The modifier keys held right now, as the shim last observed them (bit0 shift,
237    /// bit1 primary = meta|ctrl, bit2 alt).
238    fn day_dom_modifiers() -> u32;
239    fn day_dom_prepare_snapshot(host: u32, revision: u32) -> u32;
240    /// Present a save flow: `json` names it, `bytes` are the staged content the shim turns
241    /// into a download (docs/files.md).
242    fn day_dom_present_save(req: u32, json: *const u8, len: usize, bytes: *const u8, blen: usize);
243    fn day_dom_dismiss(req: u32);
244    /// `mode` is [`nav_mode`]: 0 split, 1 stack, 2 tabs, 3 rail.
245    fn day_dom_nav_mode(el: u32, mode: u32, title: *const u8, tl: usize);
246    /// Rebuild a live host's chrome for another presentation, detaching its pages (which stay
247    /// alive in the shim's registry) for Day to re-home.
248    fn day_dom_nav_present(el: u32, mode: u32);
249    /// `chrome` puts the page in the sidebar / tab-bar / rail slot rather than the detail area.
250    fn day_dom_nav_add_page(nav: u32, page: u32, chrome: u32);
251    fn day_dom_nav_back_bar(nav: u32, visible: u32, t: *const u8, tl: usize);
252    fn day_dom_navmenu(el: u32, json: *const u8, len: usize);
253    fn day_dom_navmenu_rows(el: u32, json: *const u8, len: usize);
254    // Window toolbar (docs/toolbars.md): each edit crosses as one JSON list of ops, and targeted
255    // patches address an item by id. `day_dom_toolbar_sidebar` returns 0 when the page has no
256    // split nav to toggle.
257    // `host` is the window root the edit belongs to: a cover element gets a strip of its own
258    // over the cover (docs/cover.md), anything else addresses the page's strip.
259    fn day_dom_toolbar_edit(host: u32, json: *const u8, len: usize);
260    fn day_dom_toolbar_patch(host: u32, json: *const u8, len: usize);
261    fn day_dom_toolbar_height(host: u32) -> f64;
262    fn day_dom_toolbar_sidebar() -> u32;
263    // The emulated app menu (docs/menus.md): the model crosses as one JSON document and the
264    // shim docks a trailing menu button on the toolbar strip; an empty item list removes it.
265    fn day_dom_app_menu(json: *const u8, len: usize);
266    /// Open (or, pressed again, close) a menu button's menu under the button `el` (docs/menus.md
267    /// "Menu buttons"): `json` is the item list a toolbar pull-down takes, shown by the same
268    /// popover.
269    fn day_dom_button_menu(el: u32, json: *const u8, len: usize);
270    fn day_dom_navmenu_select(el: u32, idx: i32);
271    fn day_dom_options(el: u32, json: *const u8, len: usize);
272    fn day_dom_options_select(el: u32, idx: u32);
273    fn day_dom_schedule_post();
274    fn day_dom_schedule_delayed(token: u32, ms: u32);
275    fn day_dom_request_frame(token: f64) -> u32;
276    fn day_dom_cancel_frame(id: u32);
277    fn day_dom_set_title(ptr: *const u8, len: usize);
278    fn day_dom_open_url(ptr: *const u8, len: usize);
279    fn day_dom_share_support() -> bool;
280    fn day_dom_share_url(ptr: *const u8, len: usize, title: *const u8, title_len: usize) -> bool;
281    /// Mirror the app route into the URL hash. `replace` = rewrite the current history entry
282    /// (the launch reflection) instead of pushing a new one (in-app navigation).
283    fn day_dom_set_hash(ptr: *const u8, len: usize, replace: u32);
284    /// One dayscript reply line out to the page's WebSocket (docs/web.md; the shim queues
285    /// until the socket is open and drops the line when scripting is not armed).
286    fn day_dom_script_send(ptr: *const u8, len: usize);
287    fn day_dom_env(key: *const u8, kl: usize, out: *mut u8, cap: usize) -> usize;
288    /// An element read back for `read_native`, by the `day_dom_env` buffer protocol: its
289    /// `role`, `aria-label`, value (`aria-valuetext`, else the description) and `id`, then
290    /// number, checked, enabled, visible, the frame's x, y, w, h, and last the displayed text
291    /// (`=`-prefixed), joined by U+001F; an empty field is one the element does not have.
292    /// Empty when the element is gone.
293    fn day_dom_read_native(el: u32, out: *mut u8, cap: usize) -> usize;
294    /// The page's font list in Day's list text (docs/fonts.md) — the CSS generic families plus
295    /// the bundled `document.fonts` faces — by the `day_dom_env` buffer protocol.
296    fn day_dom_fonts(out: *mut u8, cap: usize) -> usize;
297    /// Measure one line of canvas text with the CSS font the canvas replay draws it in;
298    /// `out` receives the eight f64 `TextMetrics::from_slots` reads — width, the line box, the
299    /// ascent, the cap height, then the ink box (docs/fonts.md).
300    fn day_dom_canvas_measure_text(
301        text: *const u8,
302        len: usize,
303        size: f64,
304        weight: u32,
305        italic: u32,
306        fam: *const u8,
307        fam_len: usize,
308        out: *mut f64,
309    );
310    /// Apply an appearance override on the page: 0 light, 1 dark, 2 follow the browser's
311    /// `prefers-color-scheme`. Returns the effective mode (0/1) after applying.
312    fn day_dom_set_dark(mode: u32) -> u32;
313    fn day_dom_warn(ptr: *const u8, len: usize);
314    /// One log line to the browser console (docs/logging.md), at `log`'s level ordering —
315    /// 1 Error … 5 Trace — so it lands on the matching `console.*` method and the devtools level
316    /// filter applies to Day's output too.
317    fn day_dom_log(level: u32, ptr: *const u8, len: usize);
318    /// The page's wall clock (`Date.now()`), in milliseconds since the Unix epoch. This is the
319    /// only wall clock on `wasm32-unknown-unknown` — `std::time::SystemTime::now()` aborts there.
320    fn day_dom_now_ms() -> f64;
321    /// `performance.now()`: milliseconds on the page's monotonic clock.
322    fn day_dom_perf_now() -> f64;
323    /// Fill `len` bytes at `ptr` with browser entropy (`crypto.getRandomValues`) — the
324    /// getrandom bridge below answers the crate's custom-backend hook with it.
325    fn day_dom_entropy(ptr: *mut u8, len: usize);
326}
327
328/// getrandom v0.3's custom-backend hook (its `custom.rs` contract): `day build` compiles every
329/// web app with `--cfg getrandom_backend="custom"`, so any crate in the graph that asks
330/// getrandom for entropy (uuid, rand, …) lands here instead of failing to compile — the
331/// raw-wasm pipeline carries no wasm-bindgen runtime for getrandom's own `wasm_js` backend.
332#[unsafe(no_mangle)]
333#[expect(
334    clippy::unnecessary_wraps,
335    reason = "getrandom's custom-backend contract fixes this signature"
336)]
337unsafe extern "Rust" fn __getrandom_v03_custom(
338    dest: *mut u8,
339    len: usize,
340) -> Result<(), getrandom::Error> {
341    // SAFETY: getrandom hands us a valid, writable buffer of exactly `len` bytes; the shim
342    // writes that many and no more.
343    unsafe { day_dom_entropy(dest, len) };
344    Ok(())
345}
346
347fn s(el: u32, prop: &str, val: &str) {
348    unsafe { day_dom_set_style(el, prop.as_ptr(), prop.len(), val.as_ptr(), val.len()) };
349}
350fn attr(el: u32, a: &str, v: &str) {
351    unsafe { day_dom_set_attr(el, a.as_ptr(), a.len(), v.as_ptr(), v.len()) };
352}
353fn text(el: u32, t: &str) {
354    unsafe { day_dom_set_text(el, t.as_ptr(), t.len()) };
355}
356/// The number an accessibility value leads with ("72%" → 72, "3 of 5" → 3), for
357/// `aria-valuenow`; `None` when the text starts with something else.
358fn leading_number(value: &str) -> Option<f64> {
359    let value = value.trim_start();
360    let end = value
361        .char_indices()
362        .find(|(i, c)| !(c.is_ascii_digit() || *c == '.' || (*i == 0 && (*c == '-' || *c == '+'))))
363        .map_or(value.len(), |(i, _)| i);
364    value[..end].parse().ok()
365}
366fn apply_button_content(el: u32, title: &str, icon: Option<&day_spec::Icon>, icon_only: bool) {
367    fn escape(s: &str) -> String {
368        s.replace('&', "&amp;")
369            .replace('<', "&lt;")
370            .replace('>', "&gt;")
371            .replace('"', "&quot;")
372            .replace('\'', "&#39;")
373    }
374    let url = match icon {
375        Some(day_spec::Icon::Symbol(s)) => symbol_svg(*s),
376        Some(day_spec::Icon::Image(name)) => Some(image_url(name)),
377        None => None,
378    };
379    // The title is the accessible name (an icon-only button shows none), unless the app named
380    // the button itself (`set_a11y`); overwriting that replaced app labels on every title change.
381    if !APP_NAMED.with(|t| t.contains(el as usize)) {
382        attr(el, "aria-label", title);
383    }
384    attr(
385        el,
386        "title",
387        if icon_only && url.is_some() {
388            title
389        } else {
390            ""
391        },
392    );
393    let html = match url {
394        Some(url) => format!(
395            "<span aria-hidden=\"true\" style=\"display:inline-block;width:20px;height:20px;vertical-align:middle;background:currentColor;mask:url('{}') center/contain no-repeat\"></span>{}",
396            escape(&url.replace('\'', "%27").replace('"', "%22")),
397            if icon_only {
398                String::new()
399            } else {
400                format!(" <span>{}</span>", escape(title))
401            }
402        ),
403        None => escape(title),
404    };
405    unsafe { day_dom_set_html(el, html.as_ptr(), html.len()) };
406}
407
408/// Put a [`ButtonStyleSpec`] on a `<button>`, keeping it a `<button>`.
409///
410/// A tint sets two CSS custom properties and adds `.tinted`; day.css does the rest, including
411/// the `:hover`/`:active`/`:disabled` rules every `.day-btn` already has. Painting the colors
412/// through variables rather than inline `background` is what lets those state rules keep
413/// working — an inline background would win over them.
414/// `ButtonProps::selected`: `aria-pressed` is the state a screen reader reads, and the class is
415/// what day.css draws (the accent fill a chosen item gets); the element stays a `<button>`.
416fn set_button_selected(el: u32, on: bool) {
417    attr(el, "aria-pressed", if on { "true" } else { "false" });
418    class(el, "selected", on);
419}
420
421fn apply_button_style(el: u32, style: ButtonStyleSpec) {
422    // Clear the others first, so a patch between styles cannot leave two classes on.
423    class(el, "prominent", false);
424    class(el, "bordered", false);
425    class(el, "tinted", false);
426    class(el, "compact", false);
427    match style {
428        ButtonStyleSpec::Prominent => class(el, "prominent", true),
429        ButtonStyleSpec::Bordered => class(el, "bordered", true),
430        ButtonStyleSpec::Compact => class(el, "compact", true),
431        ButtonStyleSpec::Tinted(c) => {
432            let opaque = |x: day_spec::Color| day_spec::Color { a: 1.0, ..x };
433            // The tint follows the appearance through CSS; the readable title color is
434            // decided per side, from the tint each appearance shows.
435            let (light, dark) = day_spec::Palette::both();
436            let (on_light, on_dark) = c.pair(&light, &dark);
437            let fill = match c {
438                day_spec::Ink::Fixed(x) => color_css(opaque(x)),
439                day_spec::Ink::Adaptive { light, dark } => pair_css(opaque(light), opaque(dark)),
440                day_spec::Ink::System { role, .. } => ink_css(day_spec::Ink::System {
441                    role,
442                    alpha: Some(1.0),
443                }),
444            };
445            s(el, "--day-tint", &fill);
446            s(
447                el,
448                "--day-tint-fg",
449                &pair_css(
450                    ButtonStyleSpec::on_tint(on_light),
451                    ButtonStyleSpec::on_tint(on_dark),
452                ),
453            );
454            class(el, "tinted", true);
455        }
456        ButtonStyleSpec::Automatic | ButtonStyleSpec::Plain => {}
457    }
458}
459
460/// Set a label's text, as styled spans when it has runs (docs/text-runs.md).
461///
462/// Runs become `<span>` children (a link run an `<a>`), which is what lets the whole thing stay
463/// One wrapping paragraph — the browser wraps across the spans as if they were plain text. The
464/// text goes through `textContent` per span rather than any HTML string, so a translated string
465/// containing `<` or `&` is inert.
466fn set_label_text(el: u32, s: &str, runs: &[day_spec::TextRun]) {
467    if runs.is_empty() {
468        text(el, s);
469        return;
470    }
471    // Clear and rebuild: a label's runs change wholesale (LabelPatch::Runs carries both), so
472    // there is nothing to diff against.
473    text(el, "");
474    let mut at = 0usize;
475    for r in runs {
476        // Same rule as the markup serializer: a run that does not address this string is
477        // skipped without advancing, so the text survives even when the styling does not.
478        let Some(styled) = s.get(r.range.clone()) else {
479            continue;
480        };
481        if r.range.start > at
482            && let Some(plain) = s.get(at..r.range.start)
483        {
484            append_span(el, plain, None);
485        }
486        append_span(el, styled, Some(r));
487        at = r.range.end;
488    }
489    if let Some(tail) = s.get(at..) {
490        append_span(el, tail, None);
491    }
492}
493
494/// One `<span>` (or `<a>`) child carrying a run's styling.
495fn append_span(parent: u32, content: &str, run: Option<&day_spec::TextRun>) {
496    let kind = if run.is_some_and(|r| r.link.is_some()) {
497        EL_LINK
498    } else {
499        EL_SPAN
500    };
501    let el = unsafe { day_dom_create(kind) };
502    text(el, content);
503    if let Some(r) = run {
504        apply_font(el, &r.font);
505        if let Some(c) = r.color {
506            s(el, "color", &ink_css(c));
507        }
508        if let Some(c) = r.background {
509            s(el, "background-color", &ink_css(c));
510        }
511        if let Some(url) = r.link.as_deref() {
512            unsafe { day_dom_link(el, parent, url.as_ptr(), url.len()) };
513        }
514        // One element has one decoration style and color for all its lines: an underline and
515        // a strikethrough that differ in either take an inner span for the strikethrough,
516        // which inherits the outer underline's drawing (CSS propagates decorations to inline
517        // descendants).
518        match (r.underline, r.strikethrough) {
519            (Some(u), Some(st)) if u != st => {
520                apply_decoration(el, "underline", Some(u));
521                let inner = unsafe { day_dom_create(EL_SPAN) };
522                text(el, "");
523                text(inner, content);
524                apply_decoration(inner, "line-through", Some(st));
525                unsafe { day_dom_insert(el, inner, u32::MAX) };
526            }
527            (Some(u), Some(_)) => apply_decoration(el, "underline line-through", Some(u)),
528            (Some(u), None) => apply_decoration(el, "underline", Some(u)),
529            (None, Some(st)) => apply_decoration(el, "line-through", Some(st)),
530            (None, None) => {}
531        }
532    }
533    unsafe { day_dom_insert(parent, el, u32::MAX) };
534}
535
536/// A decoration's lines, style and color on one element: `text-decoration-line`, `-style`
537/// (`solid`, `double`, `dotted`, `wavy`) and `-color` (the text's own where the run names none,
538/// docs/text-runs.md "Decorations").
539fn apply_decoration(el: u32, lines: &str, d: Option<day_spec::Decoration>) {
540    use day_spec::DecorationStyle as D;
541    let Some(d) = d else { return };
542    s(el, "text-decoration-line", lines);
543    let style = match d.style {
544        D::Single => "solid",
545        D::Double => "double",
546        D::Dotted => "dotted",
547        D::Wavy => "wavy",
548    };
549    s(el, "text-decoration-style", style);
550    s(
551        el,
552        "text-decoration-color",
553        &d.color.map_or_else(|| "currentcolor".to_owned(), ink_css),
554    );
555}
556
557fn class(el: u32, c: &str, on: bool) {
558    unsafe { day_dom_set_class(el, c.as_ptr(), c.len(), u32::from(on)) };
559}
560fn warn(msg: &str) {
561    unsafe { day_dom_warn(msg.as_ptr(), msg.len()) };
562}
563/// Read a host "environment" value (query params / navigator facts) as an app-facing
564/// environment lookup: `day launch --env K=V` lands in the page URL's query string and is
565/// read back here (docs/web.md). Empty/absent answers `None`. The page-fact keys (`vw`,
566/// `vh`, `dpr`, `dark`, `reduce_motion`, `locales`, `route`) are reserved by the shim.
567#[must_use]
568pub fn host_env(key: &str) -> Option<String> {
569    let v = env(key);
570    if v.is_empty() { None } else { Some(v) }
571}
572
573/// Seconds on the page's monotonic clock (`performance.now()`), for `day_core::frame::now_secs`
574/// on a target without `Instant`.
575#[must_use]
576pub fn monotonic_secs() -> f64 {
577    unsafe { day_dom_perf_now() / 1000.0 }
578}
579
580/// Milliseconds since the Unix epoch, from the page's `Date.now()`. The wasm target has no
581/// working `SystemTime::now()`, so time-of-day code asks the host page instead (a zone-aware app's
582/// clock routes through here on `web-dom`).
583#[must_use]
584pub fn now_epoch_ms() -> u64 {
585    let ms = unsafe { day_dom_now_ms() };
586    if ms.is_finite() && ms > 0.0 {
587        ms as u64
588    } else {
589        0
590    }
591}
592
593/// Read a host "environment" value (query params / navigator facts) into a String. A value
594/// longer than the first buffer gets a right-sized retry instead of a mid-UTF-8 truncation:
595/// a shim that reports the value's full length triggers the `n > cap` branch directly, and
596/// one that clamps its return to the buffer (writing exactly `cap` bytes) grows until there
597/// is headroom.
598fn env(key: &str) -> String {
599    read_buffer(|out, cap| unsafe { day_dom_env(key.as_ptr(), key.len(), out, cap) })
600}
601
602/// The `day_dom_env` buffer protocol for any string the shim answers: `fill` writes into the
603/// buffer and returns the length, and a full buffer means retry with a larger one.
604fn read_buffer(fill: impl Fn(*mut u8, usize) -> usize) -> String {
605    let mut cap = 512usize;
606    loop {
607        let mut buf = vec![0u8; cap];
608        let n = fill(buf.as_mut_ptr(), buf.len());
609        if n > cap {
610            cap = n;
611            continue;
612        }
613        if n == cap {
614            cap *= 2;
615            continue;
616        }
617        buf.truncate(n);
618        return String::from_utf8_lossy(&buf).into_owned();
619    }
620}
621
622thread_local! {
623    /// Elements the app gave an accessibility label (`set_a11y`), whose `aria-label` a button's
624    /// title change must leave alone. A `SideTable`, so release sweeps it.
625    static APP_NAMED: day_spec::sidetable::SideTable<()> = day_spec::sidetable::SideTable::new();
626    /// Menu button element → the provider its press opens (`set_button_menu`, docs/menus.md
627    /// "Menu buttons"). A `SideTable`, so release sweeps it.
628    static BUTTON_MENUS: day_spec::sidetable::SideTable<day_spec::ContextMenuFn> =
629        day_spec::sidetable::SideTable::new();
630}
631
632/// What a realized image was given, so a patch can rebuild its mask from the same URL and
633/// scaling (`apply_image_tint`). The DOM bridge writes attributes but does not read them back,
634/// and keeping this here is cheaper than adding a getter to the shim for one caller.
635#[derive(Clone)]
636struct ImageState {
637    src: String,
638    /// The `object-fit` keyword the content mode mapped to, which the mask scales by.
639    fit: &'static str,
640    tint: Option<day_spec::Ink>,
641    template: bool,
642    /// Realized as an `<img>` (no tint, not a template) rather than as the masked div.
643    is_img: bool,
644}
645
646impl ImageState {
647    /// A masked element rather than an `<img>`: a tint or a template paints the mask.
648    fn masked(&self) -> bool {
649        self.tint.is_some() || self.template
650    }
651}
652
653thread_local! {
654    /// The linear gradient of each surface filled with one (docs/surfaces.md) and the size it
655    /// was last written for, kept so `set_frame` can resolve its unit points against the new
656    /// size. A `SideTable`, so release sweeps it.
657    static SURFACE_GRADIENTS: day_spec::sidetable::SideTable<(day_spec::LinearGradient, Size)> =
658        day_spec::sidetable::SideTable::new();
659
660    /// The realize-time role of each surface given one, which a `ContainerPatch::Surface`
661    /// keeps (its own `role` is ignored).
662    static SURFACE_ROLES: day_spec::sidetable::SideTable<day_spec::SurfaceRole> =
663        day_spec::sidetable::SideTable::new();
664
665    /// Each realized image's [`ImageState`].
666    static IMAGE_SRC: RefCell<HashMap<u32, ImageState>> = RefCell::new(HashMap::new());
667
668    /// `BitmapId` → what the decode reported (docs/images.md). Seeded when the decode is
669    /// REQUESTED, not when it answers: the container format comes from the bytes on this side and
670    /// the alpha answer follows from it, because an `ImageBitmap` exposes neither. The browser
671    /// fills in only the pixel size.
672    static BITMAP_INFO: RefCell<HashMap<u64, day_spec::BitmapInfo>> = RefCell::new(HashMap::new());
673}
674
675/// Recolor an image (docs/vectors.md "Tint", "Template"; docs/images.md "Tinting").
676///
677/// The browser cannot recolor the pixels of an `<img>`, so a tinted image becomes a MASK painted
678/// with the tint — the same technique the nav rows use for their icons. A CSS mask is cut from
679/// the image's alpha, so this is the source-in recolor the spec asks for, for a raster as much
680/// as for a glyph. A template with no tint paints the mask with `currentColor`, so it follows
681/// the text color around it (light on a dark sidebar, white on a selected row) the way those
682/// rows do.
683///
684/// An element realized tinted (or as a template) is a div and only ever shows the mask. One
685/// realized plain is an `<img>`; a tint that arrives later masks it too and moves its own
686/// pixels out of its box (`object-position`), so only the painted mask shows, and taking the
687/// tint away puts it back exactly as it was.
688fn apply_image_tint(el: u32, state: &ImageState) {
689    if state.masked() {
690        if state.src.is_empty() {
691            // Bytes or a decoded bitmap: the shim owns the URL and cuts the mask from it, now
692            // and at every later source swap.
693            // SAFETY: an element id the shim either knows or does not.
694            unsafe { day_dom_image_mask(el, 1) };
695        } else {
696            let mask = format!("url(\"{}\")", state.src);
697            s(el, "mask-image", &mask);
698            s(el, "-webkit-mask-image", &mask);
699        }
700        // The mask scales the way the untinted image would: `object-fit` and `mask-size`
701        // share contain/cover, and Stretch's `fill` is `100% 100%`.
702        let size = if state.fit == "fill" {
703            "100% 100%"
704        } else {
705            state.fit
706        };
707        for prop in ["mask-size", "-webkit-mask-size"] {
708            s(el, prop, size);
709        }
710        for prop in ["mask-repeat", "-webkit-mask-repeat"] {
711            s(el, prop, "no-repeat");
712        }
713        for prop in ["mask-position", "-webkit-mask-position"] {
714            s(el, prop, "center");
715        }
716        let paint = state
717            .tint
718            .map_or_else(|| "currentColor".to_owned(), ink_css);
719        s(el, "background-color", &paint);
720        if state.is_img {
721            s(el, "object-position", "-100000px -100000px");
722        }
723    } else {
724        // SAFETY: as above.
725        unsafe { day_dom_image_mask(el, 0) };
726        for prop in [
727            "mask-image",
728            "-webkit-mask-image",
729            "mask-size",
730            "-webkit-mask-size",
731            "mask-repeat",
732            "-webkit-mask-repeat",
733            "mask-position",
734            "-webkit-mask-position",
735            "background-color",
736            "object-position",
737        ] {
738            s(el, prop, "");
739        }
740    }
741}
742
743/// The staged file extension for a bare image NAME: `svg` when the name is a bundled vector
744/// glyph (docs/vectors.md — the browser then renders it at display size), `png` otherwise.
745/// The page carries the vector-name list (`window.__DAY_VECTORS`, injected at assemble) and
746/// answers through the env channel's reserved `vector:` keys, so an older host page simply
747/// answers empty and the raster fallback still resolves.
748fn image_ext(name: &str) -> &'static str {
749    if env(&format!("vector:{name}")).is_empty() {
750        "png"
751    } else {
752        "svg"
753    }
754}
755
756/// The staged glyph a name resolves to. A weight variant with no art of its own falls back to its
757/// base glyph (docs/vectors.md): only SF-template sources stage `__light`/`__bold`, so a plain
758/// SVG's weight name would otherwise request an asset that was never staged. The base must itself
759/// be a known vector before we strip, so an ORDINARY image that happens to end in `__bold` is
760/// left alone.
761fn resolved_name(name: &str) -> String {
762    if !env(&format!("vector:{name}")).is_empty() {
763        return name.to_string();
764    }
765    for suffix in ["__light", "__bold"] {
766        if let Some(base) = name.strip_suffix(suffix)
767            && !base.is_empty()
768            && !env(&format!("vector:{base}")).is_empty()
769        {
770            return base.to_string();
771        }
772    }
773    name.to_string()
774}
775
776/// The page-relative URL for an image or vector NAME, alias-resolved.
777fn image_url(name: &str) -> String {
778    let n = resolved_name(name);
779    format!("assets/images/{n}.{}", image_ext(&n))
780}
781
782/// A [`Symbol`](day_spec::Symbol) as an inline-SVG `data:` URL, for the same CSS mask the shim
783/// draws a bundled image through — so a toolbar looks the same whether its items asked for a
784/// standard symbol or shipped their own art.
785///
786/// The web has no system icon set. Every other backend hands a `Symbol` to one the OS supplies
787/// (SF Symbols, freedesktop names, Fluent glyphs); here the alternative to drawing them is what
788/// this used to do, which was to draw nothing and let the label carry the item — leaving a bar
789/// where some items had icons and some did not, depending on whether they happened to use a
790/// bundled image.
791///
792/// The paths are deliberately plain geometry on a 24×24 grid, authored here rather than taken
793/// from an icon set: it keeps day free of a third-party icon license, and at toolbar size the
794/// shapes are what read, not their styling. `None` for a symbol with no glyph yet — the item
795/// falls back to its label, which is what the whole set did before.
796fn symbol_svg(sym: day_spec::Symbol) -> Option<String> {
797    // The shared outline table (day-spec), inlined as a data: URL. Single quotes in the markup
798    // and a percent-encoded `<`, `>` and `#` keep it valid in both the CSS value and the
799    // attribute the shim assigns it to.
800    let d = sym.outline_path()?;
801    Some(format!(
802        "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill-rule='evenodd' d='{d}'/%3E%3C/svg%3E"
803    ))
804}
805
806// ---------------------------------------------------------------------------
807// Element kinds the shim knows how to create (shim.js `create()` mirrors this table).
808// ---------------------------------------------------------------------------
809
810const EL_DIV: u32 = 0;
811const EL_LABEL: u32 = 1;
812const EL_BUTTON: u32 = 2;
813const EL_TOGGLE: u32 = 3;
814const EL_SLIDER: u32 = 4;
815const EL_FIELD: u32 = 5;
816const EL_AREA: u32 = 6;
817const EL_SELECT: u32 = 7;
818const EL_PROGRESS: u32 = 8;
819const EL_SPINNER: u32 = 9;
820const EL_IMAGE: u32 = 10;
821const EL_CANVAS: u32 = 11;
822const EL_SCROLL: u32 = 12;
823const EL_DIVIDER: u32 = 13;
824const EL_NAV: u32 = 14;
825const EL_PAGE: u32 = 15;
826const EL_NAVMENU: u32 = 16;
827const EL_CELL: u32 = 18;
828const EL_SEGMENTED: u32 = 19;
829const EL_RADIOS: u32 = 20;
830/// A styled run inside a label (docs/text-runs.md), and the same as a link.
831const EL_SPAN: u32 = 21;
832const EL_LINK: u32 = 22;
833
834/// Wire event kinds the shim reports through `day_dom_event` (shim.js mirrors this table).
835mod ev {
836    pub const CLICK: u32 = 1; // a = ctrl/cmd bit0 + shift bit1 modifier mask
837    pub const SUBMIT: u32 = 3;
838    pub const TOGGLE: u32 = 4; // a = 0/1
839    pub const VALUE: u32 = 5; // a
840    pub const SELECT: u32 = 6; // a = index
841    pub const FOCUS: u32 = 7; // a = 0/1
842    pub const TAP: u32 = 8; // a,b = local point
843    pub const DRAG_BEGAN: u32 = 9; // a,b = location; c,d = translation
844    pub const DRAG_MOVED: u32 = 10;
845    pub const DRAG_ENDED: u32 = 11;
846    pub const SCROLL: u32 = 12; // a,b = offset
847    pub const RESIZED: u32 = 13; // a,b = size (ResizeObserver)
848    pub const NAV_BACK: u32 = 14;
849    /// a = the settled value. The DOM already separates the two: `input` fires as the thumb
850    /// moves, `change` once the user lets go (day-spec `Event::ValueCommitted`).
851    pub const VALUE_COMMITTED: u32 = 15;
852    /// a,b = local point; c,d = the same point in viewport coordinates. The browser's
853    /// `contextmenu` (right-click / long-press), default prevented; the pieces layer
854    /// presents the composed menu at the viewport point (docs/menus.md).
855    pub const CONTEXT: u32 = 16;
856    /// a,b = local point. Pointer entry, motion and exit over the element
857    /// (docs/canvas.md "Interaction"); the exit carries the last point seen inside.
858    pub const HOVER_ENTER: u32 = 17;
859    pub const HOVER_MOVED: u32 = 18;
860    pub const HOVER_LEFT: u32 = 19;
861    pub const PAN: u32 = 20;
862    /// a,b = local centroid; c = scale, cumulative since `PINCH_BEGAN` for a two-finger
863    /// touch, the tick's own factor for a trackpad pinch (a ctrl+wheel, which arrives as a
864    /// lone `PINCH_MOVED`; docs/canvas.md "Zoom and pan").
865    pub const PINCH_BEGAN: u32 = 21;
866    pub const PINCH_MOVED: u32 = 22;
867    pub const PINCH_ENDED: u32 = 23;
868    /// a,b = local centroid; c = rotation in radians, clockwise positive, cumulative since
869    /// `ROTATE_BEGAN` (two fingers, or Safari's trackpad gesture events; docs/canvas.md "Zoom
870    /// and pan").
871    pub const ROTATE_BEGAN: u32 = 24;
872    pub const ROTATE_MOVED: u32 = 25;
873    pub const ROTATE_ENDED: u32 = 26;
874    /// a,b = the press point; fired once while the pointer is still down (docs/gestures.md
875    /// "Long press").
876    pub const LONG_PRESS: u32 = 27;
877    /// a,b = the second tap's point (`dblclick`).
878    pub const DOUBLE_TAP: u32 = 28;
879    /// a,b = the point; c = 1 for the press, 0 for its end (docs/gestures.md "Press").
880    pub const PRESS: u32 = 29;
881    /// a = the user's scroll phase: 0 idle, 1 dragging, 2 coasting (docs/scroll.md "Phases").
882    pub const SCROLL_PHASE: u32 = 30;
883}
884
885/// Listen-mask bits for the recognizers `enable_gesture` attaches (shim.js `listen`), beyond
886/// the public [`listen`] constants.
887mod gesture_mask {
888    pub const TAP: u32 = 128;
889    pub const DRAG: u32 = 256;
890    pub const CONTEXT_MENU: u32 = 1024;
891    pub const PAN: u32 = 2048;
892    pub const PINCH: u32 = 4096;
893    pub const ROTATE: u32 = 8192;
894    pub const LONG_PRESS: u32 = 1 << 14;
895    pub const DOUBLE_TAP: u32 = 1 << 15;
896    pub const PRESS: u32 = 1 << 16;
897    pub const TOUCHES: u32 = 1 << 17;
898    pub const HOVER: u32 = 1 << 18;
899}
900
901// ---------------------------------------------------------------------------
902// Toolkit state
903// ---------------------------------------------------------------------------
904
905/// A shim element id. The shim keeps `els[id] = Element`; Rust only ever sees the number.
906#[derive(Clone, Copy, PartialEq, Eq, Hash)]
907pub struct DomHandle(pub u32);
908
909struct NavState {
910    presentation: NavPresentation,
911    /// Detail pages. In `Stack` they are a push stack and the sidebar page is the root, so it
912    /// appears here first; everywhere else they are the host's detail children in attach order
913    /// and the sidebar page lives in the chrome slot instead. A re-present moves it between the
914    /// two (see `nav_present`).
915    pages: Vec<u32>,
916    /// The host's sidebar page, once it has one. Tracked by identity so a re-present can re-home
917    /// it without depending on where it currently sits.
918    sidebar: Option<u32>,
919    titles: Vec<String>,
920    /// Which detail page is showing in a presentation whose rows are chrome — an index into
921    /// `pages`. Meaningless while stacked, where the top of the stack is always the last page.
922    selected: usize,
923}
924
925/// The shim's presentation encoding. The FFI edge speaks numbers, so this is the one place the
926/// mapping lives; the shim's `navChrome` switches on the same four.
927fn nav_mode(p: NavPresentation) -> u32 {
928    match p {
929        NavPresentation::Split => 0,
930        NavPresentation::Stack => 1,
931        NavPresentation::Tabs => 2,
932        NavPresentation::Rail => 3,
933    }
934}
935
936struct ListEntry {
937    activatable: bool,
938    node: NodeId,
939    content: u32,
940    /// The declared pitch of a `Uniform` list; for an `Automatic` one, the estimate a row
941    /// stands at until it has been measured.
942    row_height: f64,
943    /// `RowHeight::Automatic`: each row takes the height Day laid it at
944    /// (`ListSource::cell_height`), and rows stack by those heights rather than a pitch.
945    automatic: bool,
946    /// A self-sizing list's measured row heights, by row; `0.0` for a row never bound, which
947    /// stands at [`ListEntry::estimate`]. Empty for a `Uniform` list.
948    heights: Vec<f64>,
949    source: Option<ListSource>,
950    /// One slot per row, 0 until that row has been shown: cell index == row index, so a slot's
951    /// identity never changes and a realized cell stays that row's for good.
952    cells: Vec<u32>,
953    /// Which rows' content is currently built and current. Cleared wholesale when the source
954    /// changes under the cells; individual rows go true as they are bound.
955    bound: Vec<bool>,
956    /// A scroll-driven fill is already posted — a flick emits a stream of scroll events, and
957    /// they would each post a pass that does the same work.
958    fill_pending: bool,
959    /// A row jump (`ListPatch::ScrollToRow`) for the next fill to repeat once the content has
960    /// its full height.
961    pending_scroll: Option<f64>,
962    /// The offset, visible height and row count the last fill read: the viewport its report
963    /// describes. A list that now reads otherwise owes a report (`list_settled`).
964    seen: Option<(f64, f64, usize)>,
965    /// `ui_idle` polls in a row that found a report owed (`list_settled`): past
966    /// [`LIST_OWED_POLLS`] the report stops counting as owed.
967    owed_polls: u32,
968    last_width: f64,
969    selectable: bool,
970    /// Host-drawn row separators (docs/list.md): a bottom border on each cell, so the line
971    /// sits exactly at the row boundary the cell frame defines.
972    separators: bool,
973    multi: bool,
974    selected: BTreeSet<usize>,
975    /// The FIXED end of a shifted range — the row the extension pivots on, set by a plain click
976    /// or a plain arrow and left alone while shift moves the other end.
977    anchor: Option<usize>,
978    /// The MOVING end: where the keyboard is, and the row a shifted arrow walks. Separate from
979    /// the anchor because a range has two ends and `shift+↓ ↓ ↑` has to grow twice and shrink
980    /// once — one field cannot both stay put and move.
981    lead: Option<usize>,
982    /// A sectioned list's pinned header (docs/list.md "Sections"): a sticky wrapper at the top
983    /// of the scroll content holding ONE extra cell, bound to the header of the section under
984    /// the top edge. `(wrapper, cell)`, both 0 until a header first scrolls off.
985    pin: (u32, u32),
986    /// The header row bound into the pinned cell, so it rebinds only when the section changes.
987    pin_row: Option<usize>,
988}
989
990impl ListEntry {
991    /// Whether row `row` is a section header (docs/list.md "Sections"); always false on an
992    /// unsectioned list.
993    fn is_header(&self, row: usize) -> bool {
994        self.source
995            .as_ref()
996            .and_then(|src| src.is_header.as_ref())
997            .is_some_and(|is_header| is_header(row))
998    }
999
1000    fn sectioned(&self) -> bool {
1001        self.source
1002            .as_ref()
1003            .is_some_and(|src| src.is_header.is_some())
1004    }
1005
1006    /// Whether row `row` is a header, footer, empty state or padding row Day added
1007    /// (docs/list.md "Header, footer and empty state"): sized like a header, with no row chrome.
1008    fn is_supplement(&self, row: usize) -> bool {
1009        self.source
1010            .as_ref()
1011            .and_then(|src| src.is_supplement.as_ref())
1012            .is_some_and(|f| f(row))
1013    }
1014
1015    fn has_supplements(&self) -> bool {
1016        self.source
1017            .as_ref()
1018            .is_some_and(|src| src.is_supplement.is_some())
1019    }
1020
1021    /// A row the reader can select, activate and walk to: neither a header nor a supplement.
1022    fn is_item(&self, row: usize) -> bool {
1023        !self.is_header(row) && !self.is_supplement(row)
1024    }
1025
1026    /// Rows stand at their own heights rather than a pitch: a self-sizing list, or one with
1027    /// headers or supplementary rows, which take their laid height even when it is `Uniform`.
1028    fn stacked(&self) -> bool {
1029        self.automatic || self.sectioned() || self.has_supplements()
1030    }
1031
1032    /// The header of the section holding `row`: the row itself, or the nearest header above.
1033    fn header_of(&self, row: usize) -> Option<usize> {
1034        (0..=row).rev().find(|i| self.is_header(*i))
1035    }
1036
1037    /// What the pinned header covers above `row`: the height of its section's header, so a
1038    /// row brought into view lands below the pin instead of under it. 0 for a header row or
1039    /// an unsectioned list.
1040    fn pinned_above(&self, row: usize) -> f64 {
1041        if !self.sectioned() || self.is_header(row) {
1042            return 0.0;
1043        }
1044        self.header_of(row).map_or(0.0, |h| {
1045            let (top, bottom) = self.row_span(h);
1046            bottom - top
1047        })
1048    }
1049
1050    /// What an unmeasured row of a self-sizing list stands at: the mean of the rows measured
1051    /// so far, so the scroll extent tracks the real rows, or the declared fallback before any.
1052    fn estimate(&self) -> f64 {
1053        let (sum, count) = self
1054            .heights
1055            .iter()
1056            .filter(|h| **h > 0.0)
1057            .fold((0.0, 0usize), |(s, c), h| (s + h, c + 1));
1058        if count == 0 {
1059            self.row_height.max(1.0)
1060        } else {
1061            sum / count as f64
1062        }
1063    }
1064
1065    /// Every row's top for `n` rows, then the whole extent: `n + 1` entries. A uniform list's
1066    /// are multiples of its pitch; a self-sizing list's add up its measured heights, standing
1067    /// each unmeasured row at the estimate.
1068    fn tops(&self, n: usize) -> Vec<f64> {
1069        let estimate = self.estimate();
1070        let mut tops = Vec::with_capacity(n + 1);
1071        let mut y = 0.0;
1072        for i in 0..n {
1073            tops.push(y);
1074            y += self.height_of(i, estimate);
1075        }
1076        tops.push(y);
1077        tops
1078    }
1079
1080    /// Row `i`'s height: the pitch, or its measured height, or `estimate`. A section header
1081    /// is measured even in a uniform list, whose `heights` then hold only headers.
1082    fn height_of(&self, i: usize, estimate: f64) -> f64 {
1083        if !self.automatic && self.is_item(i) {
1084            return self.row_height.max(1.0);
1085        }
1086        match self.heights.get(i) {
1087            Some(h) if *h > 0.0 => *h,
1088            _ => estimate,
1089        }
1090    }
1091
1092    /// Row `row`'s top and bottom edge in the list's content.
1093    fn row_span(&self, row: usize) -> (f64, f64) {
1094        if !self.stacked() {
1095            let h = self.row_height.max(1.0);
1096            return (row as f64 * h, (row + 1) as f64 * h);
1097        }
1098        let estimate = self.estimate();
1099        let top: f64 = (0..row).map(|i| self.height_of(i, estimate)).sum();
1100        (top, top + self.height_of(row, estimate))
1101    }
1102}
1103
1104/// The grabber strip above a half sheet's content, in CSS px (`.day-cover.day-half`'s
1105/// `padding-top` in day.css).
1106const HALF_SHEET_GRABBER: f64 = 20.0;
1107
1108thread_local! {
1109    static SINK: RefCell<Option<EventSink>> = const { RefCell::new(None) };
1110    /// The page's display state as last reported (`report_window_state`): Normal or Fullscreen.
1111    static WINDOW_STATE: Cell<day_spec::WindowState> =
1112        const { Cell::new(day_spec::WindowState::Normal) };
1113    /// Element id → day node id, for event routing (the shim only knows element ids).
1114    static NODE_OF: RefCell<HashMap<u32, NodeId>> = RefCell::new(HashMap::new());
1115    /// Elements whose frames are CSS-managed (nav/tab pages): `set_frame` skips them.
1116    static CSS_FRAMED: RefCell<std::collections::HashSet<u32>> = RefCell::new(std::collections::HashSet::default());
1117    /// Covers presented as half sheets (`CoverProps::half`, docs/cover.md): the bottom half
1118    /// of the viewport, under a grabber strip the stylesheet pads for.
1119    static COVER_HALF: RefCell<std::collections::HashSet<u32>> = RefCell::new(std::collections::HashSet::default());
1120    /// Covers built as modal sheets (`CoverProps::sheet`, docs/cover.md "Modal sheet"). Whether
1121    /// one shows the composed card is decided at each present (a compact window keeps the full
1122    /// cover), so this only says it may.
1123    static COVER_SHEET: RefCell<std::collections::HashSet<u32>> = RefCell::new(std::collections::HashSet::default());
1124    static NAV_STATE: RefCell<HashMap<u32, NavState>> = RefCell::new(HashMap::new());
1125    /// NAV_PAGE element → is-sidebar, recorded at realize for the nav `insert`.
1126    static PAGE_SIDEBAR: RefCell<HashMap<u32, bool>> = RefCell::new(HashMap::new());
1127    static LISTS: RefCell<HashMap<u32, ListEntry>> = RefCell::new(HashMap::new());
1128    /// List cell element → (list host element, row index) for selection clicks.
1129    static CELL_ROWS: RefCell<HashMap<u32, (u32, usize)>> = RefCell::new(HashMap::new());
1130    /// Spinner-vs-bar per PROGRESS element (progress with `None` renders as a spinner).
1131    static SPINNERS: RefCell<std::collections::HashMap<u32, f64>> = RefCell::new(HashMap::default());
1132    static POSTED: RefCell<VecDeque<Box<dyn FnOnce() + Send>>> = RefCell::new(VecDeque::new());
1133    static DELAYED: RefCell<HashMap<u32, Box<dyn FnOnce() + Send>>> = RefCell::new(HashMap::new());
1134    static NEXT_DELAY: Cell<u32> = const { Cell::new(1) };
1135
1136    static SPLIT_MODE: Cell<bool> = const { Cell::new(true) };
1137    static DARK: Cell<bool> = const { Cell::new(false) };
1138    /// The app-wide appearance (`Toolkit::set_appearance`) and the window's own override
1139    /// (`WindowChange::Appearance`); the page is the one window, so the override wins.
1140    static APPEARANCE: Cell<(Option<bool>, Option<bool>)> = const { Cell::new((None, None)) };
1141    /// The latest viewport size (updated on resize, seeded at launch). A `cover` fills the
1142    /// viewport (`position:fixed; inset:0`), so presenting it seeds its frame from here
1143    /// SYNCHRONOUSLY — without waiting for the async ResizeObserver, whose gap otherwise leaves
1144    /// RTL content laid out at width 0 (i.e. off-screen to the left) until the observer fires
1145    /// (docs/cover.md).
1146    static LAST_VIEWPORT: Cell<Size> = const { Cell::new(Size::new(0.0, 0.0)) };
1147    /// True until the first `set_route` — the launch reflection replaces the history entry.
1148    static FIRST_ROUTE: Cell<bool> = const { Cell::new(true) };
1149    /// The showcase's `select:`-driven pickers: segmented/radio groups keep their option
1150    /// count so a programmatic Selected patch can re-style the active option.
1151    static SEG_COUNT: RefCell<HashMap<u32, usize>> = RefCell::new(HashMap::new());
1152    /// Each picker's last programmatic selection, so a change of OPTIONS can keep it: the
1153    /// shim's option builder rewrites the element, and the DOM's own selectedIndex goes with
1154    /// it.
1155    static PICKER_SELECTED: RefCell<HashMap<u32, usize>> = RefCell::new(HashMap::new());
1156    /// Per-picker intrinsic size, computed from its option strings at realize (the element's
1157    /// own textContent concatenates every option, so measuring it lies about width — and a
1158    /// vertical radio group needs a per-row height the one-line measure can't produce).
1159    static PICKER_SIZE: RefCell<HashMap<u32, Size>> = RefCell::new(HashMap::new());
1160    // Text-area sizing hints (docs/textarea.md): `(min_lines, max_lines, content_lines)`, kept
1161    // so `measure` can honor the auto-growing-height contract the other backends implement.
1162    // `content_lines` counts the day-driven text's hard line breaks (realize + SetText) — an
1163    // approximation that ignores soft wrapping, noted in `measure`.
1164    static AREA_HINTS: RefCell<HashMap<u32, (u32, u32, u32)>> = RefCell::new(HashMap::new());
1165    /// Per label element: the text it stands for and its paragraph attributes (docs/text.md).
1166    static LABELS: RefCell<HashMap<u32, LabelState>> = RefCell::new(HashMap::new());
1167    /// The recognizer bits already attached per element (`enable_gesture` is idempotent).
1168    static GESTURES: RefCell<HashMap<u32, u32>> = RefCell::new(HashMap::new());
1169    /// The reading direction `set_layout_direction` gave an element (`true` = right to left);
1170    /// an element it never named follows the app's.
1171    static DIRECTION: RefCell<HashMap<u32, bool>> = RefCell::new(HashMap::new());
1172}
1173
1174/// Attach the shim listeners for `mask`'s bits not yet attached to `el`: a recognizer is a set of
1175/// listeners, and a second `listen` would double what it reports.
1176fn listen_once(el: u32, mask: u32) {
1177    let fresh = GESTURES.with(|g| {
1178        let mut g = g.borrow_mut();
1179        let had = g.entry(el).or_insert(0);
1180        let fresh = mask & !*had;
1181        *had |= mask;
1182        fresh
1183    });
1184    if fresh != 0 {
1185        unsafe { day_dom_listen(el, fresh) };
1186    }
1187}
1188
1189/// What a label element shows and how (docs/text.md): kept beside the element because a head or
1190/// middle truncation replaces the element's text with an elided copy, and every later change
1191/// (width, font, paragraph, text) elides the full text again.
1192struct LabelState {
1193    /// The full text: `LabelProps::text` or the latest text patch.
1194    text: String,
1195    /// Styled runs are spans: elision (plain text only) falls back to the tail there.
1196    runs: bool,
1197    wraps: bool,
1198    para: LabelParagraph,
1199    /// The width of the last frame, which head and middle truncation elide to.
1200    width: f64,
1201    /// Whether the element shows an elided copy rather than `text`.
1202    elided: bool,
1203    /// Whether a nonempty selection was reported last (`LabelProps::reports_selection`).
1204    selected: bool,
1205}
1206
1207impl LabelState {
1208    /// One line, where every truncation mode applies (docs/text.md "Truncation").
1209    fn one_line(&self) -> bool {
1210        !self.wraps || self.para.max_lines == 1
1211    }
1212
1213    /// Whether the element must show `day_spec::elide`'s copy: CSS truncates only the tail.
1214    fn elides(&self) -> bool {
1215        self.one_line() && !self.runs && self.para.truncation != Truncation::Tail
1216    }
1217}
1218
1219/// A label's new text (a text or runs patch); a selection the patch discards is reported
1220/// cleared.
1221fn set_label_state_text(el: u32, t: &str, runs: bool) {
1222    let cleared = LABELS.with(|tab| {
1223        let mut tab = tab.borrow_mut();
1224        let Some(st) = tab.get_mut(&el) else {
1225            return false;
1226        };
1227        t.clone_into(&mut st.text);
1228        st.runs = runs;
1229        std::mem::take(&mut st.selected)
1230    });
1231    if cleared && let Some(node) = node_of(el) {
1232        emit(node, Event::TextSelected { start: 0, end: 0 });
1233    }
1234}
1235
1236/// A line height a label can use: a finite positive multiple of the font size.
1237fn usable_line_height(multiple: f64) -> Option<f64> {
1238    (multiple.is_finite() && multiple > 0.0).then_some(multiple)
1239}
1240
1241/// The paragraph attributes on a label element (docs/text.md): letter spacing in `em`, a
1242/// unitless `line-height` (exactly Day's multiple-of-the-font-size model), and the line limit
1243/// as `-webkit-line-clamp` on a vertical `-webkit-box`, which the measuring copy in the shim
1244/// carries too. Idempotent; called at realize, on every paragraph or font patch (the `font`
1245/// shorthand resets `line-height`), and the elision follows.
1246fn apply_paragraph(el: u32) {
1247    let Some((wraps, para)) = LABELS.with(|t| t.borrow().get(&el).map(|st| (st.wraps, st.para)))
1248    else {
1249        return;
1250    };
1251    let ls = if para.letter_spacing.is_finite() && para.letter_spacing != 0.0 {
1252        format!("{}em", para.letter_spacing)
1253    } else {
1254        String::new()
1255    };
1256    s(el, "letter-spacing", &ls);
1257    // Natural is what `font_css`'s shorthand says: 1.3.
1258    let lh =
1259        usable_line_height(para.line_height).map_or_else(|| "1.3".to_owned(), |m| m.to_string());
1260    s(el, "line-height", &lh);
1261    if wraps && para.max_lines > 0 {
1262        let n = para.max_lines.to_string();
1263        s(el, "display", "-webkit-box");
1264        s(el, "-webkit-box-orient", "vertical");
1265        s(el, "-webkit-line-clamp", &n);
1266        s(el, "line-clamp", &n);
1267    } else {
1268        s(el, "display", "");
1269        s(el, "-webkit-box-orient", "");
1270        s(el, "-webkit-line-clamp", "");
1271        s(el, "line-clamp", "");
1272    }
1273    if wraps && para.max_lines == 1 {
1274        // One clamped line wraps nowhere: the tail ellipsis of a single line.
1275        s(el, "white-space", "nowrap");
1276    } else if wraps {
1277        s(el, "white-space", "");
1278    }
1279    MEASURE_CACHE.with(|c| c.borrow_mut().retain(|(e, _), _| *e != el));
1280    elide_label(el);
1281}
1282
1283/// Show `day_spec::elide`'s copy of a one-line label truncated at the head or the middle, or the
1284/// full text again where none is needed. The full text stays the element's `data-day-text` (what
1285/// `read_native` reports) and, unless the app named the element, its `aria-label`.
1286fn elide_label(el: u32) {
1287    let Some((full, elides, was, width, mode)) = LABELS.with(|t| {
1288        t.borrow().get(&el).map(|st| {
1289            (
1290                st.text.clone(),
1291                st.elides(),
1292                st.elided,
1293                st.width,
1294                st.para.truncation,
1295            )
1296        })
1297    }) else {
1298        return;
1299    };
1300    let shown = if elides && width > 0.0 {
1301        day_spec::elide(&full, mode, width, |candidate| {
1302            label_size(el, Some(candidate), f64::MAX).width
1303        })
1304    } else {
1305        full.clone()
1306    };
1307    let now = shown != full;
1308    if now || was {
1309        text(el, &shown);
1310    }
1311    if now || was {
1312        attr(el, "data-day-text", if now { &full } else { "" });
1313        if APP_NAMED.with(|t| t.get(el as usize)).is_none() {
1314            attr(el, "aria-label", if now { &full } else { "" });
1315        }
1316    }
1317    LABELS.with(|t| {
1318        if let Some(st) = t.borrow_mut().get_mut(&el) {
1319            st.elided = now;
1320        }
1321    });
1322}
1323
1324/// A label's size in its own style, for `text` in place of its content when given.
1325fn label_size(el: u32, text: Option<&str>, max_w: f64) -> Size {
1326    let mut out = [0.0f64; 2];
1327    let (ptr, len) = text.map_or((std::ptr::null(), 0), |t| (t.as_ptr(), t.len()));
1328    // SAFETY: `text` outlives the call and `out` has room for the two values the shim writes.
1329    unsafe { day_dom_measure_label(el, ptr, len, max_w, out.as_mut_ptr()) };
1330    Size::new(out[0], out[1])
1331}
1332
1333/// The byte offset in `text` of a UTF-16 offset (the DOM's `Range` counts), clamped to the
1334/// text and landing on a character boundary.
1335fn utf16_to_byte(text: &str, units: usize) -> usize {
1336    let mut seen = 0usize;
1337    for (i, ch) in text.char_indices() {
1338        if seen >= units {
1339            return i;
1340        }
1341        seen += ch.len_utf16();
1342    }
1343    text.len()
1344}
1345
1346/// Whether `el` reads right to left: its own direction once told, else the app's.
1347fn element_rtl(el: u32) -> bool {
1348    DIRECTION
1349        .with(|d| d.borrow().get(&el).copied())
1350        .unwrap_or_else(day_core::is_rtl)
1351}
1352
1353/// The shim's pointer-kind code (0 touch, 1 mouse, 2 stylus) as Day's kind.
1354fn pointer_kind(code: u32) -> day_spec::PointerKind {
1355    match code {
1356        0 => day_spec::PointerKind::Touch,
1357        2 => day_spec::PointerKind::Stylus,
1358        _ => day_spec::PointerKind::Mouse,
1359    }
1360}
1361
1362/// One contact of the shim's touches wire, `"id,phase,x,y,pressure,kind"` (phase 0 began,
1363/// 1 moved, 2 stationary, 3 ended, 4 cancelled; kind 0 touch, 1 mouse, 2 stylus), or `None`
1364/// for a malformed entry.
1365fn parse_touch(entry: &str) -> Option<day_spec::Touch> {
1366    use day_spec::{Touch, TouchPhase};
1367    let mut f = entry.split(',');
1368    let id: u64 = f.next()?.trim().parse().ok()?;
1369    let phase = match f.next()?.trim() {
1370        "0" => TouchPhase::Began,
1371        "1" => TouchPhase::Moved,
1372        "2" => TouchPhase::Stationary,
1373        "3" => TouchPhase::Ended,
1374        "4" => TouchPhase::Cancelled,
1375        _ => return None,
1376    };
1377    let x: f64 = f.next()?.trim().parse().ok()?;
1378    let y: f64 = f.next()?.trim().parse().ok()?;
1379    let pressure: f64 = f.next()?.trim().parse().ok()?;
1380    let kind = pointer_kind(f.next()?.trim().parse().ok()?);
1381    Some(
1382        Touch::new(id, phase, Point::new(x, y))
1383            .with_pressure(pressure)
1384            .with_kind(kind),
1385    )
1386}
1387
1388/// The touches wire's whole list (entries separated by `;`), skipping malformed ones.
1389fn parse_touches(wire: &str) -> Vec<day_spec::Touch> {
1390    wire.split(';')
1391        .filter(|e| !e.is_empty())
1392        .filter_map(parse_touch)
1393        .collect()
1394}
1395
1396/// A key event from the shim's modifier word: the day mask in the low byte, the phase in bits 8
1397/// and 9 ([`day_spec::KeyPhase::from_wire`]). A release carries no text.
1398fn phased_key(key: &str, text: Option<String>, word: u32) -> day_spec::KeyEvent {
1399    let phase = day_spec::KeyPhase::from_wire(f64::from(word));
1400    let modifiers = (word & 0xff) as u8;
1401    match text {
1402        Some(text) if phase != day_spec::KeyPhase::Up => {
1403            day_spec::KeyEvent::typed_by(key, text, modifiers).with_phase(phase)
1404        }
1405        _ => day_spec::KeyEvent::named(key, modifiers).with_phase(phase),
1406    }
1407}
1408
1409/// Measure one string in the control font with no wrap limit. The expression is day.css's `body`
1410/// font-size, named rather than copied — controls (`font: inherit`) render at that size, so
1411/// measuring at anything else would mis-size pickers. The shim measures with a real DOM element,
1412/// so `var(--day-text-scale)` resolves against the document exactly as it does for the control.
1413/// Hard line breaks in a text area's day-driven content — the growth unit its `measure` clamps
1414/// between the `min_lines`/`max_lines` hints.
1415fn content_lines(t: &str) -> u32 {
1416    (t.split('\n').count() as u32).max(1)
1417}
1418
1419fn measure_str(txt: &str) -> Size {
1420    let css = format!("{} {SYSTEM_STACK}", scaled_rem(1.0));
1421    let mut out = [0.0f64; 2];
1422    unsafe {
1423        day_dom_measure_text(
1424            txt.as_ptr(),
1425            txt.len(),
1426            css.as_ptr(),
1427            css.len(),
1428            1.0e6,
1429            out.as_mut_ptr(),
1430        );
1431    };
1432    Size::new(out[0].ceil(), out[1].ceil())
1433}
1434
1435fn emit(node: NodeId, event: Event) {
1436    SINK.with(|s| {
1437        if let Some(sink) = s.borrow().as_ref() {
1438            sink(node, event);
1439        }
1440    });
1441}
1442
1443fn node_of(el: u32) -> Option<NodeId> {
1444    NODE_OF.with(|m| m.borrow().get(&el).copied())
1445}
1446
1447fn remember(el: u32, id: NodeId) {
1448    NODE_OF.with(|m| m.borrow_mut().insert(el, id));
1449}
1450
1451/// Realize fallback for a builtin arm whose props failed to downcast
1452/// ([`day_spec::props_of`] already reported it): the same visible `⟨kind⟩` label the
1453/// missing-renderer path builds, so one mismatched piece cannot take down the tree build.
1454fn realize_placeholder(kind: PieceKind, id: NodeId) -> DomHandle {
1455    let el = unsafe { day_dom_create(EL_LABEL) };
1456    text(el, &format!("⟨{kind}⟩"));
1457    class(el, "placeholder", true);
1458    remember(el, id);
1459    DomHandle(el)
1460}
1461
1462// ---------------------------------------------------------------------------
1463// Fonts: FontSpec → a CSS font shorthand. The ramp is the Apple text-style ratios with Body = 1,
1464// and a step becomes a length through day.css's `--day-text-scale`: `calc(<step>rem * var(…))`.
1465// Naming the variable rather than baking a number in is what keeps one definition of the size —
1466// the stylesheet's — and lets it differ per form factor (docs/web.md): a desktop scale of 0.8125
1467// puts Body on 13px, one CSS pixel per Apple point, while a touch browser anchors `html` to
1468// `-apple-system-body` and takes a scale of 1, so every step lands on the iOS ramp and tracks the
1469// user's Dynamic Type setting. Either way `1rem` is the browser's own preference, so page zoom and
1470// a larger default font scale the whole UI.
1471//
1472// An explicit `System(pt)`/`Custom(_, pt)` size is NOT a ramp step: it means that many pixels at
1473// the default preference (the Apple pt == logical-px convention), so it skips the scale and stays
1474// in rem — still scaling with the browser preference, per docs/text.md.
1475// ---------------------------------------------------------------------------
1476
1477const SYSTEM_STACK: &str =
1478    "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif";
1479
1480/// The fixed-pitch counterpart of [`SYSTEM_STACK`], for `FontSpec::monospace`. `ui-monospace`
1481/// first so the browser's own fixed face wins where it has one; the generic `monospace` last so
1482/// there is always something fixed-pitch to fall back to.
1483const MONO_STACK: &str =
1484    "ui-monospace, SFMono-Regular, Menlo, Consolas, 'Liberation Mono', monospace";
1485
1486/// A ramp step as a CSS length: the step in rem, scaled by the stylesheet's `--day-text-scale`.
1487fn scaled_rem(step: f64) -> String {
1488    format!("calc({step}rem * var(--day-text-scale))")
1489}
1490
1491fn font_rem(style: Font) -> (f64, u32) {
1492    match style {
1493        Font::LargeTitle => (2.0, 700),
1494        Font::Title => (1.625, 700),
1495        Font::Title2 => (1.25, 600),
1496        Font::Title3 => (1.125, 600),
1497        Font::Headline => (1.0, 600),
1498        Font::Subheadline => (0.875, 400),
1499        Font::Body => (1.0, 400),
1500        Font::Callout => (0.9375, 400),
1501        Font::Footnote => (0.8125, 400),
1502        Font::Caption => (0.75, 400),
1503        Font::Caption2 => (0.6875, 400),
1504        // An explicit point size means that many px at the default preference (matching the
1505        // Apple pt == logical-px convention) — expressed in rem so it still scales with the
1506        // browser preference, per docs/text.md's rule that custom sizes never opt out.
1507        Font::System(pt) | Font::Custom(_, pt) => (pt / 16.0, 400),
1508    }
1509}
1510
1511fn weight_css(w: FontWeight) -> u32 {
1512    match w {
1513        FontWeight::UltraLight => 100,
1514        FontWeight::Thin => 200,
1515        FontWeight::Light => 300,
1516        FontWeight::Regular => 400,
1517        FontWeight::Medium => 500,
1518        FontWeight::Semibold => 600,
1519        FontWeight::Bold => 700,
1520        FontWeight::Heavy => 800,
1521        FontWeight::Black => 900,
1522    }
1523}
1524
1525/// `font` CSS shorthand: `style weight size/line-height family`. The unitless line-height
1526/// (1.3, matching the old px ramp's ratio) rides the size, so it scales too.
1527fn font_css(f: &FontSpec) -> String {
1528    let (rem, default_weight) = font_rem(f.style);
1529    // A ramp step takes the stylesheet's scale; an explicit pt size is already a size.
1530    // `FontSpec::scale` multiplies either — the same relative-size idea CSS spells `em`, so it
1531    // folds into the rem figure rather than needing a property of its own.
1532    let rem = rem * f.scale;
1533    let size = match f.style {
1534        Font::System(_) | Font::Custom(_, _) => format!("{rem}rem"),
1535        _ => scaled_rem(rem),
1536    };
1537    let weight = f.weight.map_or(default_weight, weight_css);
1538    let italic = if f.italic { "italic " } else { "" };
1539    // A bundled family names itself first and falls back to the stack; `monospace` picks the
1540    // fixed-pitch stack, which is what a code run asks for.
1541    let stack = if f.monospace {
1542        MONO_STACK
1543    } else {
1544        SYSTEM_STACK
1545    };
1546    let family = match f.style {
1547        Font::Custom(name, _) => format!("'{name}', {stack}"),
1548        _ => stack.to_string(),
1549    };
1550    format!("{italic}{weight} {size}/1.3 {family}")
1551}
1552
1553fn color_css(c: day_spec::Color) -> String {
1554    format!(
1555        "rgba({},{},{},{})",
1556        (c.r * 255.0).round() as u8,
1557        (c.g * 255.0).round() as u8,
1558        (c.b * 255.0).round() as u8,
1559        c.a
1560    )
1561}
1562
1563/// An ink as a CSS color the browser itself resolves for the page's appearance (docs/color.md),
1564/// so a view follows a light/dark switch with no patch and no Rust code running: a fixed color
1565/// is `rgba(…)`, a pair `light-dark(…)`, a role the stylesheet's `var(--day-<role>)` (day.css
1566/// defines all sixteen for both appearances), and a role at an alpha that alpha over the role's
1567/// channels (relative color syntax, which replaces the role's own alpha exactly).
1568///
1569/// Engines without those functions get equivalents that still follow: a pair through the
1570/// stylesheet's appearance toggles (`--day-if-light`/`--day-if-dark`, day.css), and a role's alpha
1571/// through `color-mix` toward transparent, which multiplies the role's own alpha instead of
1572/// replacing it (the same on the opaque roles).
1573fn ink_css(ink: day_spec::Ink) -> String {
1574    use day_spec::Ink;
1575    match ink {
1576        Ink::Fixed(c) => color_css(c),
1577        Ink::Adaptive { light, dark } => pair_css(light, dark),
1578        Ink::System { role, alpha: None } => format!("var({})", role_var(role)),
1579        Ink::System {
1580            role,
1581            alpha: Some(a),
1582        } => {
1583            let (var, a) = (role_var(role), a.clamp(0.0, 1.0));
1584            if css_colors().1 {
1585                format!("rgb(from var({var}) r g b / {a})")
1586            } else {
1587                format!("color-mix(in srgb, var({var}) {}%, transparent)", a * 100.0)
1588            }
1589        }
1590    }
1591}
1592
1593/// A light/dark pair as one CSS color (see [`ink_css`]).
1594fn pair_css(light: day_spec::Color, dark: day_spec::Color) -> String {
1595    let (l, d) = (color_css(light), color_css(dark));
1596    if l == d {
1597        l
1598    } else if css_colors().0 {
1599        format!("light-dark({l},{d})")
1600    } else {
1601        // Exactly one of the two toggles is the guaranteed-invalid `initial` (its fallback is
1602        // used) and the other is empty, so the value is one color and a space.
1603        format!("var(--day-if-light,{l}) var(--day-if-dark,{d})")
1604    }
1605}
1606
1607/// The stylesheet's custom property for a role (day.css; the brief's table in docs/color.md).
1608fn role_var(role: day_spec::SystemColor) -> &'static str {
1609    use day_spec::SystemColor as R;
1610    match role {
1611        R::Accent => "--day-accent",
1612        R::Text => "--day-fg",
1613        R::SecondaryText => "--day-fg-2",
1614        R::Background => "--day-bg",
1615        R::Surface => "--day-surface",
1616        R::TertiaryText => "--day-fg-3",
1617        R::Placeholder => "--day-placeholder",
1618        R::Link => "--day-link",
1619        R::Separator => "--day-separator",
1620        R::ControlFill => "--day-control",
1621        R::GroupedBackground => "--day-grouped",
1622        R::ElevatedSurface => "--day-elevated",
1623        R::Selection => "--day-selection",
1624        R::Destructive => "--day-destructive",
1625        R::Success => "--day-success",
1626        R::Warning => "--day-warning",
1627    }
1628}
1629
1630/// Whether the engine parses `light-dark()` and relative color syntax, asked once.
1631fn css_colors() -> (bool, bool) {
1632    thread_local! {
1633        static SUPPORT: std::cell::OnceCell<(bool, bool)> = const { std::cell::OnceCell::new() };
1634    }
1635    SUPPORT.with(|c| {
1636        *c.get_or_init(|| {
1637            let v = env("css_colors");
1638            (v.contains('d'), v.contains('r'))
1639        })
1640    })
1641}
1642
1643fn apply_font(el: u32, f: &FontSpec) {
1644    s(el, "font", &font_css(f));
1645    // The `font` shorthand RESETS every `font-variant-*` longhand to normal, so only the
1646    // tabular case writes one back — after the shorthand, never before. The reset is also why
1647    // a re-applied font needs no explicit "normal": the shorthand already cleared a previous
1648    // tabular-nums. Skipping the redundant write keeps the style attribute serializing as the
1649    // one compact `font:` declaration — touching any longhand of the family makes the browser
1650    // spell out every longhand individually, empty values and all.
1651    // The numeric features share one property, so tabular and old-style figures go in one
1652    // declaration; small capitals are `smcp`, never synthesized from scaled capitals by Day.
1653    let numeric = match (f.tabular, f.oldstyle_figures) {
1654        (true, true) => "tabular-nums oldstyle-nums",
1655        (true, false) => "tabular-nums",
1656        (false, true) => "oldstyle-nums",
1657        (false, false) => "",
1658    };
1659    if !numeric.is_empty() {
1660        s(el, "font-variant-numeric", numeric);
1661    }
1662    if f.small_caps {
1663        s(el, "font-variant-caps", "small-caps");
1664        // A face without `smcp` draws its ordinary lowercase, as on every other toolkit,
1665        // rather than capitals the browser scales down.
1666        s(el, "font-synthesis-small-caps", "none");
1667    }
1668}
1669
1670// ---------------------------------------------------------------------------
1671// JSON writer (tiny, escapes only what the shim needs — no serde dependency).
1672// ---------------------------------------------------------------------------
1673
1674/// Build the nav-menu JSON (`{items:[{title, section?, icon?, tint?}], selected}`) the shim's
1675/// `day_dom_navmenu` consumes. Shared by `NAV_MENU` realize and the data-driven
1676/// `NavMenuPatch::Items` rebuild.
1677#[allow(clippy::too_many_arguments)]
1678fn navmenu_json(
1679    items: &[String],
1680    icons: &[Option<String>],
1681    tints: &[Option<day_spec::Ink>],
1682    badges: &[Option<String>],
1683    badge_icons: &[Option<String>],
1684    badge_tints: &[Option<day_spec::Ink>],
1685    sections: &[Option<String>],
1686    selected: Option<usize>,
1687) -> String {
1688    let mut json = String::from("{\"items\":[");
1689    for (i, item) in items.iter().enumerate() {
1690        if i > 0 {
1691            json.push(',');
1692        }
1693        json.push_str("{\"title\":");
1694        json_str(&mut json, item);
1695        // The section heading that opens a group before this row (docs/navigation.md). It rides
1696        // the row rather than the list, so the shim draws it between rows and every index that
1697        // addresses rows stays Day's.
1698        if let Some(Some(section)) = sections.get(i) {
1699            json.push_str(",\"section\":");
1700            json_str(&mut json, section);
1701        }
1702        if let Some(Some(icon)) = icons.get(i) {
1703            json.push_str(",\"icon\":");
1704            json_str(&mut json, &image_url(icon));
1705            // The row's own icon tint (docs/vectors.md): the shim paints the mask with this
1706            // instead of currentColor.
1707            if let Some(Some(t)) = tints.get(i) {
1708                json.push_str(",\"tint\":");
1709                json_str(&mut json, &ink_css(*t));
1710            }
1711        }
1712        // The row's count (docs/navigation.md `badge`), drawn dim at the trailing edge.
1713        if let Some(Some(count)) = badges.get(i) {
1714            json.push_str(",\"count\":");
1715            json_str(&mut json, count);
1716        }
1717        // The trailing status glyph (docs/navigation.md), in the same shape as `icon`/`tint` so
1718        // the shim paints it with one code path at the other end of the row.
1719        if let Some(Some(badge)) = badge_icons.get(i) {
1720            json.push_str(",\"badgeIcon\":");
1721            json_str(&mut json, &image_url(badge));
1722            if let Some(Some(t)) = badge_tints.get(i) {
1723                json.push_str(",\"badgeTint\":");
1724                json_str(&mut json, &ink_css(*t));
1725            }
1726        }
1727        json.push('}');
1728    }
1729    json.push_str("],\"selected\":");
1730    json.push_str(&selected.map_or("-1".into(), |i| i.to_string()));
1731    json.push('}');
1732    json
1733}
1734
1735/// Build the toolbar JSON the shim's `day_dom_toolbar` consumes (docs/toolbars.md). One spec
1736/// per install, the way the nav menu crosses: the shim rebuilds the whole strip, and targeted
1737/// updates go through `day_dom_toolbar_patch` so a search in progress is undisturbed.
1738///
1739/// `kind` mirrors the XAML serializer's one-letter vocabulary so the two stay readable together:
1740/// B button, T toggle, S sidebar toggle, M menu, F search field, L label, `-` separator,
1741/// `_` space, `>` flexible space.
1742/// A toolbar pull-down's item list, for the shim's popup (docs/toolbars.md): label, action
1743/// id, enabled and icon per command; separators as `{"sep":true}`; submenus recursive (the
1744/// shim inlines them, indented, like the composed context menu). Activation rides the same
1745/// `day_dom_toolbar_action` route a plain button takes — the ids are registered menu-action
1746/// ids, and that export emits `Event::MenuAction`.
1747fn menu_items_json(json: &mut String, items: &[day_spec::MenuItem]) {
1748    use std::fmt::Write as _;
1749    json.push('[');
1750    for (i, item) in items.iter().enumerate() {
1751        if i > 0 {
1752            json.push(',');
1753        }
1754        match item {
1755            day_spec::MenuItem::Separator => json.push_str("{\"sep\":true}"),
1756            day_spec::MenuItem::Submenu { label, items, .. } => {
1757                json.push_str("{\"label\":");
1758                json_str(json, label);
1759                json.push_str(",\"items\":");
1760                menu_items_json(json, items);
1761                json.push('}');
1762            }
1763            day_spec::MenuItem::Action {
1764                id,
1765                action,
1766                label,
1767                shortcut,
1768                enabled,
1769                checked,
1770                role,
1771                icon,
1772            } => {
1773                json.push_str("{\"label\":");
1774                json_str(json, label);
1775                json.push_str(",\"id\":");
1776                json.push_str(&action.to_string());
1777                // The app's own name for the item (`.id`, docs/menus.md), so a browser test
1778                // can address the row the way a dayscript `menu:` step does.
1779                if let Some(name) = id {
1780                    json.push_str(",\"name\":");
1781                    json_str(json, name);
1782                }
1783                // The accelerator, for the app menu's key route and the hint beside the row.
1784                // `sys` marks the roles whose keys the browser's own routes already carry
1785                // (the clipboard events, the shim's undo/select-all keys): shown, never
1786                // registered a second time.
1787                if let Some(sc) = shortcut {
1788                    json.push_str(",\"shortcut\":{\"key\":");
1789                    json_str(json, &sc.key);
1790                    let _ = write!(
1791                        json,
1792                        ",\"primary\":{},\"shift\":{},\"alt\":{},\"control\":{}}}",
1793                        sc.primary, sc.shift, sc.alt, sc.control
1794                    );
1795                }
1796                if matches!(
1797                    role,
1798                    Some(
1799                        day_spec::MenuRole::Cut
1800                            | day_spec::MenuRole::Copy
1801                            | day_spec::MenuRole::Paste
1802                            | day_spec::MenuRole::SelectAll
1803                            | day_spec::MenuRole::Undo
1804                            | day_spec::MenuRole::Redo
1805                    )
1806                ) {
1807                    json.push_str(",\"sys\":true");
1808                }
1809                json.push_str(",\"enabled\":");
1810                json.push_str(if *enabled { "true" } else { "false" });
1811                // Absent for a plain command; true/false makes the row checkable and says which
1812                // way, so the shim can reserve the mark's column for a whole run of choices.
1813                if let Some(on) = checked {
1814                    json.push_str(",\"checked\":");
1815                    json.push_str(if *on { "true" } else { "false" });
1816                }
1817                let url = match icon {
1818                    Some(day_spec::Icon::Image(name)) => Some(image_url(name)),
1819                    Some(day_spec::Icon::Symbol(sym)) => symbol_svg(*sym),
1820                    None => None,
1821                };
1822                if let Some(url) = url {
1823                    json.push_str(",\"icon\":");
1824                    json_str(json, &url);
1825                }
1826                json.push('}');
1827            }
1828        }
1829    }
1830    json.push(']');
1831}
1832
1833/// Send the app menu to the shim's trailing toolbar button (docs/menus.md "The composed
1834/// presentation (web-dom)"): the model reduced to what the web can answer, as one JSON document
1835/// with the button's localized name. An empty web model removes the button.
1836fn install_app_menu(items: &[day_spec::MenuItem]) {
1837    use day_spec::MenuBarRole as B;
1838    // The standard slots in the desktops' order, and the stock Help menu for an app that
1839    // claimed none: that is where About and Check for Updates… live on every desktop whose
1840    // bar day-core assembles, and the web has no other place to put them. The other stock
1841    // menus are native selectors (Edit ▸ Cut, View ▸ Enter Full Screen) the web filter would
1842    // drop whole, so they are not asked for.
1843    let bar = day_core::menu::standard_menu_bar(
1844        items.to_vec(),
1845        &[B::File, B::Edit, B::View],
1846        &[B::Help],
1847        |role| match role {
1848            B::Help => day_core::menu::MenuBarStyle::Gnome.stock(B::Help),
1849            _ => None,
1850        },
1851    );
1852    let items = web_menu_items(&bar);
1853    let mut json = String::from("{\"label\":");
1854    json_str(
1855        &mut json,
1856        &day_localization::t(day_localization::key::day_menu),
1857    );
1858    json.push_str(",\"items\":");
1859    menu_items_json(&mut json, &items);
1860    if let Some(url) = symbol_svg(day_spec::Symbol::More) {
1861        json.push_str(",\"icon\":");
1862        json_str(&mut json, &url);
1863    }
1864    json.push('}');
1865    unsafe { day_dom_app_menu(json.as_ptr(), json.len()) };
1866}
1867
1868/// The menu an app that installed no `app_menu` still gets: the registered Settings… command
1869/// (docs/settings.md), the item a desktop's default bar carries; [`install_app_menu`] adds the
1870/// stock Help menu's About and Check for Updates… the same way it does for an installed model.
1871fn registration_menu() -> Vec<day_spec::MenuItem> {
1872    let prefs = day_core::windows::preferences_action_id();
1873    if prefs == 0 {
1874        return Vec::new();
1875    }
1876    vec![day_spec::MenuItem::Action {
1877        id: None,
1878        action: prefs,
1879        label: String::new(),
1880        shortcut: None,
1881        enabled: true,
1882        checked: None,
1883        role: Some(day_spec::MenuRole::Preferences),
1884        icon: None,
1885    }]
1886}
1887
1888/// The app menu reduced to what the web can answer (docs/menus.md "Standard roles", the web
1889/// column). A role whose meaning is the window or the process (Quit, Minimize, Fullscreen,
1890/// New Window, Close Window) has nothing behind it in a browser tab, and a role that lowered
1891/// without a day action (About with no registration, Delete) would be a row that does nothing:
1892/// both are left out. Every other item keeps its action id, so the popover dispatches through
1893/// `day_dom_toolbar_action` exactly as a toolbar pull-down does. A role item lowered with an
1894/// empty label (day-core's injected Settings…/About) takes its catalog label here, as every
1895/// backend does. Settings… loses its ⌘, / Ctrl+, shortcut: the browser answers that key with its
1896/// own settings before the page sees it, so the hint would promise what the key never does.
1897/// Submenus left empty by the pruning go, and separators never lead, trail, or
1898/// double up.
1899fn web_menu_items(items: &[day_spec::MenuItem]) -> Vec<day_spec::MenuItem> {
1900    use day_spec::{MenuItem, MenuRole};
1901    let mut out: Vec<MenuItem> = Vec::new();
1902    for item in items {
1903        match item {
1904            MenuItem::Separator => {
1905                if !matches!(out.last(), None | Some(MenuItem::Separator)) {
1906                    out.push(MenuItem::Separator);
1907                }
1908            }
1909            MenuItem::Submenu { label, items, role } => {
1910                let items = web_menu_items(items);
1911                if !items.is_empty() {
1912                    out.push(MenuItem::Submenu {
1913                        label: label.clone(),
1914                        items,
1915                        role: *role,
1916                    });
1917                }
1918            }
1919            MenuItem::Action {
1920                role: Some(role),
1921                action,
1922                ..
1923            } if *action == 0
1924                || matches!(
1925                    role,
1926                    MenuRole::Quit
1927                        | MenuRole::Minimize
1928                        | MenuRole::Fullscreen
1929                        | MenuRole::NewWindow
1930                        | MenuRole::CloseWindow
1931                ) => {}
1932            MenuItem::Action { .. } => {
1933                let mut item = item.clone();
1934                if let MenuItem::Action {
1935                    label,
1936                    shortcut,
1937                    role: Some(role),
1938                    ..
1939                } = &mut item
1940                {
1941                    if label.is_empty() {
1942                        *label = day_localization::t(role_catalog_key(*role));
1943                    }
1944                    if *role == MenuRole::Preferences {
1945                        *shortcut = None;
1946                    }
1947                }
1948                out.push(item);
1949            }
1950        }
1951    }
1952    while matches!(out.last(), Some(MenuItem::Separator)) {
1953        out.pop();
1954    }
1955    out
1956}
1957
1958/// The core-catalog key for a standard menu command's label (docs/localization.md), the same
1959/// table the pieces layer resolves `menu_role` labels from.
1960fn role_catalog_key(role: day_spec::MenuRole) -> &'static str {
1961    use day_spec::MenuRole as R;
1962    match role {
1963        R::Cut => "day_cut",
1964        R::Copy => "day_copy",
1965        R::Paste => "day_paste",
1966        R::SelectAll => "day_select_all",
1967        R::Undo => "day_undo",
1968        R::Redo => "day_redo",
1969        R::Delete => "day_delete",
1970        R::About => "day_about",
1971        R::Quit => "day_quit",
1972        // The web says "Settings", like macOS, Windows and the phones (docs/settings.md);
1973        // "Preferences" is the GNOME/KDE word.
1974        R::Preferences => "day_settings",
1975        R::Minimize => "day_minimize",
1976        R::CloseWindow => "day_close",
1977        R::Fullscreen => "day_fullscreen",
1978        R::NewWindow => "day_new_window",
1979        R::CheckForUpdates => "day_check_for_updates",
1980    }
1981}
1982
1983/// A toolbar edit (docs/toolbars.md) as the shim's `day_dom_toolbar_edit` reads it: the ops in
1984/// order, each insert carrying its item.
1985fn toolbar_edit_json(ops: &[day_spec::ToolbarOp]) -> String {
1986    let mut json = String::from("{\"ops\":[");
1987    for (i, op) in ops.iter().enumerate() {
1988        if i > 0 {
1989            json.push(',');
1990        }
1991        match op {
1992            day_spec::ToolbarOp::Remove { id } => {
1993                json.push_str("{\"op\":\"remove\",\"id\":");
1994                json_str(&mut json, id);
1995                json.push('}');
1996            }
1997            day_spec::ToolbarOp::Insert { index, item } => {
1998                json.push_str("{\"op\":\"insert\",\"index\":");
1999                json.push_str(&index.to_string());
2000                json.push_str(",\"item\":");
2001                toolbar_item_json(&mut json, item);
2002                json.push('}');
2003            }
2004        }
2005    }
2006    json.push_str("]}");
2007    json
2008}
2009
2010fn toolbar_item_json(json: &mut String, it: &day_spec::ToolbarItem) {
2011    use day_spec::ToolbarItemKind as K;
2012    {
2013        let kind = match &it.kind {
2014            K::Button => "B",
2015            K::Toggle { .. } => "T",
2016            K::Menu { .. } => "M",
2017            K::Search { .. } => "F",
2018            K::Segmented { .. } => "G",
2019            K::Label => "L",
2020            K::Separator => "-",
2021        };
2022        json.push_str("{\"kind\":");
2023        json_str(json, kind);
2024        json.push_str(",\"id\":");
2025        json_str(json, &it.id);
2026        json.push_str(",\"label\":");
2027        json_str(json, &it.label);
2028        json.push_str(",\"tip\":");
2029        json_str(json, it.tooltip.as_deref().unwrap_or(&it.label));
2030        json.push_str(",\"action\":");
2031        json.push_str(&it.action.to_string());
2032        json.push_str(",\"enabled\":");
2033        json.push_str(if it.enabled { "true" } else { "false" });
2034        // Placement and column (docs/toolbars.md). Day draws this strip itself, so it can honor
2035        // both: the columns become three tracks whose widths follow the split's own panes, and
2036        // within each the roles pack leading, center and trailing.
2037        json.push_str(",\"place\":");
2038        json_str(
2039            json,
2040            match it.placement {
2041                day_spec::ToolbarPlacement::Navigation => "nav",
2042                day_spec::ToolbarPlacement::Principal => "mid",
2043                day_spec::ToolbarPlacement::Primary => "primary",
2044                day_spec::ToolbarPlacement::Secondary | day_spec::ToolbarPlacement::Bottom => {
2045                    "secondary"
2046                }
2047                day_spec::ToolbarPlacement::Automatic => "auto",
2048            },
2049        );
2050        json.push_str(",\"col\":");
2051        json_str(
2052            json,
2053            match it.column {
2054                day_spec::ToolbarColumn::Sidebar => "sidebar",
2055                day_spec::ToolbarColumn::List => "list",
2056                day_spec::ToolbarColumn::Detail | day_spec::ToolbarColumn::Window => "detail",
2057            },
2058        );
2059        if let K::Toggle { on } = it.kind {
2060            json.push_str(",\"on\":");
2061            json.push_str(if on { "true" } else { "false" });
2062        }
2063        if let K::Segmented { segments, selected } = &it.kind {
2064            json.push_str(",\"selected\":");
2065            json.push_str(&selected.to_string());
2066            json.push_str(",\"segments\":[");
2067            for (n, seg) in segments.iter().enumerate() {
2068                if n > 0 {
2069                    json.push(',');
2070                }
2071                json.push_str("{\"title\":");
2072                json_str(json, &seg.title);
2073                let ic = match &seg.icon {
2074                    Some(day_spec::Icon::Image(name)) => Some(image_url(name)),
2075                    Some(day_spec::Icon::Symbol(sym)) => symbol_svg(*sym),
2076                    None => None,
2077                };
2078                if let Some(url) = ic {
2079                    json.push_str(",\"icon\":");
2080                    json_str(json, &url);
2081                }
2082                json.push('}');
2083            }
2084            json.push(']');
2085        }
2086        if let K::Menu { items } = &it.kind {
2087            json.push_str(",\"menu\":");
2088            menu_items_json(json, items);
2089        }
2090        if let K::Search {
2091            text,
2092            placeholder,
2093            suggestions,
2094        } = &it.kind
2095        {
2096            json.push_str(",\"text\":");
2097            json_str(json, text.as_str());
2098            json.push_str(",\"placeholder\":");
2099            json_str(json, placeholder.as_str());
2100            // A native <datalist>, so the browser draws the completion popup.
2101            json.push_str(",\"suggestions\":[");
2102            for (n, sug) in suggestions.iter().enumerate() {
2103                if n > 0 {
2104                    json.push(',');
2105                }
2106                json_str(json, sug);
2107            }
2108            json.push(']');
2109        }
2110        // A bundled image crosses as a staged URL; a standard symbol as an inline-SVG data URL
2111        // (`symbol_svg`). Both reach the shim as one `icon` field and draw through the same CSS
2112        // mask, so a bar mixing the two looks like one bar.
2113        let icon = match &it.icon {
2114            Some(day_spec::Icon::Image(name)) => Some(image_url(name)),
2115            Some(day_spec::Icon::Symbol(s)) => symbol_svg(*s),
2116            // The sidebar toggle carries no icon from the app — every other toolkit draws its
2117            // own platform glyph for it (docs/toolbars.md). The web has none to draw, so it takes
2118            // the standard one here rather than being the one item in the bar showing bare text.
2119            None => None,
2120        };
2121        if let Some(url) = icon {
2122            json.push_str(",\"icon\":");
2123            json_str(json, &url);
2124        }
2125        json.push('}');
2126    }
2127}
2128
2129fn json_str(out: &mut String, v: &str) {
2130    use std::fmt::Write as _;
2131    out.push('"');
2132    for ch in v.chars() {
2133        match ch {
2134            '"' => out.push_str("\\\""),
2135            '\\' => out.push_str("\\\\"),
2136            '\n' => out.push_str("\\n"),
2137            '\r' => out.push_str("\\r"),
2138            '\t' => out.push_str("\\t"),
2139            c if (c as u32) < 0x20 => {
2140                let _ = write!(out, "\\u{:04x}", c as u32);
2141            }
2142            c => out.push(c),
2143        }
2144    }
2145    out.push('"');
2146}
2147
2148// ---------------------------------------------------------------------------
2149// The toolkit
2150// ---------------------------------------------------------------------------
2151
2152thread_local! {
2153    /// Renderers registered by external Day Piece crates (§8.2, docs/extending.md).
2154    ///
2155    /// Every other backend exposes this seam as a `linkme` distributed slice populated at link
2156    /// time. **That mechanism does not exist on wasm** — `#[distributed_slice]` fails to compile
2157    /// for `wasm32-unknown-unknown` with "distributed_slice is not implemented for this platform"
2158    /// (checked against linkme 0.3.37) — so web-dom registers at RUNTIME instead, and a piece
2159    /// self-registers the first time its constructor runs. That happens before its node is
2160    /// realized, so the renderer is always in place by the time it is needed.
2161    ///
2162    /// Without this seam a piece could not render on the web at all: `realize` receives `&dyn Any`
2163    /// props whose concrete type lives in the piece crate, so only the piece itself can downcast
2164    /// them — day-toolkit-dom cannot special-case a piece it does not (and must not) depend on.
2165    static REGISTRY: RefCell<Registry<Dom>> = RefCell::new(Registry::default());
2166}
2167
2168/// Register an external piece's web renderer. Idempotent: a piece calls this from its constructor,
2169/// which may run many times.
2170pub fn register_renderer(make: fn() -> Renderer<Dom>) {
2171    REGISTRY.with(|r| {
2172        let mut r = r.borrow_mut();
2173        let renderer = make();
2174        if r.get(renderer.kind).is_none() {
2175            r.register(renderer);
2176        }
2177    });
2178}
2179
2180/// Look up a registered renderer's `make`/`update`/`measure`, if any.
2181fn registered<T>(kind: PieceKind, f: impl FnOnce(&Renderer<Dom>) -> T) -> Option<T> {
2182    REGISTRY.with(|r| r.borrow().get(kind).map(f))
2183}
2184
2185pub struct Dom {
2186    root: u32,
2187}
2188
2189impl Dom {
2190    #[allow(clippy::new_without_default)]
2191    #[must_use]
2192    pub fn new() -> Self {
2193        controls::register();
2194        // The two launch overrides a process environment would carry (docs/accessibility.md),
2195        // read from the page's query string instead.
2196        #[cfg(target_arch = "wasm32")]
2197        day_core::testing::init_fast_animations(
2198            host_env("DAY_TEST_FAST").as_deref() == Some("1")
2199                || host_env("DAY_REDUCE_MOTION").as_deref() == Some("1"),
2200        );
2201        #[cfg(target_arch = "wasm32")]
2202        day_core::init_presentation_mode(
2203            if host_env("DAY_TEST_DIALOGS").as_deref() == Some("scripted") {
2204                day_core::PresentationMode::Scripted
2205            } else {
2206                day_core::PresentationMode::Native
2207            },
2208        );
2209        Dom { root: 1 }
2210    }
2211
2212    /// Create a DOM element of `tag` for a piece renderer, returning its handle.
2213    ///
2214    /// The public helper surface a `lib-dom.rs` builds on: piece crates cannot reach day-toolkit-dom's
2215    /// private shim imports, so element creation, attributes and method calls go through these.
2216    pub fn element(&mut self, tag: &str) -> DomHandle {
2217        DomHandle(unsafe { day_dom_create_tag(tag.as_ptr(), tag.len()) })
2218    }
2219
2220    /// Set an attribute. The boolean-attribute convention applies: `""` removes, `"-"` sets
2221    /// (see the shim's `day_dom_set_attr`).
2222    pub fn set_attr(&mut self, h: &DomHandle, name: &str, value: &str) {
2223        attr(h.0, name, value);
2224    }
2225
2226    /// Call a zero-argument method on the element (`play`, `pause`, `load`, …).
2227    pub fn call(&mut self, h: &DomHandle, method: &str) {
2228        unsafe { day_dom_call(h.0, method.as_ptr(), method.len()) };
2229    }
2230
2231    /// Replace the element's markup, KEEPING the caret and the selection where they were
2232    /// (docs/texteditor.md) — which is what lets a styled-text editor repaint its attributes on
2233    /// every keystroke without fighting the user.
2234    ///
2235    /// `html` must come from Day's own serializer ([`day_spec::styled_to_html`]), which escapes
2236    /// every character of app text; this is not a hole to hand arbitrary markup through.
2237    pub fn set_html(&mut self, h: &DomHandle, html: &str) {
2238        unsafe { day_dom_set_html(h.0, html.as_ptr(), html.len()) };
2239    }
2240
2241    /// Select a BYTE range of a contenteditable element's flattened text — the same offsets
2242    /// [`listen::EDITABLE`] reports.
2243    pub fn set_editor_selection(&mut self, h: &DomHandle, start: usize, end: usize) {
2244        unsafe { day_dom_editor_select(h.0, start as u32, end as u32) };
2245    }
2246
2247    /// Insert `text` at a BYTE offset of a contenteditable element's flattened text, as typing
2248    /// would: through the browser's editing command, so its undo stack records the insertion
2249    /// and the element's `input` event reports the result (docs/texteditor.md).
2250    pub fn insert_editor_text(&mut self, h: &DomHandle, at: usize, text: &str) {
2251        unsafe { day_dom_editor_insert(h.0, at as u32, text.as_ptr(), text.len()) };
2252    }
2253
2254    /// Attach the shim's DOM listeners to a piece's element, so it can report back.
2255    ///
2256    /// The built-in kinds get this from their own `realize` arms; a piece renderer that needs
2257    /// events (`day-piece-colorpicker`'s `<input type="color">`) asks here, with a mask built
2258    /// from [`listen`]'s constants. The element the piece's `make` returned is already bound to
2259    /// its `NodeId`, so what the shim reports arrives at the piece's `cx.on` as the ordinary
2260    /// [`Event`] for that bit — `listen::INPUT` on an `<input>` becomes `Event::TextChanged`.
2261    ///
2262    /// Idempotent it is NOT: each call adds listeners, so call it once, from `make`.
2263    pub fn listen(&mut self, h: &DomHandle, mask: u32) {
2264        unsafe { day_dom_listen(h.0, mask) };
2265    }
2266}
2267
2268/// Listener bits for [`Dom::listen`] — which DOM events the shim wires to a piece's element, and
2269/// the [`Event`] each becomes. The numbers are the shim's own table (`listen(id, mask)` in
2270/// `shim.js`); naming them keeps a piece from passing a magic constant that silently means
2271/// something else after a shim change.
2272pub mod listen {
2273    // Nothing here names `Event` in code — the import is what makes the `[`Event::…`]` links in
2274    // the constants' docs below resolve to day-spec's type instead of rendering as plain text.
2275    #[allow(unused_imports)]
2276    use day_spec::Event;
2277    /// `click` → [`Event::Pressed`].
2278    pub const CLICK: u32 = 1;
2279    /// `input` → [`Event::TextChanged`] with the element's value (or [`Event::ValueChanged`] on a
2280    /// `type="range"`).
2281    pub const INPUT: u32 = 2;
2282    /// `change` → [`Event::ToggleChanged`] on a checkbox, [`Event::SelectionChanged`] on a
2283    /// `<select>`, [`Event::ValueCommitted`] on a range.
2284    pub const CHANGE: u32 = 4;
2285    /// `focus`/`blur` → [`Event::FocusChanged`].
2286    pub const FOCUS: u32 = 8;
2287    /// Enter `keydown` → [`Event::Submitted`].
2288    pub const SUBMIT: u32 = 16;
2289    /// A `ResizeObserver` → [`Event::FrameChanged`].
2290    pub const RESIZE: u32 = 32;
2291    /// `scroll` → [`Event::ScrollChanged`].
2292    pub const SCROLL: u32 = 64;
2293    /// A press released within the slop → [`Event::Tap`] (at the press point, on release —
2294    /// the shim's recognizer, matching the native toolkits).
2295    pub const POINTER: u32 = 128;
2296    /// The pointer-capture trio → [`Event::Drag`].
2297    pub const DRAG: u32 = 256;
2298    /// A `contenteditable` element's editing listeners (docs/texteditor.md): `input` (and an IME
2299    /// `compositionend`) → [`Event::TextChanged`] carrying the FLATTENED text, and
2300    /// `selectionchange` → [`Event::Custom`] carrying `"sel <start> <end>"` in byte offsets.
2301    pub const EDITABLE: u32 = 512;
2302}
2303
2304impl Toolkit for Dom {
2305    type Handle = DomHandle;
2306
2307    /// `navigator.setAppBadge(n)` / `clearAppBadge()`. A dot is the no-argument form, which is why
2308    /// the count is encoded: negative clears, zero means "dot", positive is the number.
2309    fn set_app_badge(&mut self, badge: &day_spec::AppBadge) {
2310        use day_spec::AppBadge;
2311        let encoded: i32 = match badge {
2312            AppBadge::None | AppBadge::Count(0) => -1,
2313            AppBadge::Count(n) => (*n).min(i32::MAX as u32) as i32,
2314            AppBadge::Dot => 0,
2315            // No text badge on the web; clearing would be worse than leaving the last value, so
2316            // this is the one payload the arm ignores outright.
2317            AppBadge::Text(_) => return,
2318        };
2319        unsafe { day_dom_set_app_badge(encoded) };
2320    }
2321
2322    /// The page's one window: fullscreen through the Fullscreen API, Normal by leaving it.
2323    /// Minimize and maximize are not the page's to ask for, so they are declined at once by
2324    /// reporting the state the page is in. Content protection has no web mechanism.
2325    fn apply_window(&mut self, _host: &DomHandle, change: &day_spec::WindowChange) {
2326        use day_spec::{WindowChange, WindowState};
2327        let state = match change {
2328            WindowChange::State(state) => state,
2329            // The page is the app's one window, so its own appearance is the page's: the
2330            // override replaces the app-wide one until it is cleared.
2331            WindowChange::Appearance(dark) => {
2332                APPEARANCE.with(|a| a.set((a.get().0, *dark)));
2333                apply_appearance();
2334                // day-core's dark signal re-reads `dark_mode()`, which needs the tree this call
2335                // is borrowed from: one hop later.
2336                post_local(day_core::note_appearance_changed);
2337                return;
2338            }
2339            // A page cannot move, resize, restack, hide or flash the browser window: `moveTo`
2340            // and `resizeTo` work only on popups the script opened.
2341            _ => return,
2342        };
2343        let answer = match state {
2344            WindowState::Fullscreen => unsafe { day_dom_set_fullscreen(1) },
2345            WindowState::Normal => unsafe { day_dom_set_fullscreen(0) },
2346            WindowState::Minimized | WindowState::Maximized => {
2347                WINDOW_STATE.with(std::cell::Cell::get).code()
2348            }
2349        };
2350        // -1: the browser has the request; `fullscreenchange` or the rejection reports back.
2351        if answer >= 0 {
2352            report_window_state(WindowState::from_code(answer), true);
2353        }
2354    }
2355
2356    /// `app-region: drag` on the element and `no-drag` on the controls inside it, through the
2357    /// rules `day_dom_window_chrome` installed. Live only in an installed app's window-controls
2358    /// overlay, where Chromium moves the window and maximizes it on a double click.
2359    /// `screenX`/`screenY`/`outerWidth`/`outerHeight`: the browser window's outer frame on the
2360    /// desktop, in CSS px (points at 100% zoom).
2361    fn window_frame(&self, _host: &DomHandle) -> Option<Rect> {
2362        let mut f = [0f64; 4];
2363        let ok = unsafe { day_dom_window_frame(f.as_mut_ptr()) } != 0;
2364        (ok && f[2] > 0.0 && f[3] > 0.0).then(|| Rect::new(f[0], f[1], f[2], f[3]))
2365    }
2366
2367    /// The one screen the page is on, from `window.screen`. The Window Management API would
2368    /// list them all, but only asynchronously and behind a permission prompt.
2369    fn monitors(&self) -> Vec<day_spec::Monitor> {
2370        let mut v = [0f64; 9];
2371        unsafe { day_dom_screen(v.as_mut_ptr()) };
2372        if v[2] <= 0.0 || v[3] <= 0.0 {
2373            return Vec::new();
2374        }
2375        vec![day_spec::Monitor {
2376            id: "0".into(),
2377            name: String::new(),
2378            frame: Rect::new(v[0], v[1], v[2], v[3]),
2379            work_area: Rect::new(v[4], v[5], v[6], v[7]),
2380            scale: if v[8] > 0.0 { v[8] } else { 1.0 },
2381            primary: true,
2382        }]
2383    }
2384
2385    fn set_drag_region(&mut self, h: &DomHandle, drag: bool) {
2386        class(h.0, "day-drag-region", drag);
2387        if drag {
2388            unsafe { day_dom_takes_pointer(h.0) };
2389        }
2390    }
2391
2392    fn set_drag_source(&mut self, h: &DomHandle, source: day_spec::transfer::Source) {
2393        transfer::source(h.0, source);
2394    }
2395    fn set_drop_target(&mut self, h: &DomHandle, target: day_spec::transfer::Target) {
2396        transfer::target(h.0, target);
2397    }
2398
2399    fn set_presented(&mut self, handle: &Self::Handle, visible: bool) {
2400        attr(
2401            handle.0,
2402            "data-day-presented",
2403            if visible { "true" } else { "false" },
2404        );
2405    }
2406
2407    #[expect(
2408        clippy::match_same_arms,
2409        reason = "one arm per capability, each documented with the browser mechanism behind it"
2410    )]
2411    fn capability(&self, cap: Cap) -> Support {
2412        match cap {
2413            Cap::SearchField => Support::Native,
2414            Cap::ComboBox => Support::Native,
2415            Cap::Stepper => Support::Emulated,
2416            Cap::DateTimePicker => Support::Native,
2417            Cap::ColorPicker => Support::Native,
2418            Cap::PullRefresh => Support::Emulated,
2419            Cap::Pager => Support::Emulated,
2420            Cap::PullRefreshGesture => Support::Unsupported,
2421            // `requestFullscreen` on the document element. A page in an iframe without
2422            // `allow="fullscreen"`, and Safari on iPhone, have no element fullscreen, which
2423            // `document.fullscreenEnabled` says. The browser grants the request only during a
2424            // user gesture; a button action runs inside the click handler, so a press qualifies,
2425            // and a refused request reads back as the state the page kept.
2426            Cap::WindowFullscreen => {
2427                if fullscreen_enabled() {
2428                    Support::Native
2429                } else {
2430                    Support::Unsupported
2431                }
2432            }
2433            // A page cannot minimize or zoom the browser window, and nothing keeps it out of a
2434            // screenshot or a shared tab.
2435            Cap::WindowStates | Cap::ContentProtection => Support::Unsupported,
2436            // Window Controls Overlay (docs/window-chrome.md): only an installed Chromium app on
2437            // the desktop, and only once the user hides its title bar, runs content under the
2438            // overlay and honors `app-region: drag`. Emulated where the API exists at all.
2439            Cap::OverlayTitleBar | Cap::DragRegion => {
2440                if window_controls_overlay() {
2441                    Support::Emulated
2442                } else {
2443                    Support::Unsupported
2444                }
2445            }
2446            // The browser owns the window's frame and what is behind it.
2447            Cap::FramelessWindow | Cap::TransparentWindow | Cap::WindowMaterial => {
2448                Support::Unsupported
2449            }
2450            // `window.screen`: the one screen the page is on.
2451            Cap::Monitors => Support::Emulated,
2452            // The page is the app's one window, so its appearance is the app's: the override
2453            // goes through the same path as `set_appearance`.
2454            Cap::WindowAppearance => Support::Emulated,
2455            // Browsers resize and move only the popups a script opened; nothing stacks a tab
2456            // above other apps or flashes it. The manifest's `shortcuts` are static: day-cli
2457            // writes the Day.toml ones, and a page cannot add any while it runs.
2458            Cap::WindowGeometry
2459            | Cap::WindowPosition
2460            | Cap::WindowLevel
2461            | Cap::RequestAttention
2462            | Cap::DynamicShortcuts => Support::Unsupported,
2463            // Composed, not read: the CSS generic families plus the bundled `document.fonts`
2464            // faces. A browser lists local fonts only through `queryLocalFonts()` — Chromium
2465            // only, asynchronous, behind a permission prompt — so the list is what CSS can
2466            // name for certain (docs/fonts.md).
2467            Cap::FontList => Support::Emulated,
2468            // An inline `cursor` style per element (docs/cursor.md); a coarse pointer never shows it.
2469            Cap::Cursor | Cap::DragDrop | Cap::DragExternalImport | Cap::DragMultipleItems => {
2470                Support::Native
2471            }
2472            // A statement about the toolkit, not about the current window: web-dom can always
2473            // draw two panes. Whether a given host does follows from the window's size class,
2474            // which `run`/`day_dom_resized` report and the pieces layer resolves against
2475            // (docs/size-classes.md).
2476            Cap::NavSplit => Support::Native,
2477            // A re-present is a DOM re-home: the shim rebuilds the host's chrome and the page
2478            // elements move between containers intact, keeping their subtrees, scroll offsets,
2479            // and focus (docs/size-classes.md).
2480            Cap::NavRepresent => Support::Native,
2481            // Composed rather than a native tab widget — the browser ships none — but a tab
2482            // bar all the same: the same `NAV_MENU` element the sidebar uses, laid out
2483            // horizontally in the chrome slot (docs/navigation.md).
2484            Cap::NavTabs => Support::Emulated,
2485            // A browser window ranges from a phone to a desktop, which is exactly the case
2486            // adaptive navigation exists for — so unlike the desktop toolkits, web-dom does
2487            // grow a tab bar as the viewport narrows (docs/navigation.md).
2488            Cap::NavTabsAdaptive => Support::Emulated,
2489            Cap::Appearance | Cap::Dialogs | Cap::Animation => Support::Native,
2490            // The `prefers-reduced-motion` media query, read and watched by the shim
2491            // (docs/accessibility.md).
2492            Cap::ReduceMotion => Support::Native,
2493            // `createImageBitmap` decodes every format the engine reads; a canvas writes back
2494            // PNG/JPEG/WebP (docs/images.md). `Cap::ImageProperties` is deliberately NOT here:
2495            // the browser exposes no metadata reader, and an empty struct would read as "this
2496            // file records nothing" rather than "nobody looked".
2497            Cap::ImageDecode | Cap::ImageEncode => Support::Native,
2498            // A drawing exports through the on-screen painter into a detached `<canvas>`, kept
2499            // as an `ImageBitmap` (docs/canvas.md "Exporting"). No PDF: a browser writes none.
2500            Cap::CanvasBitmap => Support::Native,
2501            // The browser's file input and download are its file dialogs; bytes ride the
2502            // `web_files` store instead of a filesystem (docs/files.md).
2503            Cap::FileDialogs => Support::Native,
2504            // The browser's own clipboard events (⌘X/C/V) are the native edit route; the
2505            // shim's document listeners forward them when no editable element claims them
2506            // (docs/menus.md).
2507            Cap::EditBridge => Support::Native,
2508            // Exact metrics from a canvas TextMetrics, but derived rather than read off a
2509            // baseline the platform publishes (docs/baseline.md).
2510            Cap::BaselineAlignment => Support::Emulated,
2511            // Runs are `<span>` children; a link run is an `<a>`, whose click the shim cancels
2512            // and reports so the app's `.on_link()` decides (docs/text-runs.md).
2513            Cap::TextRuns | Cap::TextLinks => Support::Native,
2514            // A strip docked above the app root, not window chrome the OS draws — a browser tab
2515            // has no title bar to hang one on. Emulated is the honest answer, and it is enough
2516            // for an app to decide the commands belong in the bar rather than in the content
2517            // (docs/toolbars.md).
2518            Cap::Toolbar | Cap::ToolbarSearch => Support::Emulated,
2519            // The app menu is a pull-down on that same strip, presented by the shim's popover
2520            // rather than a menu bar the browser has no way to draw (docs/menus.md). Emulated
2521            // says the commands are reachable, which is what an app probing the capability
2522            // wants to know before it duplicates Settings… or About somewhere in its content.
2523            Cap::AppMenu => Support::Emulated,
2524            // The Badging API takes a number or, with no argument, a dot. Emulated rather than
2525            // Native because whether anything is DRAWN depends on the browser and on the page
2526            // being an installed app — the call itself always succeeds (docs/badge.md).
2527            Cap::AppBadgeCount | Cap::AppBadgeDot => Support::Emulated,
2528            // An ARIA live region the shim owns, not an announcement request: the browser
2529            // has none (docs/accessibility.md).
2530            Cap::Announce => Support::Emulated,
2531            Cap::TextEditable | Cap::TextSelectable | Cap::TextSpellCheck => Support::Native,
2532            Cap::ListRecycling => Support::Emulated,
2533            // The rows are absolutely framed, so a header row cannot be `position: sticky`
2534            // itself: the host keeps one extra cell in a sticky strip at the top of the list
2535            // and binds the current section's header into it (docs/list.md "Sections").
2536            Cap::ListSections => Support::Emulated,
2537            // The COMPOSED tree (docs/tree.md M2): the piece flattens onto the emulated
2538            // list; disclosure, indentation, and row menus are day pieces. No native drag,
2539            // so `Cap::TreeMove` stays Unsupported.
2540            Cap::Tree | Cap::TreeSections => Support::Emulated,
2541            // Pointer-tracked drag with a CSS gap — the browser has no native list reorder.
2542            Cap::NavReorder | Cap::ListReorder => Support::Emulated,
2543            // A topmost fixed-position child — not a system modal (docs/cover.md).
2544            Cap::Cover => Support::Emulated,
2545            // A `tabindex` stop with the key route, focused by a press in the capture phase,
2546            // `:focus-visible` for the ring (docs/focus.md).
2547            Cap::Focusable => Support::Native,
2548            // `KeyboardEvent.repeat` and `keyup` (docs/menus.md "Keys").
2549            Cap::KeyPhases => Support::Native,
2550            // A grown pseudo-element, or a forwarding sibling where the element has none
2551            // (docs/gestures.md "Hit slop").
2552            Cap::HitSlop => Support::Native,
2553            // The document's `selectionchange`, mapped to the label's text (docs/text.md).
2554            Cap::LabelSelection => Support::Native,
2555            // The list reports its visible rows and end distance from its own row table on
2556            // every scroll, resize and data change, and scrolls rows to any alignment with the
2557            // browser's own smooth scrolling (docs/list.md).
2558            Cap::ListViewport | Cap::ListScrollAlign => Support::Native,
2559            // A list scroll under a finger, with the scroll bar held, or right after a wheel or
2560            // a key that scrolls is the reader's; `scrollTo` comes with none (docs/list.md
2561            // "Following the end").
2562            Cap::ListReaderScroll => Support::Native,
2563            // A scroll view reports its offset per frame and at rest, and the user's phases from
2564            // touch, wheel, keyboard and scroll-bar input with `scrollend` (docs/scroll.md).
2565            Cap::ScrollOffset | Cap::ScrollPhases => Support::Native,
2566            // CSS scroll snap on markers at each stop (`scroll-snap-type: mandatory`).
2567            Cap::ScrollSnap => Support::Native,
2568            // Blurring the field dismisses a touch screen's keyboard: the scroll piece resigns
2569            // focus when a drag begins. A desktop browser has no software keyboard.
2570            Cap::ScrollKeyboardDismiss => {
2571                if unsafe { day_dom_touch_points() } > 0 {
2572                    Support::Emulated
2573                } else {
2574                    Support::Unsupported
2575                }
2576            }
2577            _ => Support::Unsupported,
2578        }
2579    }
2580
2581    fn realize(&mut self, kind: PieceKind, props: &dyn std::any::Any, id: NodeId) -> DomHandle {
2582        let el = match Builtin::from_key(kind) {
2583            Some(Builtin::Container) => {
2584                // Here and in every arm below: a props-type mismatch degrades to the visible
2585                // placeholder label (`props_of` reported it) instead of panicking out of the
2586                // wasm export that drove this realize.
2587                let Some(p) = day_spec::props_of::<ContainerProps>(kind, "web-dom", props) else {
2588                    return realize_placeholder(kind, id);
2589                };
2590                let el = unsafe { day_dom_create(EL_DIV) };
2591                if let Some(role) = p.role {
2592                    SURFACE_ROLES.with(|t| t.insert(el as usize, role));
2593                }
2594                apply_surface(el, p, p.role, None, true);
2595                // Pass-through until something listens (docs/gestures.md "Pass-through").
2596                class(el, "day-passive-host", true);
2597                el
2598            }
2599            Some(Builtin::Label) => {
2600                let Some(p) = day_spec::props_of::<LabelProps>(kind, "web-dom", props) else {
2601                    return realize_placeholder(kind, id);
2602                };
2603                let el = unsafe { day_dom_create(EL_LABEL) };
2604                class(el, "day-passive-leaf", true);
2605                set_label_text(el, &p.text, &p.runs);
2606                apply_font(el, &p.font);
2607                if let Some(c) = p.color {
2608                    s(el, "color", &ink_css(c));
2609                } else if p.role == day_spec::props::TextRole::Secondary {
2610                    // No system "secondary label" on the web, so it is derived from the text color
2611                    // in force — which is what the light/dark switch already drives. Mixing toward
2612                    // transparent rather than naming a grey is what keeps it correct on both.
2613                    s(
2614                        el,
2615                        "color",
2616                        "color-mix(in srgb, currentColor 62%, transparent)",
2617                    );
2618                }
2619                if !p.wraps {
2620                    s(el, "white-space", "nowrap");
2621                    s(el, "overflow", "hidden");
2622                    s(el, "text-overflow", "ellipsis");
2623                }
2624                // `start`/`end` rather than `left`/`right`, so an RTL locale follows the writing
2625                // direction without the app asking (docs/localization.md).
2626                match p.align {
2627                    day_spec::props::TextAlign::Leading => {}
2628                    // Every line but the last stretched edge to edge; the last at the start.
2629                    day_spec::props::TextAlign::Justified => s(el, "text-align", "justify"),
2630                    day_spec::props::TextAlign::Center => s(el, "text-align", "center"),
2631                    day_spec::props::TextAlign::Trailing => s(el, "text-align", "end"),
2632                }
2633                LABELS.with(|t| {
2634                    t.borrow_mut().insert(
2635                        el,
2636                        LabelState {
2637                            text: p.text.clone(),
2638                            runs: !p.runs.is_empty(),
2639                            wraps: p.wraps,
2640                            para: p.paragraph(),
2641                            width: 0.0,
2642                            elided: false,
2643                            selected: false,
2644                        },
2645                    );
2646                });
2647                apply_paragraph(el);
2648                // Selection reports (docs/text.md "Selection"): the shim's `selectionchange`
2649                // route reports ranges inside elements carrying this flag.
2650                if p.reports_selection {
2651                    attr(el, "data-day-reports-selection", "true");
2652                }
2653                el
2654            }
2655            Some(Builtin::Button) => {
2656                let Some(p) = day_spec::props_of::<ButtonProps>(kind, "web-dom", props) else {
2657                    return realize_placeholder(kind, id);
2658                };
2659                let el = unsafe { day_dom_create(EL_BUTTON) };
2660                if p.icon.is_some() {
2661                    apply_button_content(el, &p.title, p.icon.as_ref(), p.icon_only);
2662                } else {
2663                    text(el, &p.title);
2664                }
2665                apply_button_style(el, p.style);
2666                set_button_selected(el, p.selected);
2667                if !p.enabled {
2668                    attr(el, "disabled", "-");
2669                }
2670                unsafe { day_dom_listen(el, 1) };
2671                el
2672            }
2673            Some(Builtin::Toggle) => {
2674                let Some(p) = day_spec::props_of::<ToggleProps>(kind, "web-dom", props) else {
2675                    return realize_placeholder(kind, id);
2676                };
2677                let el = unsafe { day_dom_create(EL_TOGGLE) };
2678                unsafe { day_dom_set_checked(el, u32::from(p.on)) };
2679                if !p.enabled {
2680                    attr(el, "disabled", "-");
2681                }
2682                unsafe { day_dom_listen(el, 4) };
2683                el
2684            }
2685            Some(Builtin::Slider) => {
2686                let Some(p) = day_spec::props_of::<SliderProps>(kind, "web-dom", props) else {
2687                    return realize_placeholder(kind, id);
2688                };
2689                let el = unsafe { day_dom_create(EL_SLIDER) };
2690                attr(el, "min", &p.min.to_string());
2691                attr(el, "max", &p.max.to_string());
2692                attr(el, "step", &p.step.map_or("any".into(), |s| s.to_string()));
2693                unsafe { day_dom_set_value(el, p.value) };
2694                if !p.enabled {
2695                    attr(el, "disabled", "-");
2696                }
2697                // 2 = `input` (live, every motion) | 4 = `change` (settled, on release) — the
2698                // two facts a drag produces, which the DOM already separates for us.
2699                unsafe { day_dom_listen(el, 2 | 4) };
2700                el
2701            }
2702            Some(Builtin::TextField) => {
2703                let Some(p) = day_spec::props_of::<TextFieldProps>(kind, "web-dom", props) else {
2704                    return realize_placeholder(kind, id);
2705                };
2706                let el = unsafe { day_dom_create(EL_FIELD) };
2707                attr(el, "value", &p.text);
2708                attr(el, "placeholder", &p.placeholder);
2709                if !p.enabled {
2710                    attr(el, "disabled", "-");
2711                }
2712                unsafe { day_dom_listen(el, 2 | 8 | 16) };
2713                el
2714            }
2715            Some(Builtin::TextArea) => {
2716                let Some(p) = day_spec::props_of::<TextAreaProps>(kind, "web-dom", props) else {
2717                    return realize_placeholder(kind, id);
2718                };
2719                let el = unsafe { day_dom_create(EL_AREA) };
2720                text(el, &p.text);
2721                attr(el, "placeholder", &p.placeholder);
2722                apply_area_attrs(el, p.editable, p.selectable, p.spellcheck);
2723                AREA_HINTS.with(|m| {
2724                    m.borrow_mut()
2725                        .insert(el, (p.min_lines, p.max_lines, content_lines(&p.text)))
2726                });
2727                unsafe { day_dom_listen(el, 2 | 8) };
2728                el
2729            }
2730            Some(Builtin::Picker) => {
2731                let Some(p) = day_spec::props_of::<PickerProps>(kind, "web-dom", props) else {
2732                    return realize_placeholder(kind, id);
2733                };
2734                realize_picker(p)
2735            }
2736            Some(Builtin::Progress) => {
2737                let Some(p) = day_spec::props_of::<ProgressProps>(kind, "web-dom", props) else {
2738                    return realize_placeholder(kind, id);
2739                };
2740                let el = unsafe {
2741                    day_dom_create(if p.value.is_some() {
2742                        EL_PROGRESS
2743                    } else {
2744                        EL_SPINNER
2745                    })
2746                };
2747                if let Some(v) = p.value {
2748                    attr(el, "max", "1");
2749                    unsafe { day_dom_set_value(el, v) };
2750                } else {
2751                    // Which of the two this element is, is only knowable here — both render with
2752                    // no text, so `measure` cannot tell them apart from the DOM.
2753                    SPINNERS.with(|s| s.borrow_mut().insert(el, if p.large { 48.0 } else { 22.0 }));
2754                    attr(
2755                        el,
2756                        "data-day-animating",
2757                        if p.animating { "true" } else { "false" },
2758                    );
2759                    if p.large {
2760                        s(el, "width", "48px");
2761                        s(el, "height", "48px");
2762                    }
2763                }
2764                el
2765            }
2766            Some(Builtin::Image) => {
2767                let Some(p) = day_spec::props_of::<ImageProps>(kind, "web-dom", props) else {
2768                    return realize_placeholder(kind, id);
2769                };
2770                // Bytes and shared decodes arrive through `decode_image` (docs/images.md); this
2771                // arm is the staged-asset path, unchanged — including the one backend quirk that
2772                // a slash-carrying name is passed straight through as a URL.
2773                let named = match &p.source {
2774                    day_spec::ImageSource::Named(name) => name.clone(),
2775                    _ => String::new(),
2776                };
2777                // Empty for bytes and shared decodes: the shim owns their URL (a blob), and
2778                // sets it on the element itself, mask or `<img>`.
2779                let src = if named.is_empty() {
2780                    String::new()
2781                } else if named.contains('/') {
2782                    named.clone()
2783                } else {
2784                    format!("assets/images/{}.{}", named, image_ext(&named))
2785                };
2786                let fit = match p.content_mode {
2787                    ContentMode::Fit => "contain",
2788                    ContentMode::Fill => "cover",
2789                    ContentMode::Stretch => "fill",
2790                };
2791                // A TINTED or TEMPLATE glyph is a masked div, not an `<img>`: the browser
2792                // cannot recolor an image's pixels, and an `<img>` paints its own art over
2793                // whatever sits behind it, so masking one only clips it — the tint shows through
2794                // as a faint edge. Painting the mask with the tint (or `currentColor` for a
2795                // template) is what the nav rows do, and it is the only technique here that
2796                // actually recolors (docs/vectors.md "Tint").
2797                let state = ImageState {
2798                    src: src.clone(),
2799                    fit,
2800                    tint: p.tint,
2801                    template: p.template,
2802                    is_img: p.tint.is_none() && !p.template,
2803                };
2804                let el = unsafe { day_dom_create(if state.masked() { EL_DIV } else { EL_IMAGE }) };
2805                if state.masked() {
2806                    if !p.decorative {
2807                        attr(el, "role", "img");
2808                    }
2809                    // A mask cut from bytes the app holds (a `Symbol`'s outline SVG, a settings
2810                    // row's glyph, a tinted photo) or from a shared decode: the shim makes or
2811                    // finds the blob URL and sets it as this div's mask, since a URL is the
2812                    // one thing a mask can be cut from.
2813                    match &p.source {
2814                        day_spec::ImageSource::Named(_) => {}
2815                        day_spec::ImageSource::Bytes(b) => unsafe {
2816                            day_dom_image_set_bytes(el, b.as_ptr(), b.len());
2817                        },
2818                        day_spec::ImageSource::Decoded(id) => unsafe {
2819                            day_dom_image_set_bitmap(el, id.0 as f64);
2820                        },
2821                    }
2822                } else {
2823                    // Bytes and shared decodes never name a file (docs/images.md): the shim owns
2824                    // a blob URL for them, and setting the staged `src` first would fire a
2825                    // request for an asset that does not exist.
2826                    match &p.source {
2827                        day_spec::ImageSource::Named(_) => attr(el, "src", &src),
2828                        day_spec::ImageSource::Bytes(b) => unsafe {
2829                            day_dom_image_set_bytes(el, b.as_ptr(), b.len());
2830                        },
2831                        day_spec::ImageSource::Decoded(id) => unsafe {
2832                            day_dom_image_set_bitmap(el, id.0 as f64);
2833                        },
2834                    }
2835                    s(el, "object-fit", fit);
2836                    if p.decorative {
2837                        attr(el, "alt", "");
2838                    }
2839                }
2840                if p.decorative {
2841                    attr(el, "aria-hidden", "true");
2842                }
2843                if state.masked() {
2844                    apply_image_tint(el, &state);
2845                }
2846                IMAGE_SRC.with(|m| m.borrow_mut().insert(el, state));
2847                // Pass-through until something listens (docs/gestures.md "Pass-through").
2848                class(el, "day-passive-leaf", true);
2849                el
2850            }
2851            Some(Builtin::Canvas) => {
2852                let el = unsafe { day_dom_create(EL_CANVAS) };
2853                // A canvas is the one built-in piece with no native control under it, so it
2854                // needs a tab stop of its own before focus — and with focus, the keys
2855                // (docs/menus.md) — can reach what it draws.
2856                unsafe { day_dom_canvas_keynav(el) };
2857                // …and reports focus both ways (mask 8), so `.focused(signal)` binds two-way
2858                // and dayscript's `assert_focused` can see where the keyboard is.
2859                unsafe { day_dom_listen(el, 8) };
2860                // Pass-through (docs/gestures.md): a canvas with no handler lets a press reach
2861                // what is behind it. A key handler is declared while the piece builds, after
2862                // this realize, so whether one came is asked once the build is over: a canvas
2863                // that hears keys takes the press that focuses it.
2864                class(el, "day-passive-leaf", true);
2865                post_local(move || {
2866                    if day_spec::keys::handled(id) || day_spec::keys::text(id) {
2867                        unsafe { day_dom_takes_pointer(el) };
2868                    }
2869                });
2870                el
2871            }
2872            Some(Builtin::Scroll) => {
2873                let Some(p) = day_spec::props_of::<ScrollProps>(kind, "web-dom", props) else {
2874                    return realize_placeholder(kind, id);
2875                };
2876                let el = unsafe { day_dom_create(EL_SCROLL) };
2877                if p.horizontal {
2878                    class(el, "horizontal", true);
2879                }
2880                // Offsets only for a piece that reads them (docs/scroll.md "Offset").
2881                if p.track_offset {
2882                    unsafe { day_dom_listen(el, listen::SCROLL) };
2883                }
2884                let flags = u32::from(p.indicators == ScrollIndicators::Hidden)
2885                    | (u32::from(p.bounce == Some(false)) << 1)
2886                    | (u32::from(p.track_phase) << 2);
2887                let (snap, interval) = match p.snap {
2888                    ScrollSnap::Page => (1, 0.0),
2889                    ScrollSnap::Interval(points) if points > 0.0 => (2, points),
2890                    // No snapping, or an interval that names no stops.
2891                    ScrollSnap::None | ScrollSnap::Interval(_) => (0, 0.0),
2892                };
2893                if flags != 0 || snap != 0 {
2894                    unsafe { day_dom_scroll_setup(el, flags, snap, interval) };
2895                }
2896                el
2897            }
2898            Some(Builtin::Divider) => {
2899                let el = unsafe { day_dom_create(EL_DIVIDER) };
2900                class(el, "day-passive-leaf", true);
2901                el
2902            }
2903            Some(Builtin::Nav) => {
2904                let Some(p) = day_spec::props_of::<NavProps>(kind, "web-dom", props) else {
2905                    return realize_placeholder(kind, id);
2906                };
2907                let el = unsafe { day_dom_create(EL_NAV) };
2908                class(el, "document-tabs", p.documents.is_some());
2909                unsafe {
2910                    day_dom_nav_mode(
2911                        el,
2912                        nav_mode(p.presentation),
2913                        p.title.as_ptr(),
2914                        p.title.len(),
2915                    );
2916                };
2917                unsafe { day_dom_listen(el, 1) }; // the back bar's button reports via CLICK
2918                let state = NavState {
2919                    presentation: p.presentation,
2920                    pages: Vec::new(),
2921                    sidebar: None,
2922                    titles: vec![p.title.clone()],
2923                    selected: 0,
2924                };
2925                // The bar's initial state (hidden at the root, the host's title): a cover's
2926                // strip that takes the bar over later starts from it.
2927                sync_back_bar(el, &state);
2928                NAV_STATE.with(|m| m.borrow_mut().insert(el, state));
2929                el
2930            }
2931            Some(Builtin::NavPage) => {
2932                let Some(p) = day_spec::props_of::<NavPageProps>(kind, "web-dom", props) else {
2933                    return realize_placeholder(kind, id);
2934                };
2935                let el = unsafe { day_dom_create(EL_PAGE) };
2936                PAGE_SIDEBAR.with(|m| {
2937                    m.borrow_mut()
2938                        .insert(el, p.pane == day_spec::props::Pane::Sidebar)
2939                });
2940                CSS_FRAMED.with(|set| set.borrow_mut().insert(el));
2941                unsafe { day_dom_listen(el, 32) };
2942                el
2943            }
2944            // Emulated fullscreen cover (docs/cover.md): a fixed-position overlay, hidden
2945            // until presented. CSS-framed (inset:0) and observer-reported, like nav pages.
2946            Some(Builtin::Cover) => {
2947                let el = unsafe { day_dom_create(EL_PAGE) };
2948                class(el, "day-cover", true);
2949                // The half sheet: a bottom-anchored half panel (`.day-half`, day.css), the
2950                // page above it on show and clickable.
2951                let p = day_spec::props_of::<CoverProps>(kind, "web-dom", props);
2952                if p.is_some_and(|p| p.half) {
2953                    class(el, "day-half", true);
2954                    COVER_HALF.with(|set| set.borrow_mut().insert(el));
2955                } else if p.is_some_and(|p| p.sheet) {
2956                    COVER_SHEET.with(|set| set.borrow_mut().insert(el));
2957                }
2958                CSS_FRAMED.with(|set| set.borrow_mut().insert(el));
2959                unsafe { day_dom_listen(el, 32) };
2960                el
2961            }
2962            Some(Builtin::NavMenu) => {
2963                let Some(p) = day_spec::props_of::<NavMenuProps>(kind, "web-dom", props) else {
2964                    return realize_placeholder(kind, id);
2965                };
2966                let el = unsafe { day_dom_create(EL_NAVMENU) };
2967                let json = navmenu_json(
2968                    &p.items,
2969                    &p.icons,
2970                    &p.tints,
2971                    &p.badges,
2972                    &p.badge_icons,
2973                    &p.badge_tints,
2974                    &p.sections,
2975                    p.selected,
2976                );
2977                unsafe { day_dom_navmenu(el, json.as_ptr(), json.len()) };
2978                el
2979            }
2980            Some(Builtin::List) => {
2981                let Some(p) = day_spec::props_of::<ListProps>(kind, "web-dom", props) else {
2982                    return realize_placeholder(kind, id);
2983                };
2984                let host = unsafe { day_dom_create(EL_SCROLL) };
2985                class(host, "day-list", true);
2986                if p.reorderable {
2987                    unsafe { day_dom_list_reorder(host) };
2988                }
2989                let content = unsafe { day_dom_create(EL_DIV) };
2990                unsafe { day_dom_insert(host, content, 0) };
2991                let (row_height, automatic) = match p.row_height {
2992                    RowHeight::Uniform(h) => (h, false),
2993                    RowHeight::Automatic => (44.0, true),
2994                };
2995                LISTS.with(|m| {
2996                    m.borrow_mut().insert(
2997                        host,
2998                        ListEntry {
2999                            node: id,
3000                            content,
3001                            row_height,
3002                            automatic,
3003                            heights: Vec::new(),
3004                            source: None,
3005                            cells: Vec::new(),
3006                            bound: Vec::new(),
3007                            fill_pending: false,
3008                            pending_scroll: None,
3009                            seen: None,
3010                            owed_polls: 0,
3011                            last_width: -1.0,
3012                            activatable: p.activatable,
3013                            selectable: p.selectable,
3014                            separators: p.separators == Some(true),
3015                            multi: p.multi_select,
3016                            selected: BTreeSet::new(),
3017                            anchor: None,
3018                            lead: None,
3019                            pin: (0, 0),
3020                            pin_row: None,
3021                        },
3022                    )
3023                });
3024                // Rows are built as they scroll in, so the list has to hear about scrolling.
3025                unsafe { day_dom_list_on_scroll(host) };
3026                if p.selectable {
3027                    unsafe { day_dom_list_keynav(host, u32::from(p.multi_select)) };
3028                }
3029                host
3030            }
3031            // A recycled list cell is ADOPTED from the native list, never realized through
3032            // this path; the inspector kinds never arrive (`Cap::Inspector` is Unsupported
3033            // here, so the piece composes its pane instead — docs/inspector.md); anything
3034            // else is an extension piece.
3035            Some(
3036                Builtin::ListCell
3037                | Builtin::ListItem
3038                | Builtin::Tree
3039                | Builtin::Inspector
3040                | Builtin::InspectorPane
3041                | Builtin::Split
3042                | Builtin::SplitPane,
3043            )
3044            | None => {
3045                // An external piece's own dom renderer, if one registered for this kind.
3046                if let Some(make) = registered(kind, |r| r.make) {
3047                    let h = make(self, props, id);
3048                    remember(h.0, id);
3049                    return h;
3050                }
3051                // `warn` reaches the browser console; `report` records it for
3052                // dayscript's assert_no_placeholders (eprintln goes nowhere on wasm).
3053                warn(&format!(
3054                    "day: no renderer for piece kind \"{kind}\" on web-dom (rendering a placeholder)"
3055                ));
3056                day_spec::placeholder::report(kind, "web-dom");
3057                let el = unsafe { day_dom_create(EL_LABEL) };
3058                text(el, &format!("⟨{kind}⟩"));
3059                class(el, "placeholder", true);
3060                el
3061            }
3062        };
3063        remember(el, id);
3064        DomHandle(el)
3065    }
3066
3067    fn update(
3068        &mut self,
3069        h: &DomHandle,
3070        kind: PieceKind,
3071        patch: &dyn std::any::Any,
3072        anim: Option<&AnimSpec>,
3073    ) {
3074        let el = h.0;
3075        match kind {
3076            kinds::IMAGE => {
3077                if let Some(p) = patch.downcast_ref::<day_spec::props::ImagePatch>() {
3078                    match p {
3079                        day_spec::props::ImagePatch::Tint(c) => {
3080                            // The mask needs the same URL the element already loads.
3081                            let state = IMAGE_SRC.with(|m| {
3082                                let mut m = m.borrow_mut();
3083                                let state = m.get_mut(&el)?;
3084                                state.tint = *c;
3085                                Some(state.clone())
3086                            });
3087                            if let Some(state) = state {
3088                                // An element realized with a tint or as a template is already
3089                                // the masked div, so this repaints the mask's fill (a template
3090                                // with no tint goes back to `currentColor`); an `<img>` gains
3091                                // or loses its mask.
3092                                apply_image_tint(el, &state);
3093                            }
3094                        }
3095                        // A source swap repaints the same element (docs/images.md), so an
3096                        // `image()` bound to a signal shows new pixels without rebuilding its
3097                        // subtree. A masked image (tinted or a template) re-cuts its mask from
3098                        // the new source and keeps its tint: from the new name here — a
3099                        // recycled sidebar row shows the glyph it was rebound to — or, for
3100                        // bytes and decodes, in the shim, which owns their URL.
3101                        day_spec::props::ImagePatch::Source(source) => {
3102                            let src = match source {
3103                                day_spec::ImageSource::Named(name) if name.contains('/') => {
3104                                    name.clone()
3105                                }
3106                                day_spec::ImageSource::Named(name) => {
3107                                    format!("assets/images/{}.{}", name, image_ext(name))
3108                                }
3109                                _ => String::new(),
3110                            };
3111                            let state = IMAGE_SRC.with(|m| {
3112                                let mut m = m.borrow_mut();
3113                                let state = m.get_mut(&el)?;
3114                                state.src.clone_from(&src);
3115                                Some(state.clone())
3116                            });
3117                            match source {
3118                                day_spec::ImageSource::Named(_) => {
3119                                    if state.as_ref().is_none_or(|s| s.is_img) {
3120                                        attr(el, "src", &src);
3121                                    }
3122                                }
3123                                day_spec::ImageSource::Bytes(b) => unsafe {
3124                                    day_dom_image_set_bytes(el, b.as_ptr(), b.len());
3125                                },
3126                                day_spec::ImageSource::Decoded(id) => unsafe {
3127                                    day_dom_image_set_bitmap(el, id.0 as f64);
3128                                },
3129                            }
3130                            if let Some(state) = state.filter(ImageState::masked) {
3131                                apply_image_tint(el, &state);
3132                            }
3133                        }
3134                    }
3135                }
3136            }
3137            kinds::CONTAINER => match patch.downcast_ref::<ContainerPatch>() {
3138                Some(ContainerPatch::Fill(fill)) => apply_fill(el, fill.as_ref(), anim, false),
3139                Some(ContainerPatch::Surface(p)) => {
3140                    let role = SURFACE_ROLES.with(|t| t.get(el as usize));
3141                    apply_surface(el, p, role, anim, false);
3142                }
3143                None => {}
3144            },
3145            kinds::LABEL => {
3146                if let Some(p) = patch.downcast_ref::<LabelPatch>() {
3147                    match p {
3148                        LabelPatch::Paragraph(para) => {
3149                            LABELS.with(|t| {
3150                                if let Some(st) = t.borrow_mut().get_mut(&el) {
3151                                    st.para = *para;
3152                                }
3153                            });
3154                            apply_paragraph(el);
3155                        }
3156                        LabelPatch::Text(t) => {
3157                            set_label_state_text(el, t, false);
3158                            text(el, t);
3159                            // The measure cache is keyed by element — new text, new metrics.
3160                            MEASURE_CACHE.with(|c| c.borrow_mut().retain(|(e, _), _| *e != el));
3161                            elide_label(el);
3162                        }
3163                        LabelPatch::Runs(t, runs) => {
3164                            set_label_state_text(el, t, !runs.is_empty());
3165                            set_label_text(el, t, runs);
3166                            MEASURE_CACHE.with(|c| c.borrow_mut().retain(|(e, _), _| *e != el));
3167                            elide_label(el);
3168                        }
3169                        LabelPatch::Color(c) => match c {
3170                            Some(c) => s(el, "color", &ink_css(*c)),
3171                            None => s(el, "color", ""),
3172                        },
3173                        LabelPatch::Font(f) => {
3174                            apply_font(el, f);
3175                            // The `font` shorthand reset the line height.
3176                            apply_paragraph(el);
3177                        }
3178                    }
3179                }
3180            }
3181            kinds::BUTTON => {
3182                if let Some(p) = patch.downcast_ref::<ButtonPatch>() {
3183                    match p {
3184                        ButtonPatch::Content(c) => {
3185                            apply_button_content(el, &c.title, c.icon.as_ref(), c.icon_only);
3186                        }
3187                        ButtonPatch::Title(t) => text(el, t),
3188                        ButtonPatch::Enabled(e) => set_enabled(el, *e),
3189                        ButtonPatch::Selected(on) => set_button_selected(el, *on),
3190                        ButtonPatch::Style(st) => apply_button_style(el, *st),
3191                    }
3192                }
3193            }
3194            kinds::TOGGLE => {
3195                if let Some(p) = patch.downcast_ref::<TogglePatch>() {
3196                    match p {
3197                        TogglePatch::On(on) => unsafe { day_dom_set_checked(el, u32::from(*on)) },
3198                        TogglePatch::Enabled(e) => set_enabled(el, *e),
3199                    }
3200                }
3201            }
3202            kinds::SLIDER => {
3203                if let Some(p) = patch.downcast_ref::<SliderPatch>() {
3204                    match p {
3205                        SliderPatch::Value(v) => unsafe { day_dom_set_value(el, *v) },
3206                        SliderPatch::Enabled(e) => set_enabled(el, *e),
3207                    }
3208                }
3209            }
3210            kinds::TEXT_FIELD => {
3211                if let Some(p) = patch.downcast_ref::<TextFieldPatch>() {
3212                    match p {
3213                        TextFieldPatch::Text {
3214                            text: t,
3215                            from_native,
3216                        } => {
3217                            if !*from_native {
3218                                attr(el, "value", t);
3219                            }
3220                        }
3221                        TextFieldPatch::Placeholder(t) => attr(el, "placeholder", t),
3222                        TextFieldPatch::Enabled(e) => set_enabled(el, *e),
3223                        TextFieldPatch::Select(sel) => {
3224                            let at = |n: usize| n.min(u32::MAX as usize) as u32;
3225                            unsafe { day_dom_field_select(el, at(sel.start), at(sel.end)) }
3226                        }
3227                    }
3228                }
3229            }
3230            kinds::TEXT_AREA => {
3231                if let Some(TextAreaPatch::SetText(t)) = patch.downcast_ref::<TextAreaPatch>() {
3232                    // Day-driven content changed: refresh the line count `measure` grows by.
3233                    AREA_HINTS.with(|m| {
3234                        if let Some(h) = m.borrow_mut().get_mut(&el) {
3235                            h.2 = content_lines(t);
3236                        }
3237                    });
3238                }
3239                if let Some(p) = patch.downcast_ref::<TextAreaPatch>() {
3240                    match p {
3241                        TextAreaPatch::SetText(t) => text(el, t),
3242                        // `readonly` is the INVERSE of editable, and the marker convention is
3243                        // "-" sets / "" removes (see the shim's day_dom_set_attr): editable ⇒ no
3244                        // readonly attribute.
3245                        TextAreaPatch::SetEditable(e) => {
3246                            attr(el, "readonly", if *e { "" } else { "-" });
3247                        }
3248                        TextAreaPatch::SetSelectable(sel) => {
3249                            s(el, "user-select", if *sel { "text" } else { "none" });
3250                        }
3251                        TextAreaPatch::SetSpellCheck(sc) => {
3252                            attr(el, "spellcheck", if *sc { "true" } else { "false" });
3253                        }
3254                    }
3255                }
3256            }
3257            kinds::PICKER => {
3258                // Programmatic DOM value sets fire no events — echo-free by construction.
3259                match patch.downcast_ref::<PickerPatch>() {
3260                    Some(PickerPatch::Selected(i)) => {
3261                        PICKER_SELECTED.with(|m| m.borrow_mut().insert(el, *i));
3262                        let seg = SEG_COUNT.with(|m| m.borrow().get(&el).copied());
3263                        match seg {
3264                            Some(_) => unsafe { day_dom_options_select(el, *i as u32) },
3265                            None => unsafe { day_dom_set_value(el, *i as f64) },
3266                        }
3267                    }
3268                    // New labels: the shim's own builder rewrites the choices, so the same
3269                    // call that filled them at build refills them here. The selected index
3270                    // rides along, clamped to the new list.
3271                    Some(PickerPatch::Options(opts)) => {
3272                        let keep = PICKER_SELECTED.with(|m| m.borrow().get(&el).copied());
3273                        let selected = keep.unwrap_or(0).min(opts.len().saturating_sub(1));
3274                        let json = picker_json(&PickerProps {
3275                            options: opts.clone(),
3276                            selected,
3277                            ..Default::default()
3278                        });
3279                        unsafe { day_dom_options(el, json.as_ptr(), json.len()) };
3280                        if SEG_COUNT.with(|m| m.borrow().contains_key(&el)) {
3281                            SEG_COUNT.with(|m| m.borrow_mut().insert(el, opts.len()));
3282                        }
3283                    }
3284                    // A segmented or inline picker is a group of buttons; the shim passes the
3285                    // group's `disabled` to each one (and to the ones a later Options rebuild
3286                    // makes).
3287                    Some(PickerPatch::Enabled(on)) => set_enabled(el, *on),
3288                    None => {}
3289                }
3290            }
3291            kinds::PROGRESS => {
3292                if let Some(ProgressPatch::Animating(on)) = patch.downcast_ref::<ProgressPatch>() {
3293                    attr(el, "data-day-animating", if *on { "true" } else { "false" });
3294                }
3295
3296                if let Some(ProgressPatch::Value(v)) = patch.downcast_ref::<ProgressPatch>()
3297                    && let Some(v) = v
3298                {
3299                    unsafe { day_dom_set_value(el, *v) };
3300                }
3301            }
3302            kinds::NAV => {
3303                if let Some(p) = patch.downcast_ref::<NavPatch>() {
3304                    nav_patch(el, p);
3305                }
3306            }
3307            // Emulated cover (docs/cover.md): present = re-home under #day-root (position:fixed
3308            // escapes ancestor transforms only from a clean containing block) and show; the
3309            // ResizeObserver reports the frame. Dismiss = hide + `CoverHidden` at once.
3310            kinds::COVER => {
3311                if let Some(p) = patch.downcast_ref::<CoverPatch>() {
3312                    match p {
3313                        CoverPatch::Present { background, .. } => {
3314                            // Each present sets its own fill or returns to the stylesheet's: the
3315                            // element outlives one presentation. A composed sheet's cover is
3316                            // clear (docs/cover.md "Modal sheet"), and here it is `.day-sheet`:
3317                            // the stylesheet frosts the page under it, and its toolbar strip
3318                            // docks on the card rather than across the window (shim.js).
3319                            let sheet = COVER_SHEET.with(|set| set.borrow().contains(&el))
3320                                && *background == Some(day_spec::Color::CLEAR.into());
3321                            class(el, "day-sheet", sheet);
3322                            match background {
3323                                Some(bg) if !sheet => {
3324                                    s(el, "background-color", &ink_css(*bg));
3325                                }
3326                                _ => s(el, "background-color", ""),
3327                            }
3328                            unsafe { day_dom_insert(1, el, u32::MAX) };
3329                            class(el, "open", true);
3330                            // Seed the frame SYNCHRONOUSLY from the cached viewport (the cover is
3331                            // fixed/inset:0, so that IS its size). Without this, the content lays
3332                            // out at width 0 until the async ResizeObserver fires — invisible in
3333                            // LTR's top-left but off-screen to the LEFT under RTL (docs/cover.md).
3334                            if let Some(node) = node_of(el) {
3335                                let vp = LAST_VIEWPORT.with(std::cell::Cell::get);
3336                                // Less the cover's own toolbar strip, which sits above it.
3337                                let strip = unsafe { day_dom_toolbar_height(el) };
3338                                // A half sheet is the bottom half, less the grabber strip
3339                                // the stylesheet pads for (`.day-half`); the observer
3340                                // reports the content box too.
3341                                let half = COVER_HALF.with(|s| s.borrow().contains(&el));
3342                                let size = if half {
3343                                    Size::new(vp.width, vp.height * 0.5 - HALF_SHEET_GRABBER)
3344                                } else {
3345                                    Size::new(vp.width, vp.height - strip)
3346                                };
3347                                if size.width > 0.0 && size.height > 0.0 {
3348                                    emit(node, Event::FrameChanged(size));
3349                                }
3350                            }
3351                        }
3352                        CoverPatch::DismissDisabled(_) => {}
3353                        CoverPatch::Dismiss => {
3354                            class(el, "open", false);
3355                            if let Some(node) = node_of(el) {
3356                                emit(node, Event::CoverHidden);
3357                            }
3358                        }
3359                    }
3360                }
3361            }
3362            kinds::NAV_MENU => {
3363                if let Some(NavMenuPatch::Items {
3364                    items,
3365                    icons,
3366                    tints,
3367                    badges,
3368                    badge_icons,
3369                    badge_tints,
3370                    sections,
3371                    selected,
3372                    rows_changed,
3373                    ..
3374                }) = patch.downcast_ref::<NavMenuPatch>()
3375                {
3376                    let mut json = navmenu_json(
3377                        items,
3378                        icons,
3379                        tints,
3380                        badges,
3381                        badge_icons,
3382                        badge_tints,
3383                        sections,
3384                        *selected,
3385                    );
3386                    match rows_changed {
3387                        // The same rows with new words or counts: refill those rows in place.
3388                        Some(rows) => {
3389                            json.pop();
3390                            json.push_str(",\"rows\":[");
3391                            for (n, r) in rows.iter().enumerate() {
3392                                if n > 0 {
3393                                    json.push(',');
3394                                }
3395                                json.push_str(&r.to_string());
3396                            }
3397                            json.push_str("]}");
3398                            unsafe { day_dom_navmenu_rows(el, json.as_ptr(), json.len()) };
3399                        }
3400                        None => unsafe { day_dom_navmenu(el, json.as_ptr(), json.len()) },
3401                    }
3402                } else if let Some(NavMenuPatch::Selected(sel)) =
3403                    patch.downcast_ref::<NavMenuPatch>()
3404                {
3405                    unsafe { day_dom_navmenu_select(el, sel.map_or(-1, |i| i as i32)) };
3406                }
3407            }
3408            kinds::LIST => {
3409                if let Some(p) = patch.downcast_ref::<ListPatch>() {
3410                    list_patch(el, p);
3411                }
3412            }
3413            other => {
3414                if let Some(update) = registered(other, |r| r.update) {
3415                    update(self, h, patch);
3416                }
3417            }
3418        }
3419    }
3420
3421    /// Offer a satellite piece its teardown hook before `release` frees the handle (§15.2).
3422    /// web-dom's registry is a runtime `RefCell`, so the hook is copied out before the call —
3423    /// the borrow must end before a piece re-enters the registry.
3424    fn release_piece(&mut self, kind: day_spec::PieceKind, h: &Self::Handle) {
3425        if let Some(Some(f)) = registered(kind, |r| r.release) {
3426            f(self, h);
3427        }
3428    }
3429
3430    fn release(&mut self, h: DomHandle) {
3431        let el = h.0;
3432        // One sweep drops this element's entry from every registered `SideTable` — present
3433        // and future — before the manual purges below (day_spec::sidetable; day-toolkit-dom keys by
3434        // shim element id, widened to the sweeper's usize key space).
3435        day_spec::sidetable::sweep(el as usize);
3436        NODE_OF.with(|m| m.borrow_mut().remove(&el));
3437        IMAGE_SRC.with(|m| m.borrow_mut().remove(&el));
3438        // An object URL this element made for `ImageSource::Bytes` is not reachable by the GC: it
3439        // lives on the document until revoked, so the element's release is the moment to do it.
3440        // SAFETY: an element id the shim either knows or does not; revoking nothing is a no-op.
3441        unsafe { day_dom_image_revoke(el) };
3442        CSS_FRAMED.with(|s| s.borrow_mut().remove(&el));
3443        COVER_HALF.with(|s| s.borrow_mut().remove(&el));
3444        COVER_SHEET.with(|s| s.borrow_mut().remove(&el));
3445        AREA_HINTS.with(|m| m.borrow_mut().remove(&el));
3446        PAGE_SIDEBAR.with(|m| m.borrow_mut().remove(&el));
3447        NAV_STATE.with(|m| m.borrow_mut().remove(&el));
3448        SEG_COUNT.with(|m| m.borrow_mut().remove(&el));
3449        PICKER_SIZE.with(|m| m.borrow_mut().remove(&el));
3450        SPINNERS.with(|s| s.borrow_mut().remove(&el));
3451        LABELS.with(|t| t.borrow_mut().remove(&el));
3452        GESTURES.with(|t| t.borrow_mut().remove(&el));
3453        DIRECTION.with(|t| t.borrow_mut().remove(&el));
3454        MEASURE_CACHE.with(|c| c.borrow_mut().retain(|(e, _), _| *e != el));
3455        if let Some(list) = LISTS.with(|m| m.borrow_mut().remove(&el)) {
3456            CELL_ROWS.with(|m| {
3457                let mut m = m.borrow_mut();
3458                for c in list.cells {
3459                    m.remove(&c);
3460                }
3461            });
3462            // The pinned header's cell is the host's alone (no row slot holds it), so nothing
3463            // else tells day-core to dispose the header built there.
3464            if list.pin.1 != 0
3465                && let Some(source) = &list.source
3466            {
3467                (source.release)(list.pin.1 as usize as day_spec::RawHandle);
3468            }
3469        }
3470        unsafe { day_dom_release(el) };
3471    }
3472
3473    fn insert(&mut self, parent: &DomHandle, child: &DomHandle, index: usize) {
3474        // Nav host: route pages into the right pane; everything else is plain DOM insert.
3475        let routed = NAV_STATE.with(|m| {
3476            let mut m = m.borrow_mut();
3477            let Some(state) = m.get_mut(&parent.0) else {
3478                return false;
3479            };
3480            let sidebar = PAGE_SIDEBAR
3481                .with(|p| p.borrow().get(&child.0).copied())
3482                .unwrap_or(false);
3483            if sidebar {
3484                state.sidebar = Some(child.0);
3485            }
3486            // The sidebar page belongs to the CHROME slot in every presentation except `Stack`,
3487            // where it is the stack's root and so joins the detail pages instead.
3488            let to_chrome = sidebar && state.presentation != NavPresentation::Stack;
3489            unsafe { day_dom_nav_add_page(parent.0, child.0, u32::from(to_chrome)) };
3490            if !to_chrome {
3491                state.pages.push(child.0);
3492            }
3493            true
3494        });
3495        if routed {
3496            return;
3497        }
3498        unsafe { day_dom_insert(parent.0, child.0, index as u32) };
3499    }
3500
3501    fn remove(&mut self, parent: &DomHandle, child: &DomHandle) {
3502        NAV_STATE.with(|m| {
3503            if let Some(state) = m.borrow_mut().get_mut(&parent.0) {
3504                state.pages.retain(|p| *p != child.0);
3505                // Dropping a page shifts every index after it, and `selected` is an index. Clamp
3506                // rather than leave it dangling past the end — a stale one would hide every page.
3507                state.selected = state.selected.min(state.pages.len().saturating_sub(1));
3508            }
3509        });
3510        unsafe { day_dom_remove(child.0) };
3511    }
3512
3513    fn move_child(&mut self, parent: &DomHandle, child: &DomHandle, to: usize) {
3514        unsafe { day_dom_insert(parent.0, child.0, to as u32) };
3515    }
3516
3517    fn measure(&mut self, h: &DomHandle, kind: PieceKind, p: Proposal) -> Size {
3518        let el = h.0;
3519        let max_w = p.width.unwrap_or(1.0e6);
3520        match kind {
3521            kinds::LABEL => MEASURE_CACHE.with(|cache| {
3522                let key = (el, (max_w * 4.0) as i64);
3523                if let Some(sz) = cache.borrow().get(&key) {
3524                    return *sz;
3525                }
3526                // In the label's own style, so the line limit, the letter spacing and the line
3527                // height count; an elided label measures the text it stands for, never the
3528                // shorter copy it shows at its current width.
3529                let full = LABELS.with(|t| {
3530                    t.borrow()
3531                        .get(&el)
3532                        .filter(|st| st.elided)
3533                        .map(|st| st.text.clone())
3534                });
3535                let m = label_size(el, full.as_deref(), max_w);
3536                let sz = Size::new(m.width.ceil().min(max_w), m.height.ceil());
3537                cache.borrow_mut().insert(key, sz);
3538                sz
3539            }),
3540            kinds::BUTTON => {
3541                let mut out = [0.0f64; 2];
3542                unsafe {
3543                    day_dom_measure_text(
3544                        std::ptr::null(),
3545                        el as usize,
3546                        std::ptr::null(),
3547                        0,
3548                        1.0e6,
3549                        out.as_mut_ptr(),
3550                    );
3551                };
3552                Size::new(out[0].ceil() + 26.0, 28.0)
3553            }
3554            kinds::TOGGLE => Size::new(40.0, 24.0),
3555            kinds::SLIDER => Size::new(p.width.unwrap_or(180.0), 24.0),
3556            kinds::TEXT_FIELD => Size::new(p.width.unwrap_or(200.0), 30.0),
3557            kinds::TEXT_AREA => {
3558                // The auto-growing-height contract (docs/textarea.md): content height clamped
3559                // between `min_lines` and `max_lines`, like the uikit arm's sizeThatFits path.
3560                // The line height comes from a REAL measurement in the control font, so it rides
3561                // `--day-text-scale` and the browser's font-size preference exactly as the
3562                // rendered control does; `content_lines` counts hard breaks only (soft wrapping
3563                // is not simulated — the area scrolls where wrapping would have grown it).
3564                let (min_l, max_l, lines) =
3565                    AREA_HINTS.with(|m| m.borrow().get(&el).copied().unwrap_or((1, 0, 1)));
3566                let line_h = measure_str("x").height.max(16.0);
3567                let pad = 14.0; // .day-area: 6px top/bottom padding + 1px borders (day.css)
3568                let min_l = min_l.max(1);
3569                let mut l = lines.max(min_l);
3570                if max_l > 0 {
3571                    l = l.min(max_l.max(min_l));
3572                }
3573                Size::new(
3574                    p.width.unwrap_or(240.0),
3575                    p.height.unwrap_or(f64::from(l) * line_h + pad),
3576                )
3577            }
3578            kinds::PICKER => PICKER_SIZE
3579                .with(|m| m.borrow().get(&el).copied())
3580                .unwrap_or(Size::new(68.0, 26.0)),
3581            // A spinner is SQUARE — `.day-spinner` is a 50%-radius ring that rotates, so any
3582            // other aspect ratio spins as an ellipse sweeping the layout (docs/pieces.md).
3583            // Determinate progress is the wide, short bar.
3584            kinds::PROGRESS => {
3585                if let Some(side) = SPINNERS.with(|s| s.borrow().get(&el).copied()) {
3586                    Size::new(side, side)
3587                } else {
3588                    Size::new(p.width.unwrap_or(160.0), 8.0)
3589                }
3590            }
3591            kinds::DIVIDER => Size::new(p.width.unwrap_or(0.0), 1.0),
3592            kinds::IMAGE => Size::new(p.width.unwrap_or(100.0), p.height.unwrap_or(100.0)),
3593            other => {
3594                if let Some(measure) = registered(other, |r| r.measure).flatten() {
3595                    return measure(self, h, p);
3596                }
3597                Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0))
3598            }
3599        }
3600    }
3601
3602    /// The browser reports exact font metrics through a canvas `TextMetrics`, and the
3603    /// element's own border/padding says where its text box begins — so an `<input>` reports a
3604    /// lower baseline than a bare `<div>`, which is what makes a row line up (docs/baseline.md).
3605    /// `Emulated` rather than `Native`: CSS `align-items: baseline` would do this natively, but
3606    /// day positions every element absolutely and needs the number, not the alignment mode.
3607    fn first_baseline(&mut self, h: &DomHandle, kind: PieceKind, size: Size) -> Option<f64> {
3608        if !day_spec::kind_has_baseline(kind) {
3609            return None;
3610        }
3611        let b = unsafe { day_dom_baseline(h.0, size.height) };
3612        (b >= 0.0).then_some(b)
3613    }
3614
3615    fn set_frame(&mut self, h: &DomHandle, frame: Rect, anim: Option<&AnimSpec>) {
3616        if CSS_FRAMED.with(|s| s.borrow().contains(&h.0)) {
3617            return;
3618        }
3619        match anim {
3620            Some(_) => animate(
3621                h.0,
3622                anim_prop::FRAME,
3623                &[
3624                    frame.origin.x,
3625                    frame.origin.y,
3626                    frame.size.width,
3627                    frame.size.height,
3628                ],
3629                anim,
3630            ),
3631            None => unsafe {
3632                day_dom_set_frame(
3633                    h.0,
3634                    frame.origin.x,
3635                    frame.origin.y,
3636                    frame.size.width,
3637                    frame.size.height,
3638                );
3639            },
3640        }
3641        let relabel = LABELS.with(|t| {
3642            t.borrow_mut().get_mut(&h.0).is_some_and(|st| {
3643                let changed = (st.width - frame.size.width).abs() >= 0.5;
3644                st.width = frame.size.width;
3645                changed && st.elides()
3646            })
3647        });
3648        if relabel {
3649            elide_label(h.0);
3650        }
3651        let gradient = SURFACE_GRADIENTS.with(|t| {
3652            t.with(h.0 as usize, |(g, size)| {
3653                *size = frame.size;
3654                linear_gradient_css(g, frame.size)
3655            })
3656        });
3657        if let Some(css) = gradient {
3658            s(h.0, "background-image", &css);
3659        }
3660        // A list host framed: (re)populate when its width actually changed.
3661        let repopulate = LISTS.with(|m| {
3662            let mut m = m.borrow_mut();
3663            let Some(st) = m.get_mut(&h.0) else {
3664                return false;
3665            };
3666            if (st.last_width - frame.size.width).abs() < 0.5 {
3667                return false;
3668            }
3669            st.last_width = frame.size.width;
3670            true
3671        });
3672        if repopulate {
3673            let host = h.0;
3674            post_local(move || list_populate(host));
3675        }
3676    }
3677
3678    fn set_opacity(&mut self, h: &DomHandle, opacity: f64, anim: Option<&AnimSpec>) {
3679        animate(h.0, anim_prop::OPACITY, &[opacity], anim);
3680    }
3681
3682    fn set_transform(&mut self, h: &DomHandle, t: Transform, _size: Size, anim: Option<&AnimSpec>) {
3683        // Mark this element as a compositing root so its rounded-clip descendants get their own
3684        // clipped layer (day.css `.day-xform .day-clip`) — see the note in `apply_surface`.
3685        class(h.0, "day-xform", true);
3686        s(h.0, "transform-origin", "50% 50%");
3687        animate(
3688            h.0,
3689            anim_prop::TRANSFORM,
3690            &[t.tx, t.ty, t.rotation.degrees(), t.sx, t.sy],
3691            anim,
3692        );
3693    }
3694
3695    fn set_selectable(&mut self, h: &DomHandle, selectable: bool) -> Option<DomHandle> {
3696        // Nothing is selectable by default (#day-root sets `user-select: none`); the class opts
3697        // this element and its text back in (`.day-selectable` in day.css). See docs/text.md.
3698        class(h.0, "day-selectable", selectable);
3699        if selectable {
3700            unsafe { day_dom_takes_pointer(h.0) };
3701        }
3702        None
3703    }
3704
3705    fn set_input_traits(
3706        &mut self,
3707        h: &DomHandle,
3708        traits: &day_spec::InputTraits,
3709    ) -> Option<DomHandle> {
3710        use day_spec::{InputPurpose as P, SubmitLabel as L};
3711        // One `<input>` covers every member: each is an attribute, and all of them are written
3712        // on every call (an empty value removes one), so a flip back to the defaults leaves no
3713        // attribute behind. The type is `text` for every purpose: the typed ones (`email`,
3714        // `url`, `number`) trim or coerce what the user types and validate it, and a controlled
3715        // input has to hold exactly the text it reports. `inputmode` alone picks the keyboard.
3716        let (inputmode, autocomplete, capitalize) = match traits.purpose {
3717            P::Text => ("", "", ""),
3718            P::Name => ("", "name", "words"),
3719            P::Email => ("email", "email", "none"),
3720            P::Url => ("url", "url", "none"),
3721            P::Phone => ("tel", "tel", ""),
3722            P::Number => ("numeric", "", "none"),
3723            P::Decimal => ("decimal", "", "none"),
3724            P::Username => ("", "username", "none"),
3725            P::Password => ("", "current-password", "none"),
3726            P::NewPassword => ("", "new-password", "none"),
3727            P::OneTimeCode => ("", "one-time-code", "none"),
3728        };
3729        // Hidden characters are never capitalized, corrected or handed to a spell checker,
3730        // whatever the purpose; free text and a phone number keep the browser's own handling.
3731        let plain = !traits.secure && matches!(traits.purpose, P::Text | P::Phone);
3732        let kind = if traits.secure { "password" } else { "text" };
3733        let capitalize = if traits.secure { "none" } else { capitalize };
3734        let (autocorrect, spellcheck) = if plain { ("", "") } else { ("off", "false") };
3735        let enterkeyhint = match traits.submit_label {
3736            L::Return => "",
3737            L::Done => "done",
3738            L::Go => "go",
3739            L::Next => "next",
3740            L::Search => "search",
3741            L::Send => "send",
3742        };
3743        // `max_length` takes no attribute: `maxlength` counts UTF-16 units and the bound is in
3744        // characters, so the native limit would refuse text the bound allows. day-pieces holds
3745        // it.
3746        let readonly = if traits.read_only { "readonly" } else { "" };
3747        // Every value is one of the fixed words above, so the object needs no escaping.
3748        let json = format!(
3749            r#"{{"type":"{kind}","inputmode":"{inputmode}","autocomplete":"{autocomplete}","autocapitalize":"{capitalize}","autocorrect":"{autocorrect}","spellcheck":"{spellcheck}","enterkeyhint":"{enterkeyhint}","readonly":"{readonly}"}}"#
3750        );
3751        unsafe { day_dom_input_traits(h.0, json.as_ptr(), json.len()) };
3752        None
3753    }
3754
3755    fn set_cursor(&mut self, h: &DomHandle, cursor: Cursor) {
3756        // The CSS vocabulary is the contract (docs/cursor.md); an inline `cursor` on the element
3757        // wins over the stylesheet's affordance rules, and an empty value removes it.
3758        let v = if cursor == Cursor::Default {
3759            ""
3760        } else {
3761            cursor.css_name()
3762        };
3763        let p = "cursor";
3764        unsafe { day_dom_set_style(h.0, p.as_ptr(), p.len(), v.as_ptr(), v.len()) };
3765        // A browser shows a cursor only over an element the pointer hits, so a cursor makes a
3766        // pass-through element a pointer target (the one place the web departs from
3767        // docs/gestures.md "Pass-through").
3768        if cursor != Cursor::Default {
3769            unsafe { day_dom_takes_pointer(h.0) };
3770        }
3771    }
3772
3773    fn set_scroll_content(&mut self, h: &DomHandle, content: Size) {
3774        unsafe { day_dom_scroll_content(h.0, content.width, content.height) };
3775    }
3776
3777    /// A web list row sized for touch: 16px sides, 44px tall.
3778    fn list_row_metrics(&mut self, _h: &DomHandle) -> day_spec::RowMetrics {
3779        day_spec::RowMetrics {
3780            insets: day_spec::Insets {
3781                top: 10.0,
3782                leading: 16.0,
3783                bottom: 10.0,
3784                trailing: 16.0,
3785            },
3786            min_height: 44.0,
3787        }
3788    }
3789
3790    /// Queued one turn, behind the populate a splice or reload in the same turn posted, so the
3791    /// content has its new extent; then the browser scrolls (`behavior: smooth` when animated)
3792    /// and its scroll events refill the window and send the viewport report.
3793    fn list_scroll(&mut self, h: &DomHandle, to: day_spec::ListScroll) -> bool {
3794        let el = h.0;
3795        if !LISTS.with(|m| m.borrow().contains_key(&el)) {
3796            return false;
3797        }
3798        post_local(move || {
3799            // The list can be released before its turn comes: a page swapped out in the same
3800            // task (a test run moving to its next case) takes the element with it, and the
3801            // shim would throw reading a viewport it no longer has.
3802            if !LISTS.with(|m| m.borrow().contains_key(&el)) {
3803                return;
3804            }
3805            let mut view = [0.0_f64; 2];
3806            unsafe { day_dom_list_viewport(el, view.as_mut_ptr()) };
3807            let target = LISTS.with(|m| {
3808                let m = m.borrow();
3809                let st = m.get(&el)?;
3810                let n = st.source.as_ref().map_or(0, |src| (src.len)());
3811                let extent = if st.stacked() {
3812                    st.tops(n)[n]
3813                } else {
3814                    n as f64 * st.row_height.max(1.0)
3815                };
3816                match to.row {
3817                    None => Some((extent - view[1]).max(0.0)),
3818                    Some(row) if row < n => row_scroll_target(
3819                        st.row_span(row),
3820                        st.pinned_above(row),
3821                        to.align,
3822                        view[0],
3823                        view[1],
3824                        extent,
3825                    ),
3826                    Some(_) => None,
3827                }
3828            });
3829            match target {
3830                Some(y) => {
3831                    // A list not laid out yet has nothing to scroll: the next fill repeats it.
3832                    if view[1] <= 0.0 {
3833                        LISTS.with(|m| {
3834                            if let Some(st) = m.borrow_mut().get_mut(&el) {
3835                                st.pending_scroll = Some(y);
3836                            }
3837                        });
3838                    }
3839                    unsafe { day_dom_scroll_to(el, 0.0, y, u32::from(to.animated)) };
3840                    // An instant jump has moved the offset already, but its `scroll` event
3841                    // waits for the next frame: build and report the rows it shows now.
3842                    if !to.animated && view[1] > 0.0 {
3843                        list_fill_window(el);
3844                    }
3845                }
3846                // Nothing moves: the report still follows the request.
3847                None => list_fill_window(el),
3848            }
3849        });
3850        true
3851    }
3852
3853    fn scroll_to(&mut self, h: &DomHandle, target: Rect, animated: bool) {
3854        unsafe { day_dom_scroll_to(h.0, target.origin.x, target.origin.y, u32::from(animated)) };
3855    }
3856
3857    fn scroll_offset(&mut self, h: &DomHandle) -> Point {
3858        let mut out = [0.0f64; 2];
3859        unsafe { day_dom_scroll_offset(h.0, out.as_mut_ptr()) };
3860        Point::new(out[0], out[1])
3861    }
3862
3863    fn set_event_sink(&mut self, sink: EventSink) {
3864        SINK.with(|s| *s.borrow_mut() = Some(sink));
3865    }
3866
3867    fn enable_gesture(&mut self, h: &DomHandle, node: NodeId, kind: GestureKind) {
3868        remember(h.0, node);
3869        // Idempotent per (element, kind): each shim recognizer is a set of listeners, which a
3870        // second `listen` would double.
3871        let mask = match kind {
3872            GestureKind::Tap => gesture_mask::TAP,
3873            GestureKind::Drag => gesture_mask::DRAG,
3874            GestureKind::Hover => gesture_mask::HOVER,
3875            GestureKind::LongPress => gesture_mask::LONG_PRESS,
3876            GestureKind::DoubleTap => gesture_mask::DOUBLE_TAP,
3877            GestureKind::Press => gesture_mask::PRESS,
3878            GestureKind::Touches => gesture_mask::TOUCHES,
3879            GestureKind::Pan => gesture_mask::PAN,
3880            GestureKind::Pinch => gesture_mask::PINCH,
3881            GestureKind::Rotate => gesture_mask::ROTATE,
3882        };
3883        listen_once(h.0, mask);
3884    }
3885
3886    /// Every kind is the shim's own recognizer over pointer events (docs/gestures.md
3887    /// "Recognizers"): long press and press from `pointerdown`, double tap from the browser's
3888    /// `dblclick`, touches from the pointer stream of every contact.
3889    fn gesture_support(&self, _kind: GestureKind) -> Support {
3890        Support::Native
3891    }
3892
3893    /// Leading and trailing follow the element's reading direction (`set_layout_direction`, else
3894    /// the app's).
3895    fn set_hit_slop(&mut self, h: &DomHandle, node: NodeId, slop: day_spec::Insets) {
3896        remember(h.0, node);
3897        let (left, right) = if element_rtl(h.0) {
3898            (slop.trailing, slop.leading)
3899        } else {
3900            (slop.leading, slop.trailing)
3901        };
3902        unsafe {
3903            day_dom_hit_slop(
3904                h.0,
3905                slop.top.max(0.0),
3906                left.max(0.0),
3907                slop.bottom.max(0.0),
3908                right.max(0.0),
3909            );
3910        }
3911    }
3912
3913    /// `touch-action: pan-y` / `pan-x` on the element, so the browser scrolls across the axis
3914    /// natively, and the shim's drag stands down at the slop when a mouse sets off across it.
3915    fn set_drag_axis(&mut self, h: &DomHandle, _node: NodeId, axis: Option<day_spec::DragAxis>) {
3916        let code = match axis {
3917            None => 0,
3918            Some(day_spec::DragAxis::Horizontal) => 1,
3919            Some(day_spec::DragAxis::Vertical) => 2,
3920        };
3921        unsafe { day_dom_drag_axis(h.0, code) };
3922    }
3923
3924    /// `inert` on the element (input, focus and the accessibility tree at once) plus
3925    /// `aria-disabled`; form controls keep their own `disabled` from day-core's patches.
3926    fn set_subtree_enabled(&mut self, h: &DomHandle, _node: NodeId, enabled: bool) {
3927        unsafe { day_dom_subtree_enabled(h.0, u32::from(enabled)) };
3928    }
3929
3930    /// The computed style mid-run (`getComputedStyle` reports what a Web Animation shows):
3931    /// opacity, the frame from `left`/`top`/`width`/`height` in the root's space, the
3932    /// transform's translation, and the fill of an element that has one (docs/tween.md).
3933    fn read_displayed(&self, h: &DomHandle) -> day_spec::Displayed {
3934        let mut v = [0.0f64; 11];
3935        // SAFETY: `v` has room for the eleven values the shim writes.
3936        let fill = unsafe { day_dom_displayed(h.0, v.as_mut_ptr()) } != 0;
3937        day_spec::Displayed {
3938            opacity: Some(v[0]),
3939            frame: Some(Rect::new(v[1], v[2], v[3], v[4])),
3940            translation: Some(Point::new(v[5], v[6])),
3941            background: fill.then(|| day_spec::Color::rgba(v[7], v[8], v[9], v[10])),
3942        }
3943    }
3944
3945    /// The browser's default font size against the 16 px (17 px under iOS Dynamic Type) Day's
3946    /// ramp is drawn for; one factor for every style.
3947    fn text_scale(&mut self, _style: Font) -> f64 {
3948        unsafe { day_dom_text_scale() }
3949    }
3950
3951    /// `dir` on the element (docs/localization.md "Direction of a subtree"): a label's or a
3952    /// field's base direction and what `start`/`end` alignment mean, a range's fill side. Day
3953    /// places children with `left`, so a container's own `dir` moves nothing; scrolling hosts
3954    /// keep theirs, since an RTL scroller counts its offsets from the right.
3955    fn set_layout_direction(
3956        &mut self,
3957        h: &DomHandle,
3958        kind: PieceKind,
3959        direction: day_spec::LayoutDirection,
3960    ) {
3961        if kind == kinds::SCROLL || kind == kinds::LIST || kind == kinds::NAV {
3962            return;
3963        }
3964        let rtl = direction == day_spec::LayoutDirection::Rtl;
3965        DIRECTION.with(|d| d.borrow_mut().insert(h.0, rtl));
3966        attr(h.0, "dir", if rtl { "rtl" } else { "ltr" });
3967        MEASURE_CACHE.with(|c| c.borrow_mut().retain(|(e, _), _| *e != h.0));
3968    }
3969
3970    /// `(pointer: coarse)` at launch, then the `pointerType` of each pointer down or hover.
3971    fn primary_pointer(&self) -> day_spec::PointerKind {
3972        pointer_kind(unsafe { day_dom_pointer_kind() })
3973    }
3974
3975    fn set_focusable(&mut self, h: &DomHandle, node: NodeId, focusable: bool) {
3976        remember(h.0, node);
3977        if focusable {
3978            unsafe {
3979                day_dom_canvas_keynav(h.0);
3980                // The key route reports focus both ways itself (shim `reportFocus`), and a
3981                // press focuses the element, so it is a pointer target from now on.
3982                day_dom_takes_pointer(h.0);
3983            };
3984        }
3985    }
3986
3987    fn focus(&mut self, h: &DomHandle, _node: NodeId, focused: bool) {
3988        unsafe { day_dom_focus(h.0, u32::from(focused)) };
3989    }
3990
3991    fn attach_list(&mut self, host: &DomHandle, source: ListSource) {
3992        let el = host.0;
3993        LISTS.with(|m| {
3994            if let Some(st) = m.borrow_mut().get_mut(&el) {
3995                st.source = Some(source);
3996            }
3997        });
3998        post_local(move || list_populate(el));
3999    }
4000
4001    fn set_route(&mut self, route: &str) {
4002        // First reflection rewrites the current entry (a fresh page load shouldn't grow
4003        // history just for showing its own launch route); every later change pushes one, so
4004        // browser back/forward walk the app's navigation.
4005        let replace = FIRST_ROUTE.with(|c| c.replace(false));
4006        unsafe { day_dom_set_hash(route.as_ptr(), route.len(), u32::from(replace)) };
4007    }
4008
4009    fn edit_toolbar(&mut self, h: &DomHandle, ops: &[day_spec::ToolbarOp]) -> bool {
4010        // The web has no window chrome, so the bar is a strip the shim docks at the top of the
4011        // document (docs/toolbars.md), edited one item at a time like every native bar. A
4012        // cover-tier window's items go on a strip over the cover, where its content can reach
4013        // them (the page's strip is underneath it).
4014        let json = toolbar_edit_json(ops);
4015        unsafe { day_dom_toolbar_edit(h.0, json.as_ptr(), json.len()) };
4016        true
4017    }
4018
4019    fn update_toolbar(&mut self, h: &DomHandle, patch: &day_spec::ToolbarPatch) {
4020        use day_spec::ToolbarPatch as P;
4021        let mut json = String::from("{\"item\":");
4022        match patch {
4023            P::Focus { item } => {
4024                json_str(&mut json, item);
4025                json.push_str(",\"focus\":true");
4026            }
4027            P::Text { item, text } => {
4028                json_str(&mut json, item);
4029                json.push_str(",\"text\":");
4030                json_str(&mut json, text);
4031            }
4032            P::On { item, on } => {
4033                json_str(&mut json, item);
4034                json.push_str(",\"on\":");
4035                json.push_str(if *on { "true" } else { "false" });
4036            }
4037            P::Selected { item, index } => {
4038                json_str(&mut json, item);
4039                json.push_str(",\"selected\":");
4040                json.push_str(&index.to_string());
4041            }
4042            P::Enabled { item, on } => {
4043                json_str(&mut json, item);
4044                json.push_str(",\"enabled\":");
4045                json.push_str(if *on { "true" } else { "false" });
4046            }
4047            P::Suggestions { item, list } => {
4048                json_str(&mut json, item);
4049                json.push_str(",\"suggestions\":[");
4050                for (n, sug) in list.iter().enumerate() {
4051                    if n > 0 {
4052                        json.push(',');
4053                    }
4054                    json_str(&mut json, sug);
4055                }
4056                json.push(']');
4057            }
4058            P::Label {
4059                item,
4060                label,
4061                tooltip,
4062            } => {
4063                json_str(&mut json, item);
4064                json.push_str(",\"label\":");
4065                json_str(&mut json, label);
4066                if let Some(tip) = tooltip {
4067                    json.push_str(",\"tip\":");
4068                    json_str(&mut json, tip);
4069                }
4070            }
4071            P::Placeholder { item, text } => {
4072                json_str(&mut json, item);
4073                json.push_str(",\"placeholder\":");
4074                json_str(&mut json, text);
4075            }
4076        }
4077        json.push('}');
4078        unsafe { day_dom_toolbar_patch(h.0, json.as_ptr(), json.len()) };
4079    }
4080    fn toggle_sidebar(&mut self, _host: &DomHandle) -> bool {
4081        // One window, one split: the host is implied. Same call the strip's own button makes,
4082        // so a dayscript walkthrough drives the real path (docs/toolbars.md).
4083        unsafe { day_dom_toolbar_sidebar() != 0 }
4084    }
4085
4086    fn set_app_menu(&mut self, items: &[MenuItem]) {
4087        install_app_menu(items);
4088    }
4089
4090    fn set_button_menu(&mut self, h: &DomHandle, _node: NodeId, f: day_spec::ContextMenuFn) {
4091        // The button's click already reaches `day_dom_event`, which opens the menu instead of
4092        // reporting a press. Announce the popup the way the app menu's button does.
4093        BUTTON_MENUS.with(|t| t.insert(h.0 as usize, f));
4094        attr(h.0, "aria-haspopup", "menu");
4095    }
4096
4097    fn set_context_menu(&mut self, h: &DomHandle, node: NodeId, _items: &[MenuItem]) {
4098        // The browser has no native menu to hand day's model to: arm the `contextmenu`
4099        // listener and report `Event::ContextMenu`; the pieces layer presents the COMPOSED
4100        // menu from its own copy of the items (docs/menus.md), so none are stored here.
4101        remember(h.0, node);
4102        listen_once(h.0, gesture_mask::CONTEXT_MENU);
4103    }
4104
4105    fn set_context_menu_fn(&mut self, h: &DomHandle, node: NodeId, _f: day_spec::ContextMenuFn) {
4106        // Summon-time menus take the same route as the static ones above: the event reaches
4107        // the piece that owns the provider, and the composed presenter calls it there.
4108        remember(h.0, node);
4109        listen_once(h.0, gesture_mask::CONTEXT_MENU);
4110    }
4111
4112    fn supports_lifecycle(&self, phase: Lifecycle) -> bool {
4113        matches!(
4114            phase,
4115            Lifecycle::WillLaunch
4116                | Lifecycle::DidLaunch
4117                | Lifecycle::DidBecomeActive
4118                | Lifecycle::WillResignActive
4119                | Lifecycle::DidExit
4120        )
4121    }
4122
4123    fn set_a11y(&mut self, h: &DomHandle, a11y: &A11yProps) {
4124        use day_spec::Role;
4125        if let Some(label) = &a11y.label {
4126            attr(h.0, "aria-label", label);
4127            APP_NAMED.with(|t| t.insert(h.0 as usize, ()));
4128        }
4129        // `aria-description`, not `title`: a title is also a tooltip, and the hint is for the
4130        // screen reader alone.
4131        if let Some(hint) = &a11y.hint {
4132            attr(h.0, "aria-description", hint);
4133        }
4134        // An explicit role retypes the element; a heading also carries its level. The shim's
4135        // `role` branch gives a retyped button its tab stop and keyboard activation.
4136        let role = match a11y.role {
4137            Role::None => None,
4138            Role::Button => Some("button"),
4139            Role::Toggle => Some("switch"),
4140            Role::Slider => Some("slider"),
4141            Role::TextInput => Some("textbox"),
4142            Role::Heading(_) => Some("heading"),
4143            Role::Image => Some("img"),
4144            Role::Meter => Some("meter"),
4145            Role::Group => Some("group"),
4146            Role::Tree => Some("tree"),
4147            Role::TreeItem => Some("treeitem"),
4148            Role::Tab => Some("tab"),
4149            Role::TabList => Some("tablist"),
4150        };
4151        if let Some(role) = role {
4152            attr(h.0, "role", role);
4153        }
4154        if let Role::Heading(level) = a11y.role {
4155            attr(h.0, "aria-level", &level.to_string());
4156        }
4157        if let Some(on) = a11y.selected {
4158            attr(h.0, "aria-selected", if on { "true" } else { "false" });
4159        }
4160        // A range role reads its value through `aria-valuetext`, with `aria-valuenow` beside it
4161        // when the text leads with a number ("72%" is 72). Any other role has no value
4162        // attribute, so the value rides the description, after the hint when there is one.
4163        if let Some(value) = &a11y.value {
4164            match a11y.role {
4165                Role::Meter | Role::Slider => {
4166                    attr(h.0, "aria-valuetext", value);
4167                    if let Some(n) = leading_number(value) {
4168                        attr(h.0, "aria-valuenow", &n.to_string());
4169                    }
4170                }
4171                _ => {
4172                    let described = match &a11y.hint {
4173                        Some(hint) => format!("{hint}. {value}"),
4174                        None => value.clone(),
4175                    };
4176                    attr(h.0, "aria-description", &described);
4177                }
4178            }
4179        }
4180        // Hidden takes the subtree out of the accessibility tree; the shim's `aria-hidden`
4181        // branch also takes it out of the tab order, which the attribute alone would not.
4182        if a11y.hidden || a11y.decorative {
4183            attr(h.0, "aria-hidden", "true");
4184        }
4185        // The Day element id (`.id(day_core::id!(counter_label))`) becomes the DOM id — the same duty that
4186        // sets accessibilityIdentifier on Apple backends. Day ids are app-unique by contract
4187        // (dayscript addresses by them), so they satisfy the DOM's uniqueness rule too. Only
4188        // nodes with native handles get one, exactly like every other backend.
4189        if let Some(id) = &a11y.identifier {
4190            attr(h.0, "id", id);
4191        }
4192    }
4193
4194    fn announce(&mut self, text: &str, urgent: bool) {
4195        // The shim's live regions (docs/accessibility.md): one per politeness, so an urgent
4196        // sentence interrupts and a polite one waits its turn.
4197        unsafe { day_dom_announce(text.as_ptr(), text.len(), u32::from(urgent)) };
4198    }
4199
4200    /// The element read back off the page, so `a11y_audit` and `assert_native` run on the web
4201    /// too. The DOM is the accessibility tree here: what `set_a11y` wrote is what a screen
4202    /// reader reads, and an element the page lost answers `found = false`. The rest is the
4203    /// control's own state as the browser holds it (the shim's `day_dom_read_native` says which
4204    /// property backs which field); a field the element does not carry stays `None`.
4205    fn read_native(&self, h: &DomHandle) -> day_spec::NativeSnapshot {
4206        use day_spec::Role;
4207        let el = h.0;
4208        let raw = read_buffer(|out, cap| unsafe { day_dom_read_native(el, out, cap) });
4209        if raw.is_empty() {
4210            return day_spec::NativeSnapshot::default();
4211        }
4212        // Twelve fields before the text, which goes last and whole: a field's contents may
4213        // hold the separator itself.
4214        let mut parts = raw.splitn(13, '\u{1f}');
4215        let mut next = || parts.next().filter(|s| !s.is_empty()).map(str::to_owned);
4216        let role = match next().as_deref() {
4217            Some("button") => Role::Button,
4218            Some("switch") => Role::Toggle,
4219            Some("slider") => Role::Slider,
4220            Some("textbox") => Role::TextInput,
4221            // The level is a second attribute and the audit ignores it.
4222            Some("heading") => Role::Heading(0),
4223            Some("img") => Role::Image,
4224            Some("meter") => Role::Meter,
4225            Some("group") => Role::Group,
4226            Some("tree") => Role::Tree,
4227            Some("treeitem") => Role::TreeItem,
4228            Some("tab") => Role::Tab,
4229            Some("tablist") => Role::TabList,
4230            _ => Role::None,
4231        };
4232        let label = next();
4233        let value = next();
4234        let identifier = next();
4235        let number = next().and_then(|s| s.parse::<f64>().ok());
4236        let flag = |s: Option<String>| match s.as_deref() {
4237            Some("1") => Some(true),
4238            Some("0") => Some(false),
4239            _ => None,
4240        };
4241        let checked = flag(next());
4242        let enabled = flag(next());
4243        let visible = flag(next());
4244        let mut coord = || next().and_then(|s| s.parse::<f64>().ok());
4245        let (x, y, w, hgt) = (coord(), coord(), coord(), coord());
4246        let frame = match (x, y, w, hgt) {
4247            (Some(x), Some(y), Some(w), Some(hgt)) => Some(Rect::new(x, y, w, hgt)),
4248            _ => None,
4249        };
4250        // "=" marks text the element shows, so an empty field still reads as `Some("")`.
4251        let text = next().and_then(|s| s.strip_prefix('=').map(str::to_owned));
4252        day_spec::NativeSnapshot {
4253            found: true,
4254            role,
4255            label,
4256            value,
4257            identifier,
4258            text,
4259            number,
4260            checked,
4261            enabled,
4262            visible,
4263            frame,
4264        }
4265    }
4266
4267    /// Hand the bytes to the browser's own decoder (docs/images.md).
4268    ///
4269    /// `createImageBitmap` is ASYNCHRONOUS, so nothing is answered here; the shim calls
4270    /// `day_dom_image_decoded` when it resolves. Every other backend completes inline — this is
4271    /// the one the request-id design was actually needed for.
4272    fn decode_image(&mut self, req: u64, id: day_spec::BitmapId, bytes: &[u8]) {
4273        // Seeded now because the browser reports neither: an `ImageBitmap` has no format and no
4274        // way to ask about alpha. Unknown counts as "may have alpha" — compositing an opaque
4275        // image as if it had one is harmless, the reverse loses transparency.
4276        let format = day_spec::ImageFormat::sniff(bytes);
4277        let has_alpha = !matches!(
4278            format,
4279            Some(day_spec::ImageFormat::Jpeg | day_spec::ImageFormat::Bmp)
4280        );
4281        BITMAP_INFO.with(|m| {
4282            m.borrow_mut().insert(
4283                id.0,
4284                day_spec::BitmapInfo {
4285                    pixels: Size::new(0.0, 0.0),
4286                    // Decoded bytes carry no density — a PNG is simply its pixels.
4287                    scale: 1.0,
4288                    format,
4289                    has_alpha,
4290                },
4291            )
4292        });
4293        // SAFETY: the shim copies the span out of wasm memory before the first await point.
4294        unsafe { day_dom_image_decode(req as u32, id.0 as f64, bytes.as_ptr(), bytes.len()) };
4295    }
4296
4297    fn image_info(&mut self, id: day_spec::BitmapId) -> Option<day_spec::BitmapInfo> {
4298        BITMAP_INFO.with(|m| m.borrow().get(&id.0).copied())
4299    }
4300
4301    fn encode_image(&mut self, req: u64, id: day_spec::BitmapId, spec: &day_spec::EncodeSpec) {
4302        use day_spec::ImageFormat as F;
4303        let refuse = |err: day_spec::ImageError| {
4304            emit(
4305                day_spec::WINDOW_NODE,
4306                Event::ImageEncoded {
4307                    req,
4308                    result: Err(err),
4309                },
4310            );
4311        };
4312        // An id this backend never decoded, or has released, is `Gone` here as everywhere else.
4313        if !BITMAP_INFO.with(|m| m.borrow().contains_key(&id.0)) {
4314            refuse(day_spec::ImageError::Gone);
4315            return;
4316        }
4317        let mime = match spec.format {
4318            F::Png => "image/png",
4319            F::Jpeg => "image/jpeg",
4320            F::Webp => "image/webp",
4321            // A canvas writes no TIFF, GIF or BMP; `encode_formats` says so before an app asks.
4322            _ => {
4323                refuse(day_spec::ImageError::Encode);
4324                return;
4325            }
4326        };
4327        // Refuse a type this engine cannot write rather than let `toBlob` substitute PNG for it.
4328        // SAFETY: `mime` is a 'static str the shim reads and does not keep.
4329        if unsafe { day_dom_image_can_encode(mime.as_ptr(), mime.len()) } == 0 {
4330            refuse(day_spec::ImageError::Encode);
4331            return;
4332        }
4333        let (fit_w, fit_h) = spec.fit.map_or((0.0, 0.0), |f| (f.width, f.height));
4334        // -1 means "the type's own default", which is what `toBlob` does with an absent quality.
4335        let quality = spec.quality.map_or(-1.0, |q| q.clamp(0.0, 1.0));
4336        // SAFETY: `mime` is a 'static str; the shim reads `fmt_len` bytes and copies what it keeps.
4337        unsafe {
4338            day_dom_image_encode(
4339                req as u32,
4340                id.0 as f64,
4341                mime.as_ptr(),
4342                mime.len(),
4343                quality,
4344                fit_w,
4345                fit_h,
4346            );
4347        };
4348    }
4349
4350    /// What a canvas WRITES (`toBlob` / `convertToBlob`). A browser READS far more than this —
4351    /// GIF, BMP, often AVIF — and the asymmetry is the platform's own, which is why this duty
4352    /// exists rather than letting `Cap::ImageEncode` imply everything decodable is encodable.
4353    fn encode_formats(&mut self) -> Vec<day_spec::ImageFormat> {
4354        use day_spec::ImageFormat::{Jpeg, Png, Webp};
4355        // Asked of the engine, not assumed: WebKit — the browser this project tests with — reads
4356        // WebP but does not write it, and `toBlob` would silently hand back PNG instead.
4357        [Png, Jpeg, Webp]
4358            .into_iter()
4359            .filter(|f| {
4360                let mime = f.mime();
4361                // SAFETY: a 'static str the shim reads and does not keep.
4362                unsafe { day_dom_image_can_encode(mime.as_ptr(), mime.len()) != 0 }
4363            })
4364            .collect()
4365    }
4366
4367    fn release_image(&mut self, id: day_spec::BitmapId) {
4368        BITMAP_INFO.with(|m| {
4369            m.borrow_mut().remove(&id.0);
4370        });
4371        // SAFETY: an id the shim either knows or does not; releasing an absent one is a no-op.
4372        unsafe { day_dom_image_release(id.0 as f64) };
4373    }
4374
4375    /// Replay a drawing into an offscreen bitmap (docs/canvas.md "Exporting") through the same
4376    /// painter the on-screen canvas uses. Like a decode, the browser answers on a later turn
4377    /// (`createImageBitmap` is a promise), through `day_dom_bitmap_rendered`.
4378    fn render_bitmap(
4379        &mut self,
4380        req: u64,
4381        id: day_spec::BitmapId,
4382        ops: &[DrawOp],
4383        size: Size,
4384        scale: f64,
4385    ) {
4386        let (pw, ph) = day_spec::export_pixels(size, scale);
4387        // Seeded now, as a decode is: the answer only confirms it or takes it back out.
4388        BITMAP_INFO.with(|m| {
4389            m.borrow_mut().insert(
4390                id.0,
4391                day_spec::BitmapInfo {
4392                    pixels: Size::new(f64::from(pw), f64::from(ph)),
4393                    scale,
4394                    format: None,
4395                    has_alpha: true,
4396                },
4397            )
4398        });
4399        let (buf, strs) = encode_ops(ops);
4400        // SAFETY: both spans outlive the call, and the shim paints from them synchronously
4401        // before its first await point.
4402        unsafe {
4403            day_dom_canvas_render_bitmap(
4404                req as u32,
4405                id.0 as f64,
4406                buf.as_ptr(),
4407                buf.len(),
4408                strs.as_ptr(),
4409                strs.len(),
4410                f64::from(pw),
4411                f64::from(ph),
4412                scale,
4413            );
4414        };
4415    }
4416
4417    fn request_frame(
4418        &mut self,
4419        _host: &DomHandle,
4420        cb: day_spec::FrameCallback,
4421    ) -> day_spec::CancelFrame {
4422        let token = day_core::frame::native::register(cb);
4423        let request = unsafe { day_dom_request_frame(token as f64) };
4424        Box::new(move || {
4425            day_core::frame::native::cancel(token);
4426            unsafe { day_dom_cancel_frame(request) };
4427        })
4428    }
4429
4430    fn replay(&mut self, h: &DomHandle, ops: &[DrawOp], size: Size) {
4431        let (buf, strs) = encode_ops(ops);
4432        unsafe {
4433            day_dom_canvas_replay(
4434                h.0,
4435                buf.as_ptr(),
4436                buf.len(),
4437                strs.as_ptr(),
4438                strs.len(),
4439                size.width,
4440                size.height,
4441            );
4442        };
4443    }
4444
4445    /// The shim's list (docs/fonts.md): CSS generic families with synthesized faces (a browser
4446    /// synthesizes bold and italic for any family) plus each bundled `FontFace`, read by the
4447    /// same grow-and-retry protocol as `env`.
4448    fn font_families(&mut self) -> Vec<day_spec::FontFamilyInfo> {
4449        let mut cap = 4096usize;
4450        let text = loop {
4451            let mut buf = vec![0u8; cap];
4452            let n = unsafe { day_dom_fonts(buf.as_mut_ptr(), buf.len()) };
4453            if n > cap {
4454                cap = n;
4455                continue;
4456            }
4457            if n == cap {
4458                cap *= 2;
4459                continue;
4460            }
4461            buf.truncate(n);
4462            break String::from_utf8_lossy(&buf).into_owned();
4463        };
4464        day_spec::parse_font_list(&text)
4465    }
4466
4467    /// `CanvasRenderingContext2D.measureText` with the CSS font the replay draws in
4468    /// (docs/fonts.md).
4469    fn measure_text(
4470        &mut self,
4471        text: &str,
4472        size: f64,
4473        font: &day_spec::CanvasFont,
4474    ) -> Option<day_spec::TextMetrics> {
4475        let family = font.family_str();
4476        let mut out = [0.0f64; 8];
4477        unsafe {
4478            day_dom_canvas_measure_text(
4479                text.as_ptr(),
4480                text.len(),
4481                size,
4482                u32::from(font.css_weight()),
4483                u32::from(font.italic),
4484                family.as_ptr(),
4485                family.len(),
4486                out.as_mut_ptr(),
4487            );
4488        };
4489        Some(day_spec::TextMetrics::from_slots(&out))
4490    }
4491
4492    fn prepare_snapshot(
4493        &mut self,
4494        host: Option<&Self::Handle>,
4495        revision: u32,
4496    ) -> Result<day_spec::capture::Readiness, String> {
4497        Ok(
4498            if unsafe { day_dom_prepare_snapshot(host.map_or(0, |h| h.0), revision) } != 0 {
4499                day_spec::capture::Readiness::Ready
4500            } else {
4501                day_spec::capture::Readiness::Pending
4502            },
4503        )
4504    }
4505
4506    /// Settled once no shown list is still gliding to where Day scrolled it and every shown list
4507    /// has reported the viewport it shows (`list_settled`): a scripted step after "scroll to
4508    /// row" or a row change then sees the rows the list shows now.
4509    fn ui_idle(&mut self) -> bool {
4510        list_settled()
4511    }
4512
4513    fn modifiers(&mut self) -> day_spec::Modifiers {
4514        let mask = unsafe { day_dom_modifiers() };
4515        // The shim's mask uses the wire bits (`Modifiers::bits`).
4516        day_spec::Modifiers::from_bits((mask & 7) as u8)
4517    }
4518
4519    fn present(&mut self, req: u64, spec: &PresentSpec) {
4520        // A save flow carries its staged bytes out with the request — the shim wraps them in a
4521        // Blob and clicks a download link, the browser's native "save" (docs/files.md).
4522        #[cfg(all(target_family = "wasm", target_os = "unknown"))]
4523        if let PresentSpec::SaveFile {
4524            title,
4525            suggested_name,
4526            src_path,
4527            ..
4528        } = spec
4529        {
4530            let bytes = day_spec::present::web_files::read(src_path).unwrap_or_default();
4531            let mut j = String::from("{\"kind\":\"save\",\"title\":");
4532            json_str(&mut j, title);
4533            j.push_str(",\"name\":");
4534            json_str(&mut j, suggested_name);
4535            j.push('}');
4536            unsafe {
4537                day_dom_present_save(req as u32, j.as_ptr(), j.len(), bytes.as_ptr(), bytes.len());
4538            };
4539            return;
4540        }
4541        let json = present_json(spec);
4542        if let Some(j) = json {
4543            unsafe { day_dom_present(req as u32, j.as_ptr(), j.len()) }
4544        } else {
4545            // Unsupported spec: answer dismissed so the await resolves.
4546            let node = day_spec::WINDOW_NODE;
4547            emit(
4548                node,
4549                Event::PresentResult {
4550                    req,
4551                    result: PresentResult::Dismissed,
4552                },
4553            );
4554        }
4555    }
4556
4557    fn dismiss(&mut self, req: u64) {
4558        unsafe { day_dom_dismiss(req as u32) };
4559    }
4560
4561    fn share_support(&self) -> day_spec::Support {
4562        if unsafe { day_dom_share_support() } {
4563            day_spec::Support::Native
4564        } else {
4565            day_spec::Support::Unsupported
4566        }
4567    }
4568    fn share(&mut self, spec: &day_spec::share::ShareSpec, _anchor: Option<&Self::Handle>) -> bool {
4569        let (url, title) = (&spec.url, &spec.title);
4570        unsafe { day_dom_share_url(url.as_ptr(), url.len(), title.as_ptr(), title.len()) }
4571    }
4572    fn open_url(&mut self, url: &str) {
4573        unsafe { day_dom_open_url(url.as_ptr(), url.len()) };
4574    }
4575
4576    fn system_color(&mut self, role: day_spec::SystemColor) -> day_spec::Color {
4577        let key = format!("system_color_{}", role as u8);
4578        let rgba: Vec<f64> = env(&key)
4579            .split(',')
4580            .filter_map(|s| s.parse().ok())
4581            .collect();
4582        if let [r, g, b, a] = rgba.as_slice() {
4583            day_spec::Color::rgba(*r, *g, *b, *a)
4584        } else {
4585            role.fallback(self.dark_mode())
4586        }
4587    }
4588
4589    fn dark_mode(&mut self) -> bool {
4590        DARK.with(std::cell::Cell::get)
4591    }
4592
4593    /// The browser's `prefers-reduced-motion: reduce` (docs/accessibility.md), read live: the
4594    /// shim's media query answers, and its `change` event reaches [`day_dom_motion_changed`].
4595    fn reduce_motion(&mut self) -> bool {
4596        env("reduce_motion") == "1"
4597    }
4598
4599    fn set_appearance(&mut self, dark: Option<bool>) {
4600        APPEARANCE.with(|a| a.set((dark, a.get().1)));
4601        apply_appearance();
4602    }
4603
4604    fn adopt(&mut self, raw: day_spec::RawHandle) -> DomHandle {
4605        DomHandle(raw as u32)
4606    }
4607}
4608
4609thread_local! {
4610    static MEASURE_CACHE: RefCell<HashMap<(u32, i64), Size>> = RefCell::new(HashMap::new());
4611}
4612
4613impl Platform for Dom {
4614    const TARGET: &'static str = "web-dom";
4615    const TOOLKIT: &'static str = "dom";
4616    // The host owns the loop: `run` hands back at once, and DidExit is its last callback.
4617    const RUN_ENDS_APP: bool = false;
4618
4619    fn run(self, options: WindowOptions, ready: Box<dyn FnOnce(Self, DomHandle, Size)>) {
4620        unsafe { day_dom_set_title(options.title.as_ptr(), options.title.len()) };
4621        // Before the viewport is read: the Standard chrome's rules can move the root down.
4622        // Frameless, the backgrounds, placement and resizability are the browser's to decide.
4623        let overlay = options.chrome == day_spec::WindowChrome::Overlay;
4624        let inset = unsafe { day_dom_window_chrome(u32::from(overlay)) };
4625        // The root's content reads its safe area while it builds, before any tree exists to
4626        // report into: seed it, as the first window's inset.
4627        if overlay && inset > 0.0 {
4628            log::debug!("web: title bar overlay inset {inset} at boot");
4629            day_core::seed_safe_area(day_spec::Insets {
4630                top: inset,
4631                ..Default::default()
4632            });
4633        }
4634        let w: f64 = env("vw").parse().unwrap_or(1000.0);
4635        let h: f64 = env("vh").parse().unwrap_or(700.0);
4636        LAST_VIEWPORT.with(|v| v.set(Size::new(w, h)));
4637        DARK.with(|d| d.set(env("dark") == "1"));
4638        // Root container: the shim pre-registers the `#day-root` element under this id.
4639        let root = self.root;
4640        ready(self, DomHandle(root), Size::new(w, h));
4641        // `ready` ran the app's root(), so its registrations are in. An app with its own
4642        // `app_menu` model reached the strip through `set_app_menu` with Settings…/About
4643        // injected by day-core; one without still gets the button when something registered,
4644        // the way a desktop's default bar carries those items (day-toolkit-appkit rebuilds its default
4645        // menu at this same point).
4646        if !day_core::has_app_menu() {
4647            install_app_menu(&registration_menu());
4648        }
4649    }
4650
4651    fn post(f: Box<dyn FnOnce() + Send>) {
4652        POSTED.with(|q| q.borrow_mut().push_back(f));
4653        unsafe { day_dom_schedule_post() };
4654    }
4655
4656    fn post_delayed(ms: u32, f: Box<dyn FnOnce() + Send>) {
4657        let token = NEXT_DELAY.with(|c| {
4658            let t = c.get();
4659            c.set(t.wrapping_add(1).max(1));
4660            t
4661        });
4662        DELAYED.with(|m| m.borrow_mut().insert(token, f));
4663        unsafe { day_dom_schedule_delayed(token, ms) };
4664    }
4665
4666    fn locale_hints(&self) -> Vec<String> {
4667        env("locales")
4668            .split(',')
4669            .map(str::to_owned)
4670            .filter(|s| !s.is_empty())
4671            .collect()
4672    }
4673}
4674
4675/// Post onto the (single-threaded) main loop without the `Send` bound.
4676fn post_local(f: impl FnOnce() + 'static) {
4677    // SAFETY-BY-CONSTRUCTION: wasm is single-threaded — the queue never crosses threads;
4678    // the Send bound on the queue is satisfied by wrapping in a type that is only ever
4679    // touched on this thread.
4680    struct NotSendButFine(Option<Box<dyn FnOnce()>>);
4681    unsafe impl Send for NotSendButFine {}
4682    let wrapped = NotSendButFine(Some(Box::new(f)));
4683    Dom::post(Box::new(move || {
4684        // Move the whole wrapper (not just its field) so the closure captures the Send type.
4685        let mut w = wrapped;
4686        if let Some(f) = w.0.take() {
4687            f();
4688        }
4689    }));
4690}
4691
4692// ---------------------------------------------------------------------------
4693// Kind helpers
4694// ---------------------------------------------------------------------------
4695
4696fn set_enabled(el: u32, enabled: bool) {
4697    attr(el, "disabled", if enabled { "" } else { "-" });
4698}
4699
4700/// A surface's styling on its element (docs/surfaces.md): fill, corners, clipping, border and
4701/// shadow. Idempotent: every property it owns is written and an absent one cleared, so a
4702/// `ContainerPatch::Surface` runs it again on the realized element. `role` is the realize-time
4703/// one ([`SURFACE_ROLES`]); a patch's own `role` is ignored. `anim` animates a solid fill;
4704/// `fresh` is the realize (see [`apply_fill`]).
4705fn apply_surface(
4706    el: u32,
4707    p: &ContainerProps,
4708    role: Option<day_spec::SurfaceRole>,
4709    anim: Option<&AnimSpec>,
4710    fresh: bool,
4711) {
4712    // A fresh element has nothing to clear: skip the empty writes.
4713    let set = |prop: &str, value: &str| {
4714        if !(fresh && value.is_empty()) {
4715            s(el, prop, value);
4716        }
4717    };
4718    let flag = |name: &str, on: bool| {
4719        if on || !fresh {
4720            class(el, name, on);
4721        }
4722    };
4723    let radius = p.corner_radius;
4724    match role {
4725        // The dimming under a composed sheet: the stylesheet frosts the page (`.day-scrim`,
4726        // day.css) instead of laying the plain color over it.
4727        Some(day_spec::SurfaceRole::Scrim) => class(el, "day-scrim", true),
4728        // The window's own surface: the page background a cover paints (`.day-cover`, day.css).
4729        Some(day_spec::SurfaceRole::Window) => s(el, "background-color", "var(--day-bg)"),
4730        _ => apply_fill(el, p.fill.as_ref(), anim, fresh),
4731    }
4732    // A shadowed surface does not clip (docs/surfaces.md): the shadow itself would survive
4733    // `overflow: hidden`, which cuts descendants only, but the rule is that content is not cut.
4734    let cuts = p.clips || (radius > 0.0 && p.shadow.is_none());
4735    let radii = if radius <= 0.0 {
4736        String::new()
4737    } else if p.corners == day_spec::Corners::ALL {
4738        format!("{radius}px")
4739    } else {
4740        let r = p.corners.radii(radius);
4741        format!(
4742            "{}px {}px {}px {}px",
4743            r.top_left, r.top_right, r.bottom_right, r.bottom_left
4744        )
4745    };
4746    set("border-radius", &radii);
4747    // A rounded clip inside a transformed (animated) ancestor hits a WebKit bug: the clip
4748    // layer's backing paints its SHARP bounding box black behind the rounded content. The
4749    // `.day-xform .day-clip` rule (day.css) gives such a clip its own correctly-clipped layer;
4750    // the class is inert everywhere else, so static rounded surfaces aren't promoted.
4751    flag("day-clip", radius > 0.0 && cuts);
4752    set("overflow", if cuts { "hidden" } else { "" });
4753    if role == Some(day_spec::SurfaceRole::SectionCard) {
4754        class(el, "day-card", true);
4755    }
4756    // The border is a layer of its own over the surface AND its content (`.day-bordered::after`,
4757    // day.css: the last box painted in the element) rather than a CSS `border`: children are
4758    // placed from the padding box, so a real border would move every one of them inward by its
4759    // width, and it would be painted under them.
4760    if let Some(b) = p.border.filter(|b| b.width > 0.0) {
4761        s(el, "--day-border-width", &format!("{}px", b.width));
4762        s(el, "--day-border-color", &ink_css(b.color));
4763        class(el, "day-bordered", true);
4764    } else {
4765        flag("day-bordered", false);
4766        set("--day-border-width", "");
4767        set("--day-border-color", "");
4768    }
4769    // `box-shadow` is the spec's shadow exactly: the blur radius is the same number, it follows
4770    // the per-corner radii, it paints outside the border box only, takes no layout room and no
4771    // pointer events.
4772    //
4773    // The second, invisible layer is for WebKit: a single blurred shadow in an opaque color
4774    // under an opaque fill takes a fast path there that paints the FILL color across the
4775    // shadow's middle, leaving only a rim of shadow. Two layers take the general path.
4776    let shadow = p.shadow.map_or_else(String::new, |sh| {
4777        format!(
4778            "{}px {}px {}px {},0 0 0 transparent",
4779            sh.dx,
4780            sh.dy,
4781            sh.blur.max(0.0),
4782            ink_css(sh.color)
4783        )
4784    });
4785    set("box-shadow", &shadow);
4786}
4787
4788/// A surface's fill (`ContainerProps::fill`, `ContainerPatch::Fill`): a solid ink is the
4789/// background color, animated with `anim` (docs/tween.md rule 8) and written as the ink's own
4790/// CSS so it follows the appearance; a gradient is the background image, with the color
4791/// cleared; `None` clears both, back to what the stylesheet gives the element. `fresh` is a
4792/// just-created element, which has nothing to clear and no animation to cancel.
4793fn apply_fill(el: u32, fill: Option<&day_spec::Paint>, anim: Option<&AnimSpec>, fresh: bool) {
4794    use day_spec::Paint;
4795    match fill {
4796        Some(Paint::Solid(ink)) if fresh => s(el, "background-color", &ink_css(*ink)),
4797        Some(Paint::Solid(ink)) => {
4798            // From the color shown to the new one under the whole contract; the shim writes
4799            // the resolved target and runs from what is displayed. A dynamic ink then replaces
4800            // the inline target with its own CSS, which the running animation overrides until
4801            // it ends.
4802            animate(
4803                el,
4804                anim_prop::BACKGROUND,
4805                &color_parts(ink.resolved()),
4806                anim,
4807            );
4808            if ink.is_dynamic() {
4809                s(el, "background-color", &ink_css(*ink));
4810            }
4811        }
4812        _ if fresh => {}
4813        _ => {
4814            animate(el, anim_prop::BACKGROUND, &[0.0; 4], None);
4815            s(el, "background-color", "");
4816        }
4817    }
4818    // A linear gradient depends on the frame (`linear_gradient_css`), so `set_frame` writes it
4819    // again at every size; radial and conic ones are given in fractions of the box.
4820    let image = match fill {
4821        Some(Paint::Linear(g)) => {
4822            let size = SURFACE_GRADIENTS
4823                .with(|t| t.get(el as usize))
4824                .map_or(Size::new(1.0, 1.0), |(_, size)| size);
4825            SURFACE_GRADIENTS.with(|t| t.insert(el as usize, (g.clone(), size)));
4826            linear_gradient_css(g, size)
4827        }
4828        Some(Paint::Radial(g)) => radial_gradient_css(g),
4829        Some(Paint::Conic(g)) => conic_gradient_css(g),
4830        Some(Paint::Solid(_)) | None => String::new(),
4831    };
4832    if !matches!(fill, Some(Paint::Linear(_))) {
4833        SURFACE_GRADIENTS.with(|t| t.remove(el as usize));
4834    }
4835    if !(fresh && image.is_empty()) {
4836        s(el, "background-image", &image);
4837    }
4838}
4839
4840/// Gradient stops as CSS color stops: each stop's ink (following the appearance) at its offset
4841/// as a percentage of the gradient line or ray.
4842fn css_stops(stops: &[(f64, day_spec::Ink)]) -> String {
4843    stops
4844        .iter()
4845        .map(|(off, c)| format!("{} {}%", ink_css(*c), off.clamp(0.0, 1.0) * 100.0))
4846        .collect::<Vec<_>>()
4847        .join(",")
4848}
4849
4850/// A surface's radial gradient as CSS (docs/surfaces.md): an ellipse whose radii are `radius` of
4851/// the box's width and of its height, so it is a circle in a square frame and stretches with a
4852/// non-square one, as the unit space of the frame does. The stops run along that radius, and the
4853/// last color holds beyond it.
4854fn radial_gradient_css(g: &day_spec::RadialGradient) -> String {
4855    if g.stops.len() < 2 {
4856        return flat_gradient_css(&g.stops);
4857    }
4858    let r = g.radius.max(0.0) * 100.0;
4859    format!(
4860        "radial-gradient(ellipse {r}% {r}% at {}% {}%,{})",
4861        g.center.x * 100.0,
4862        g.center.y * 100.0,
4863        css_stops(&g.stops)
4864    )
4865}
4866
4867/// A surface's conic gradient as CSS (docs/surfaces.md). Day's angles turn clockwise from +x; a
4868/// CSS conic gradient's turn clockwise from up, so the start moves a quarter turn on.
4869fn conic_gradient_css(g: &day_spec::ConicGradient) -> String {
4870    if g.stops.len() < 2 {
4871        return flat_gradient_css(&g.stops);
4872    }
4873    format!(
4874        "conic-gradient(from {}deg at {}% {}%,{})",
4875        g.start.degrees() + 90.0,
4876        g.center.x * 100.0,
4877        g.center.y * 100.0,
4878        css_stops(&g.stops)
4879    )
4880}
4881
4882/// A gradient with nothing to run between: one flat color, the last stop's (none if empty).
4883fn flat_gradient_css(stops: &[(f64, day_spec::Ink)]) -> String {
4884    let c = stops
4885        .last()
4886        .map_or_else(|| color_css(day_spec::Color::CLEAR), |s| ink_css(s.1));
4887    format!("linear-gradient({c},{c})")
4888}
4889
4890/// A surface's gradient as a CSS `linear-gradient(…)` for a box of `size`.
4891///
4892/// CSS places a gradient by an ANGLE through the box's center, with a length that makes the
4893/// end colors land in the corners; the spec places it by two unit points resolved against the
4894/// frame, which is how a canvas gradient is given. So this resolves the points, takes the angle
4895/// of the line through them, and moves each stop to where it falls on the CSS gradient line
4896/// (positions outside 0–100% are allowed, and the end colors hold flat beyond them as they do
4897/// on a canvas). The answer changes with the box's shape for any gradient that is not
4898/// axis-aligned, which is why `set_frame` asks again.
4899fn linear_gradient_css(g: &day_spec::LinearGradient, size: Size) -> String {
4900    let (w, h) = (
4901        if size.width > 0.0 { size.width } else { 1.0 },
4902        if size.height > 0.0 { size.height } else { 1.0 },
4903    );
4904    let (x0, y0) = (g.start.x * w, g.start.y * h);
4905    let (dx, dy) = (g.end.x * w - x0, g.end.y * h - y0);
4906    let len = dx.hypot(dy);
4907    if len < 1e-9 || g.stops.len() < 2 {
4908        // No direction, or nothing to run between: one flat color, the last stop's.
4909        return flat_gradient_css(&g.stops);
4910    }
4911    let (ux, uy) = (dx / len, dy / len);
4912    // CSS: 0deg points up and angles turn clockwise, and the line's length is
4913    // |w·sin| + |h·cos|, centered on the box.
4914    let angle = ux.atan2(-uy).to_degrees();
4915    let line = (w * ux).abs() + (h * uy).abs();
4916    let t0 = ((x0 - w / 2.0) * ux + (y0 - h / 2.0) * uy + line / 2.0) / line;
4917    let span = len / line;
4918    let stops: Vec<String> = g
4919        .stops
4920        .iter()
4921        .map(|(off, c)| {
4922            let at = (t0 + off.clamp(0.0, 1.0) * span) * 100.0;
4923            format!("{} {at}%", ink_css(*c))
4924        })
4925        .collect();
4926    format!("linear-gradient({angle}deg,{})", stops.join(","))
4927}
4928
4929fn apply_area_attrs(el: u32, editable: bool, selectable: bool, spellcheck: bool) {
4930    if !editable {
4931        attr(el, "readonly", "-");
4932    }
4933    if !selectable {
4934        s(el, "user-select", "none");
4935    }
4936    attr(el, "spellcheck", if spellcheck { "true" } else { "false" });
4937}
4938
4939fn realize_picker(p: &PickerProps) -> u32 {
4940    let json = picker_json(p);
4941    // Intrinsic size from the option strings — measuring the element itself would concatenate
4942    // every option's text into one line.
4943    let longest = p
4944        .options
4945        .iter()
4946        .map(|o| measure_str(o).width)
4947        .fold(0.0f64, f64::max);
4948    let n = p.options.len() as f64;
4949    let el = match p.style {
4950        PickerStyle::Menu => {
4951            let el = unsafe { day_dom_create(EL_SELECT) };
4952            PICKER_SELECTED.with(|m| m.borrow_mut().insert(el, p.selected));
4953            unsafe { day_dom_options(el, json.as_ptr(), json.len()) }; // shim fills <option>s
4954            unsafe { day_dom_listen(el, 4) };
4955            PICKER_SIZE.with(|m| m.borrow_mut().insert(el, Size::new(longest + 38.0, 26.0)));
4956            el
4957        }
4958        PickerStyle::Segmented | PickerStyle::Inline => {
4959            let segmented = p.style == PickerStyle::Segmented;
4960            let el = unsafe { day_dom_create(if segmented { EL_SEGMENTED } else { EL_RADIOS }) };
4961            PICKER_SELECTED.with(|m| m.borrow_mut().insert(el, p.selected));
4962            unsafe { day_dom_options(el, json.as_ptr(), json.len()) };
4963            SEG_COUNT.with(|m| m.borrow_mut().insert(el, p.options.len()));
4964            let size = if segmented {
4965                let total: f64 = p.options.iter().map(|o| measure_str(o).width + 28.0).sum();
4966                Size::new(total + 4.0, 28.0)
4967            } else {
4968                Size::new(longest + 28.0, n * 24.0 + (n - 1.0).max(0.0) * 4.0)
4969            };
4970            PICKER_SIZE.with(|m| m.borrow_mut().insert(el, size));
4971            el
4972        }
4973    };
4974    // After the options exist, so a segmented or inline group passes it to its buttons.
4975    if !p.enabled {
4976        set_enabled(el, false);
4977    }
4978    el
4979}
4980
4981fn picker_json(p: &PickerProps) -> String {
4982    let mut json = String::from("{\"options\":[");
4983    for (i, o) in p.options.iter().enumerate() {
4984        if i > 0 {
4985            json.push(',');
4986        }
4987        json_str(&mut json, o);
4988    }
4989    json.push_str("],\"selected\":");
4990    json.push_str(&p.selected.to_string());
4991    json.push('}');
4992    json
4993}
4994
4995/// The properties the shim animates (`animateProp` in shim.js).
4996mod anim_prop {
4997    pub const OPACITY: u32 = 0;
4998    pub const TRANSFORM: u32 = 1;
4999    pub const BACKGROUND: u32 = 2;
5000    pub const FRAME: u32 = 3;
5001}
5002
5003/// Set `prop` of `el` to `to`, playing the whole `AnimSpec` contract when `anim` is given
5004/// (docs/tween.md): Day's own samples of one cycle as the keyframes (two for `Linear`, which
5005/// needs no more), the delay, the cycles and the alternate direction. `None` sets at once and
5006/// cancels a run on that property.
5007fn animate(el: u32, prop: u32, to: &[f64], anim: Option<&AnimSpec>) {
5008    let (samples, duration, delay, iterations, alternate) = match anim {
5009        Some(a) if a.duration_ms > 0 => {
5010            let samples: Vec<f64> = if matches!(a.curve, Curve::Linear) {
5011                vec![0.0, 0.0, 1.0, 1.0]
5012            } else {
5013                a.keyframes()
5014                    .iter()
5015                    .flat_map(|k| [k.offset, k.progress])
5016                    .collect()
5017            };
5018            let iterations = a.cycles().map_or(-1.0, f64::from);
5019            (
5020                samples,
5021                f64::from(a.duration_ms),
5022                f64::from(a.delay_ms),
5023                iterations,
5024                u32::from(a.autoreverse),
5025            )
5026        }
5027        _ => (Vec::new(), 0.0, 0.0, 1.0, 0),
5028    };
5029    // SAFETY: both slices outlive the call; the shim copies them before returning.
5030    unsafe {
5031        day_dom_animate(
5032            el,
5033            prop,
5034            to.as_ptr(),
5035            to.len(),
5036            samples.as_ptr(),
5037            samples.len(),
5038            duration,
5039            delay,
5040            iterations,
5041            alternate,
5042        );
5043    }
5044}
5045
5046/// A color as the shim's `[r, g, b, a]`.
5047fn color_parts(c: day_spec::Color) -> [f64; 4] {
5048    [c.r, c.g, c.b, c.a]
5049}
5050
5051fn nav_patch(el: u32, p: &NavPatch) {
5052    // Re-present rebuilds chrome and re-homes pages — it needs the state map unborrowed while it
5053    // calls back into the shim, so it runs outside the borrow below.
5054    if let NavPatch::Presentation(next) = p {
5055        nav_present(el, *next);
5056        return;
5057    }
5058    NAV_STATE.with(|m| {
5059        let mut m = m.borrow_mut();
5060        let Some(state) = m.get_mut(&el) else { return };
5061        match p {
5062            // Handled above, before the borrow.
5063            #[expect(
5064                clippy::match_same_arms,
5065                reason = "each group of no-op patches keeps its own arm and the comment saying why"
5066            )]
5067            NavPatch::Presentation(_) => {}
5068            // Never arrives: this backend answers `Cap::NavContentList` Unsupported, so the
5069            // pieces layer composes the pane itself (docs/navigation.md).
5070            #[expect(
5071                clippy::match_same_arms,
5072                reason = "each group of no-op patches keeps its own arm and the comment saying why"
5073            )]
5074            NavPatch::ListVisible(_) | NavPatch::ListInStack(_) => {}
5075            // Resident-page switch (docs/navigation.md): every page stays in the DOM and only
5076            // one is displayed, so a tab switch costs a `display` flip and keeps the other
5077            // tabs' scroll offsets and focused fields exactly as the user left them.
5078            NavPatch::Select(i) => {
5079                state.selected = *i;
5080                for (n, page) in state.pages.iter().enumerate() {
5081                    s(*page, "display", if n == *i { "block" } else { "none" });
5082                }
5083                sync_back_bar(el, state);
5084            }
5085            NavPatch::Pushed { title, .. } => {
5086                state.titles.push(title.clone());
5087                let last = state.pages.len().saturating_sub(1);
5088                state.selected = last;
5089                for (i, page) in state.pages.iter().enumerate() {
5090                    s(*page, "display", if i == last { "block" } else { "none" });
5091                }
5092                sync_back_bar(el, state);
5093            }
5094            NavPatch::Popped => {
5095                if state.titles.len() > 1 {
5096                    state.titles.pop();
5097                }
5098                let n = state.pages.len();
5099                if let Some(top) = state.pages.last() {
5100                    s(*top, "display", "none");
5101                }
5102                if n >= 2 {
5103                    s(state.pages[n - 2], "display", "block");
5104                }
5105                state.selected = n.saturating_sub(2);
5106                sync_back_bar_at(el, state, n.saturating_sub(1));
5107            }
5108            // The custom back bar routes back through Day; no native auto-pop to suppress.
5109            NavPatch::GuardTop(_) => {}
5110            NavPatch::Reorder(order) => {
5111                let old = state.pages.clone();
5112                state.pages = order.iter().filter_map(|i| old.get(*i).copied()).collect();
5113            }
5114            NavPatch::Title(t) => {
5115                if let Some(last) = state.titles.last_mut() {
5116                    last.clone_from(t);
5117                }
5118                sync_back_bar(el, state);
5119            }
5120        }
5121    });
5122}
5123
5124fn sync_back_bar(el: u32, state: &NavState) {
5125    sync_back_bar_at(el, state, state.pages.len());
5126}
5127
5128/// Re-present a live nav host (docs/size-classes.md): the window crossed a breakpoint, so the
5129/// chrome changes but the pages do not.
5130///
5131/// The whole point is that no page is rebuilt. The shim rebuilds the host's own chrome and leaves
5132/// the page elements detached-but-alive; this function then re-homes each one by its PANE, which
5133/// is the only thing that differs between the two presentations:
5134///
5135/// - `Split` — the sidebar page gets its own pane; `pages` holds detail pages alone.
5136/// - `Stack` — the sidebar page is the stack's root, so it heads `pages`.
5137/// - `Tabs` / `Rail` — the sidebar page moves into the CHROME slot, where its `NAV_MENU` lays
5138///   out as a bar or a strip. It is the same element with the same click handlers and the same
5139///   selection sync; only its container and its CSS class change, which is why a morph costs no
5140///   rebuilding on either side of the boundary.
5141fn nav_present(el: u32, next: NavPresentation) {
5142    let Some((sidebar, mut pages, was, selected)) = NAV_STATE.with(|m| {
5143        let st = m.borrow();
5144        let s = st.get(&el)?;
5145        Some((s.sidebar, s.pages.clone(), s.presentation, s.selected))
5146    }) else {
5147        return;
5148    };
5149    if was == next {
5150        return;
5151    }
5152    // Which page is on screen, by IDENTITY rather than index: moving the sidebar page in or out
5153    // of the detail list below shifts every index past it, so an index captured now would point
5154    // at the wrong page afterwards.
5155    let shown_node = pages.get(selected).copied();
5156    // The sidebar page is a stack ROOT only while stacked; everywhere else it is chrome or its
5157    // own pane, and so leaves the detail list.
5158    if let Some(side) = sidebar {
5159        pages.retain(|p| *p != side);
5160        if next == NavPresentation::Stack {
5161            pages.insert(0, side);
5162        }
5163    }
5164    unsafe { day_dom_nav_present(el, nav_mode(next)) };
5165    if let Some(side) = sidebar
5166        && next != NavPresentation::Stack
5167    {
5168        unsafe { day_dom_nav_add_page(el, side, 1) };
5169        // The chrome slot always shows its page; it may have been hidden as a stack root under
5170        // a pushed detail.
5171        s(side, "display", "block");
5172    }
5173    // The page the user is looking at STAYS the page the user is looking at. `selected` tracks
5174    // exactly that in every presentation — push and pop maintain it too — so carrying it across
5175    // is the whole of "re-present without rebuilding".
5176    //
5177    // Getting this from the page ORDER instead does not work when leaving a tab bar: the pieces
5178    // layer keeps the selected page and disposes the rest, so a backend that showed the last
5179    // page would hide the one survivor and the detail pane would come up empty.
5180    //
5181    // Its index in the REARRANGED list. Falling back to the last page covers the one case where
5182    // it is not there any more: a stack showing only its root, whose root has just left the
5183    // detail list to become a sidebar pane.
5184    let shown = shown_node
5185        .and_then(|n| pages.iter().position(|p| *p == n))
5186        .unwrap_or_else(|| pages.len().saturating_sub(1));
5187    for (i, page) in pages.iter().enumerate() {
5188        unsafe { day_dom_nav_add_page(el, *page, 0) };
5189        s(*page, "display", if i == shown { "block" } else { "none" });
5190    }
5191    // The back bar belongs to the stack presentation alone, and its visibility depends on the
5192    // page count we just settled — so commit the state first, then sync from it.
5193    NAV_STATE.with(|m| {
5194        let mut m = m.borrow_mut();
5195        if let Some(st) = m.get_mut(&el) {
5196            st.presentation = next;
5197            st.pages = pages;
5198            st.selected = shown;
5199            sync_back_bar(el, st);
5200        }
5201    });
5202}
5203
5204/// Stack presentation: the back bar shows while pushed pages are on top (`depth` counts the
5205/// pages that will remain after the in-flight patch). Every other presentation has its own way
5206/// out — a sidebar row, a tab — and never shows it.
5207fn sync_back_bar_at(el: u32, state: &NavState, depth: usize) {
5208    let visible =
5209        state.presentation == NavPresentation::Stack && depth >= 1 && state.titles.len() > 1;
5210    let title = state.titles.last().cloned().unwrap_or_default();
5211    unsafe { day_dom_nav_back_bar(el, u32::from(visible), title.as_ptr(), title.len()) };
5212}
5213
5214// ---------------------------------------------------------------------------
5215// Emulated list (docs/list.md): cells over the ListSource pull contract, the Qt shape — and,
5216// like Qt and XAML, only the rows the viewport SHOWS are realized. That is the promise `list`
5217// makes over `each` ("builds only the rows the native widget currently shows"); building all of
5218// them is what a ten-thousand-row query cost before: ten thousand elements and ten thousand row
5219// layouts, in wasm, before the first paint. Cell index stays == row index for the cell's whole
5220// life, so nothing about selection or the click handler's row changes.
5221// ---------------------------------------------------------------------------
5222
5223/// Rows built beyond each edge of the viewport, so a flick has something to show before the
5224/// scroll event lands.
5225const LIST_OVERSCAN: usize = 8;
5226
5227/// A source change under the cells: everything realized is now showing the wrong row's data, so
5228/// mark it all dirty and refill the window. Reload and splice come through here — the callers
5229/// that used to rebind all n rows.
5230fn list_populate(host: u32) {
5231    LISTS.with(|m| {
5232        let mut m = m.borrow_mut();
5233        let Some(st) = m.get_mut(&host) else {
5234            return;
5235        };
5236        st.bound.iter_mut().for_each(|b| *b = false);
5237        // The pinned header may now be a different section's, or an item's row.
5238        st.pin_row = None;
5239        // A source that SHRANK leaves realized cells past its end. They stay in the pool (index
5240        // == row, so a source that grows back reuses each for the row it always held) and are
5241        // simply hidden — the same append-only pool, minus the eager building.
5242        let n = st.source.as_ref().map_or(0, |src| (src.len)());
5243        let recycle = st.source.as_ref().map(|src| src.recycle.clone());
5244        let stale: Vec<u32> = st
5245            .cells
5246            .iter()
5247            .skip(n)
5248            .copied()
5249            .filter(|c| *c != 0)
5250            .collect();
5251        drop(m);
5252        for cell in stale {
5253            s(cell, "display", "none");
5254            // A hidden row past the shrunk source keeps its pooled cell but must stop
5255            // answering dayscript lookups — clear its element ids (day-core's recycle).
5256            if let Some(recycle) = &recycle {
5257                recycle(cell as usize as day_spec::RawHandle);
5258            }
5259        }
5260    });
5261    list_fill_window(host);
5262}
5263
5264/// Build the rows the viewport shows and that are not built already. Idempotent and cheap when
5265/// nothing moved, which is what lets every scroll event call it.
5266fn list_fill_window(host: u32) {
5267    let Some((content, rowh, source, work, n, width, separators, selectable, seen, tops)) = LISTS
5268        .with(|m| {
5269            let mut m = m.borrow_mut();
5270            let st = m.get_mut(&host)?;
5271            let source = st.source.clone()?;
5272            let (content, rowh, selectable) = (st.content, st.row_height.max(1.0), st.selectable);
5273            let separators = st.separators;
5274            let n = (source.len)();
5275            let width = unsafe { day_dom_width(host) }.max(1.0);
5276            // The rows on screen, plus the overscan. A list the browser has not laid out yet reports
5277            // no height — build a screen's worth then, and let the scroll that follows extend it.
5278            let mut view = [0.0_f64; 2];
5279            unsafe { day_dom_list_viewport(host, view.as_mut_ptr()) };
5280            let laid_out = view[1] > 0.0;
5281            let (offset, vh) = (view[0], if laid_out { view[1] } else { 600.0 });
5282            // A self-sizing list's rows stand where their heights add up to; a uniform list's
5283            // at multiples of the pitch, with no per-row table to build.
5284            let tops = st.stacked().then(|| st.tops(n));
5285            // (first visible, last visible): rows with any part in the viewport, overscan
5286            // excluded; `end` is one past the last.
5287            let (first_visible, end) = match &tops {
5288                Some(tops) => {
5289                    // The row whose span holds `offset`, and the first row starting below the
5290                    // viewport's bottom edge.
5291                    let at = tops[..n]
5292                        .partition_point(|t| *t <= offset)
5293                        .saturating_sub(1);
5294                    let end = tops[..n].partition_point(|t| *t < offset + vh);
5295                    (at.min(n.saturating_sub(1)), end)
5296                }
5297                None => (
5298                    ((offset / rowh).floor() as usize).min(n.saturating_sub(1)),
5299                    (((offset + vh) / rowh).ceil() as usize).min(n),
5300                ),
5301            };
5302            let (first, last) = (
5303                first_visible.saturating_sub(LIST_OVERSCAN),
5304                (end + LIST_OVERSCAN).min(n),
5305            );
5306            let extent = tops.as_ref().map_or(n as f64 * rowh, |t| t[n]);
5307            if laid_out {
5308                st.seen = Some((offset, vh, n));
5309            }
5310            // What the viewport report says (docs/list.md "Viewport"), for a laid-out list
5311            // with rows: the visible range and how far the content runs past the bottom edge.
5312            let seen = (laid_out && n > 0).then(|| day_spec::ListViewport {
5313                first: first_visible,
5314                last: end.saturating_sub(1).clamp(first_visible, n - 1),
5315                end_distance: (extent - (offset + vh)).max(0.0),
5316            });
5317            // Slots exist for every row (a Vec of zeros, not of elements): the cell for row i lives
5318            // at i for good, which is what keeps the click handler's recorded row honest.
5319            if st.cells.len() < n {
5320                st.cells.resize(n, 0);
5321                st.bound.resize(n, false);
5322            }
5323            if st.stacked() && st.heights.len() < n {
5324                st.heights.resize(n, 0.0);
5325            }
5326            // (row, cell, is a section header, is a supplementary row): both take their laid
5327            // height even in a uniform list, and neither is drawn or wired as an item.
5328            let mut work: Vec<(usize, u32, bool, bool)> = Vec::new();
5329            for i in first..last {
5330                if st.cells[i] == 0 {
5331                    let cell = unsafe { day_dom_create(EL_CELL) };
5332                    // Appended, not inserted at the row index: cells are absolutely framed, so
5333                    // document order says nothing about where a row appears — and a window filled
5334                    // out of order (scroll down, then back up) has no meaningful index to insert at.
5335                    unsafe { day_dom_insert(content, cell, u32::MAX) };
5336                    if selectable {
5337                        unsafe { day_dom_listen(cell, 1) };
5338                        // The role pairs with the host's `listbox` (day_dom_list_keynav): it is what
5339                        // makes the arrow keys below mean something to a screen reader, and what
5340                        // gives `aria-selected` somewhere to live.
5341                        attr(cell, "role", "option");
5342                        CELL_ROWS.with(|m| m.borrow_mut().insert(cell, (host, i)));
5343                    }
5344                    st.cells[i] = cell;
5345                }
5346                if !st.bound[i] {
5347                    st.bound[i] = true;
5348                    work.push((i, st.cells[i], st.is_header(i), st.is_supplement(i)));
5349                }
5350            }
5351            st.last_width = width;
5352            Some((
5353                content, rowh, source, work, n, width, separators, selectable, seen, tops,
5354            ))
5355        })
5356    else {
5357        return;
5358    };
5359    // Application observers can synchronously rebuild overlays and relayout this list.
5360    // Report only after releasing LISTS, just like bind_row below. Layout can hold the core
5361    // tree borrow, so the report goes out on the next loop turn, after both the tree and the
5362    // list registry are free. The full viewport report supersedes the first-row one: both feed
5363    // the same state, and the first-only one would overwrite the range with a single row.
5364    if let Some(seen) = seen
5365        && (source.viewport.is_some() || source.first_visible.is_some())
5366    {
5367        post_local(move || {
5368            let source = LISTS.with(|m| m.borrow().get(&host).and_then(|st| st.source.clone()));
5369            let Some(source) = source else { return };
5370            if let Some(report) = &source.viewport {
5371                report(seen);
5372            } else if let Some(report) = &source.first_visible {
5373                report(seen.first.min((source.len)().saturating_sub(1)));
5374            }
5375        });
5376    }
5377    let mut measured = false;
5378    let automatic = LISTS.with(|m| m.borrow().get(&host).is_some_and(|st| st.automatic));
5379    for &(i, cell, header, supplement) in &work {
5380        let (top, height) = match &tops {
5381            Some(t) => (t[i], t[i + 1] - t[i]),
5382            None => (i as f64 * rowh, rowh),
5383        };
5384        unsafe {
5385            day_dom_set_frame(cell, 0.0, top, width, height);
5386        }
5387        s(cell, "display", "block");
5388        // Cell index is row index, so a reload that moves the section breaks can turn an
5389        // item's cell into a header's and back: set (or clear) the header treatment every bind.
5390        if source.is_header.is_some() || source.is_supplement.is_some() {
5391            list_style_header(cell, header, selectable);
5392            list_style_supplement(cell, supplement);
5393        }
5394        if separators && !header && !supplement {
5395            // Inside the frame (border-box), so the line lands exactly on the row boundary
5396            // without growing the cell past its pitch.
5397            s(cell, "box-sizing", "border-box");
5398            s(
5399                cell,
5400                "border-bottom",
5401                "1px solid color-mix(in srgb, currentColor 18%, transparent)",
5402            );
5403        }
5404        (source.bind_row)(i, cell as usize as day_spec::RawHandle);
5405        // A self-sizing row takes the height Day just laid it at. `0.0` means the tree was
5406        // busy; the row keeps its estimate until a resize reaches it. A uniform list's items
5407        // keep the pitch, so only its headers are measured.
5408        if tops.is_some() && (automatic || header || supplement) {
5409            let laid = (source.cell_height)(cell as usize as day_spec::RawHandle);
5410            if laid > 0.0 {
5411                measured |= LISTS.with(|m| {
5412                    m.borrow_mut()
5413                        .get_mut(&host)
5414                        .and_then(|st| st.heights.get_mut(i))
5415                        .is_some_and(|h| {
5416                            let changed = (*h - laid).abs() > 0.25;
5417                            *h = laid;
5418                            changed
5419                        })
5420                });
5421            }
5422        }
5423    }
5424    s(content, "position", "relative");
5425    // The extent is the whole source, built or not: the scrollbar is how the user reaches rows
5426    // that do not exist yet, so it cannot be sized to what happens to be realized.
5427    match &tops {
5428        Some(t) => s(content, "height", &format!("{}px", t[n])),
5429        None => s(content, "height", &format!("{}px", n as f64 * rowh)),
5430    }
5431    // Measured rows moved every row after them, and rows the estimate placed off screen may
5432    // now be in view: restack, then fill again (a no-op once every row in view is built).
5433    if measured {
5434        list_restack(host);
5435        post_local(move || list_fill_window(host));
5436    }
5437    // A row jump that arrived before this extent existed lands now; its scroll event builds the
5438    // rows it reveals.
5439    let pending = LISTS.with(|m| {
5440        m.borrow_mut()
5441            .get_mut(&host)
5442            .and_then(|st| st.pending_scroll.take())
5443    });
5444    if let Some(y) = pending {
5445        unsafe { day_dom_scroll_to(host, 0.0, y, 0) };
5446    }
5447    // Rows realized just now start unpainted, and a reload can move which rows are selected
5448    // under a selection that never changed — so repaint from the entry's set on every fill.
5449    LISTS.with(|m| {
5450        if let Some(st) = m.borrow().get(&host) {
5451            list_paint_selection(st);
5452        }
5453    });
5454    list_pin_header(host);
5455}
5456
5457/// The look and wiring of a sectioned list's row: a header reads as a group heading (an opaque
5458/// band in the sidebar tone, which also beats the stylesheet's row hover), carries the heading
5459/// role instead of `option`, and draws no separator; an item gets its row role back.
5460fn list_style_header(cell: u32, header: bool, selectable: bool) {
5461    if header {
5462        s(cell, "background", "var(--day-sidebar-bg)");
5463        s(cell, "border-bottom", "");
5464        attr(cell, "role", "heading");
5465        attr(cell, "aria-level", "2");
5466        attr(cell, "aria-selected", "");
5467    } else {
5468        s(cell, "background", "");
5469        attr(cell, "role", if selectable { "option" } else { "" });
5470        attr(cell, "aria-level", "");
5471    }
5472}
5473
5474/// A supplementary row (docs/list.md "Header, footer and empty state"): no row role, no
5475/// separator, no hover or selection highlight. Runs after `list_style_header`, which gives an
5476/// item row its role back.
5477fn list_style_supplement(cell: u32, supplement: bool) {
5478    class(cell, "day-supplement", supplement);
5479    if supplement {
5480        attr(cell, "role", "");
5481        attr(cell, "aria-selected", "");
5482        s(cell, "border-bottom", "");
5483    }
5484}
5485
5486/// Pin the header of the section under the list's top edge (docs/list.md "Sections"). The
5487/// rows are absolutely framed inside the content, so the real header row cannot stick; the
5488/// host keeps one extra cell in a strip that does: `position: sticky` at the top of the scroll
5489/// content, with a negative bottom margin so it takes no room from the rows. The browser
5490/// keeps the strip pinned while scrolling, so only a change of section, and the push-up as the
5491/// next header arrives, wait for this pass (a microtask after the scroll event, before paint).
5492fn list_pin_header(host: u32) {
5493    // Read the placement under the borrow; create, bind and style after it, since a bind
5494    // re-enters day-core and its patches can come back here.
5495    let Some(plan) = LISTS.with(|m| {
5496        let m = m.borrow();
5497        let st = m.get(&host)?;
5498        let pin = st.pin;
5499        let hidden = Some((pin, None));
5500        if !st.sectioned() {
5501            return if pin.0 != 0 { hidden } else { None };
5502        }
5503        let n = st.source.as_ref().map_or(0, |src| (src.len)());
5504        if n == 0 {
5505            return hidden;
5506        }
5507        let mut view = [0.0_f64; 2];
5508        unsafe { day_dom_list_viewport(host, view.as_mut_ptr()) };
5509        let offset = view[0];
5510        let tops = st.tops(n);
5511        let at = tops[..n]
5512            .partition_point(|t| *t <= offset)
5513            .saturating_sub(1)
5514            .min(n - 1);
5515        let Some(h) = st.header_of(at) else {
5516            return hidden;
5517        };
5518        // The real header is still at (or below) the top edge: it shows itself.
5519        if tops[h] >= offset - 0.5 {
5520            return hidden;
5521        }
5522        let height = tops[h + 1] - tops[h];
5523        // The next section's header pushes the pin up rather than sliding under it.
5524        let next = (h + 1..n).find(|i| st.is_header(*i));
5525        let push = next.map_or(0.0, |k| (tops[k] - offset - height).min(0.0));
5526        let source = st.source.clone()?;
5527        let rebind = st.pin_row != Some(h);
5528        Some((pin, Some((source, h, height, push, rebind))))
5529    }) else {
5530        return;
5531    };
5532    let ((mut wrapper, mut cell), show) = plan;
5533    let Some((source, h, height, push, rebind)) = show else {
5534        if wrapper != 0 {
5535            s(wrapper, "display", "none");
5536        }
5537        return;
5538    };
5539    if wrapper == 0 {
5540        wrapper = unsafe { day_dom_create(EL_DIV) };
5541        cell = unsafe { day_dom_create(EL_CELL) };
5542        unsafe { day_dom_insert(wrapper, cell, 0) };
5543        // Before the rows' content, so the sticky strip's natural place is the list's top.
5544        unsafe { day_dom_insert(host, wrapper, 0) };
5545        s(wrapper, "position", "sticky");
5546        s(wrapper, "top", "0");
5547        s(wrapper, "z-index", "2");
5548        // A copy of a header the list already has: assistive tech reads the real one.
5549        attr(wrapper, "aria-hidden", "true");
5550        list_style_header(cell, true, false);
5551        LISTS.with(|m| {
5552            if let Some(st) = m.borrow_mut().get_mut(&host) {
5553                st.pin = (wrapper, cell);
5554            }
5555        });
5556    }
5557    let width = unsafe { day_dom_width(host) }.max(1.0);
5558    s(wrapper, "display", "block");
5559    s(wrapper, "height", &format!("{height}px"));
5560    s(wrapper, "margin-bottom", &format!("{}px", -height));
5561    s(wrapper, "transform", &format!("translateY({push}px)"));
5562    unsafe { day_dom_set_frame(cell, 0.0, 0.0, width, height) };
5563    if rebind {
5564        LISTS.with(|m| {
5565            if let Some(st) = m.borrow_mut().get_mut(&host) {
5566                st.pin_row = Some(h);
5567            }
5568        });
5569        (source.bind_pinned)(h, cell as usize as day_spec::RawHandle);
5570    }
5571}
5572
5573/// A self-sizing list's rows moved: frame every realized row at the top its predecessors' heights
5574/// add up to, and size the content to the new extent. A no-op on a uniform list, whose rows
5575/// never move.
5576fn list_restack(host: u32) {
5577    LISTS.with(|m| {
5578        let m = m.borrow();
5579        let Some(st) = m.get(&host) else {
5580            return;
5581        };
5582        let Some(source) = st.source.as_ref().filter(|_| st.stacked()) else {
5583            return;
5584        };
5585        let n = (source.len)();
5586        let tops = st.tops(n);
5587        let width = unsafe { day_dom_width(host) }.max(1.0);
5588        for (i, &cell) in st.cells.iter().enumerate().take(n) {
5589            if cell != 0 {
5590                unsafe { day_dom_set_frame(cell, 0.0, tops[i], width, tops[i + 1] - tops[i]) };
5591            }
5592        }
5593        s(st.content, "height", &format!("{}px", tops[n]));
5594    });
5595}
5596
5597/// How many `ui_idle` polls in a row a list may find its viewport report owed before it stops
5598/// holding scripts up: a fill that cannot catch up must never wedge one.
5599const LIST_OWED_POLLS: u32 = 30;
5600
5601/// Whether every shown list has settled (`Toolkit::ui_idle`, docs/list.md "Visible rows"): its
5602/// own smooth scroll has arrived, and its last viewport report describes the offset, height and
5603/// rows it has now. A browser delivers `scroll` events with the next frame, so an offset that
5604/// moved this frame (a row jump, a reload that clamped it) is reported only then; until it is,
5605/// the app reads the rows the list showed before. A fill is posted for a list found behind, so
5606/// the next poll finds it reported.
5607fn list_settled() -> bool {
5608    let (settled, behind) = LISTS.with(|m| {
5609        let mut m = m.borrow_mut();
5610        let (mut settled, mut behind) = (true, Vec::new());
5611        for (&host, st) in m.iter_mut() {
5612            let Some(source) = &st.source else { continue };
5613            if source.viewport.is_none() && source.first_visible.is_none() {
5614                continue;
5615            }
5616            let mut view = [0.0_f64; 2];
5617            unsafe { day_dom_list_viewport(host, view.as_mut_ptr()) };
5618            let n = (source.len)();
5619            // A list that is not shown reports nothing, so it owes nothing.
5620            let late = view[1] > 0.0
5621                && n > 0
5622                && (st.fill_pending
5623                    || st.seen.is_none_or(|(offset, height, rows)| {
5624                        (offset - view[0]).abs() > 0.5
5625                            || (height - view[1]).abs() > 0.5
5626                            || rows != n
5627                    }));
5628            let gliding = view[1] > 0.0 && unsafe { day_dom_list_gliding(host) } != 0;
5629            if !(late || gliding) {
5630                st.owed_polls = 0;
5631            } else if st.owed_polls < LIST_OWED_POLLS {
5632                st.owed_polls += 1;
5633                settled = false;
5634                if late {
5635                    behind.push(host);
5636                }
5637            }
5638        }
5639        (settled, behind)
5640    });
5641    for host in behind {
5642        day_dom_list_scrolled(host);
5643    }
5644    settled
5645}
5646
5647/// A list scrolled (the shim's `scroll` listener): build whatever rows just came into view, on
5648/// the next turn and at most once per turn however many events arrive.
5649#[unsafe(no_mangle)]
5650pub extern "C" fn day_dom_list_scrolled(host: u32) {
5651    day_spec::ffi_guard::contain((), || {
5652        let post = LISTS.with(|m| {
5653            let mut m = m.borrow_mut();
5654            let Some(st) = m.get_mut(&host) else {
5655                return false;
5656            };
5657            let first = !st.fill_pending;
5658            st.fill_pending = true;
5659            first
5660        });
5661        if post {
5662            post_local(move || {
5663                LISTS.with(|m| {
5664                    if let Some(st) = m.borrow_mut().get_mut(&host) {
5665                        st.fill_pending = false;
5666                    }
5667                });
5668                list_fill_window(host);
5669            });
5670        }
5671    });
5672}
5673
5674/// The reader scrolled a list themselves (the shim's input watch, docs/list.md "Following the
5675/// end"): a finger, the scroll bar, the wheel or a key moved it, not the app.
5676#[unsafe(no_mangle)]
5677pub extern "C" fn day_dom_list_reader(host: u32) {
5678    day_spec::ffi_guard::contain((), || {
5679        let report = LISTS.with(|m| {
5680            m.borrow()
5681                .get(&host)
5682                .and_then(|st| st.source.as_ref()?.reader_scroll.clone())
5683        });
5684        if let Some(report) = report {
5685            report();
5686        }
5687    });
5688}
5689
5690fn list_paint_selection(entry: &ListEntry) {
5691    for (i, &cell) in entry.cells.iter().enumerate() {
5692        // Unrealized rows have no cell to paint; they pick the treatment up when they are built
5693        // (this runs at the end of every fill, so a row scrolled into a selection lands painted).
5694        if cell == 0 {
5695            continue;
5696        }
5697        let on = entry.selected.contains(&i);
5698        class(cell, "selected", on);
5699        if entry.selectable {
5700            attr(cell, "aria-selected", if on { "true" } else { "false" });
5701        }
5702    }
5703}
5704
5705/// Where the keyboard is in the list — the row an arrow moves from. That is the lead, the end a
5706/// shifted range last moved; failing that the anchor, and failing that the selection's last row
5707/// (a list whose selection the app set without either). With nothing selected there is no
5708/// cursor, and the caller decides which end to enter the list from.
5709fn list_cursor(entry: &ListEntry) -> Option<usize> {
5710    entry
5711        .lead
5712        .or(entry.anchor)
5713        .or_else(|| entry.selected.iter().next_back().copied())
5714}
5715
5716/// Scroll `row` into view if it is not fully there, the way a native list does when the
5717/// keyboard walks off the visible edge. Whichever edge it went past is the one it comes back
5718/// to, so a held arrow key scrolls a line at a time instead of recentering on every step.
5719fn list_reveal_row(host: u32, (top, bottom): (f64, f64)) {
5720    let mut view = [0.0_f64; 2];
5721    unsafe { day_dom_list_viewport(host, view.as_mut_ptr()) };
5722    let (offset, vh) = (view[0], view[1]);
5723    if vh <= 0.0 {
5724        return; // not laid out yet; the fill that follows builds from the top anyway
5725    }
5726    let y = if top < offset {
5727        top
5728    } else if bottom > offset + vh {
5729        bottom - vh
5730    } else {
5731        return;
5732    };
5733    unsafe { day_dom_scroll_to(host, 0.0, y, 0) };
5734}
5735
5736/// An arrow, Home or End the shim's list keyboard route claims for a focused list
5737/// (docs/list.md): `dir` is 0 up, 1 down, 2 home, 3 end, and `mods` is a `KeyEvent` mask. Moves
5738/// the selection one row (or to an end), extends the range instead when a multi-select list is
5739/// shifted, reveals the row and reports the same event a click on it would. `dir == 4`
5740/// activates the selected row. Returns 1 when handled; 0 lets Enter reach the default action.
5741#[unsafe(no_mangle)]
5742pub extern "C" fn day_dom_list_key(host: u32, dir: u32, mods: u32) -> u32 {
5743    day_spec::ffi_guard::contain(0, || {
5744        if dir == 4 {
5745            let active = LISTS.with(|m| {
5746                m.borrow()
5747                    .get(&host)
5748                    .filter(|s| s.activatable && !s.selected.is_empty())
5749                    .and_then(|s| list_cursor(s).map(|row| (s.node, row)))
5750            });
5751            if let Some((node, row)) = active {
5752                emit(node, Event::ListActivated(row));
5753                return 1;
5754            }
5755            return 0;
5756        }
5757        let moved = LISTS.with(|m| {
5758            let mut m = m.borrow_mut();
5759            let st = m.get_mut(&host)?;
5760            let n = st.source.as_ref().map_or(0, |src| (src.len)());
5761            if !st.selectable || n == 0 {
5762                return None;
5763            }
5764            // Entering an unselected list picks the row the arrow points AT: down lands on the
5765            // first row, up on the last, which is what every desktop list does. Section headers
5766            // are not rows the keyboard can stand on, so every move steps over them
5767            // (docs/list.md "Sections").
5768            // Supplementary rows (header, footer, empty state, padding) are skipped the same way.
5769            let is_header = st.source.as_ref().and_then(|src| src.is_header.clone());
5770            let is_supplement = st.source.as_ref().and_then(|src| src.is_supplement.clone());
5771            let item = |i: &usize| {
5772                !is_header.as_ref().is_some_and(|f| f(*i))
5773                    && !is_supplement.as_ref().is_some_and(|f| f(*i))
5774            };
5775            let cursor = list_cursor(st).map(|c| c.min(n - 1));
5776            let row = match (dir, cursor) {
5777                (0, Some(c)) => (0..c).rev().find(item).unwrap_or(c),
5778                (1, Some(c)) => (c + 1..n).find(item).unwrap_or(c),
5779                (0 | 3, None) | (3, _) => (0..n).rev().find(item)?,
5780                (1 | 2, None) | (2, _) => (0..n).find(item)?,
5781                _ => return None,
5782            };
5783            let shift = mods as u8 & day_spec::Modifiers::SHIFT.bits() != 0;
5784            if st.multi && shift {
5785                // Shift extends from the anchor and leaves it where it was, moving only the
5786                // lead — so a run of shifted arrows grows and shrinks one range instead of
5787                // starting a new one from wherever the last one ended.
5788                let a = st.anchor.unwrap_or(row);
5789                st.selected = (a.min(row)..=a.max(row)).filter(item).collect();
5790                st.anchor = Some(a);
5791                st.lead = Some(row);
5792            } else {
5793                st.selected = std::iter::once(row).collect();
5794                st.anchor = Some(row);
5795                st.lead = Some(row);
5796            }
5797            list_paint_selection(st);
5798            let ev = if st.multi {
5799                Event::SelectionSet(st.selected.iter().map(|r| *r as i64).collect())
5800            } else {
5801                Event::SelectionChanged(row as i64)
5802            };
5803            // Revealed below the pinned header, which would otherwise cover a row the keyboard
5804            // walked up onto.
5805            let (top, bottom) = st.row_span(row);
5806            Some((st.node, ev, (top - st.pinned_above(row), bottom)))
5807        });
5808        let Some((node, ev, span)) = moved else {
5809            return 0;
5810        };
5811        list_reveal_row(host, span);
5812        emit(node, ev);
5813        1
5814    })
5815}
5816
5817fn list_patch(el: u32, p: &ListPatch) {
5818    match p {
5819        ListPatch::Reload => post_local(move || list_populate(el)),
5820        // Cell index is row index, so every cell rebinds as on a reload; what must follow the
5821        // deltas is the measured heights of a stacked list, which belong to rows, not slots.
5822        ListPatch::Splice(deltas) => {
5823            LISTS.with(|m| {
5824                if let Some(st) = m.borrow_mut().get_mut(&el)
5825                    && st.stacked()
5826                {
5827                    splice_heights(&mut st.heights, deltas);
5828                }
5829            });
5830            post_local(move || list_populate(el));
5831        }
5832        // No editing mode (Cap::ListEditing is Unsupported).
5833        ListPatch::Editing(_) => {}
5834        // A self-sizing row re-laid at a new height. This arrives inside day-core's layout
5835        // pass, so the row moves on the next turn: record the height Day gave it (cell index
5836        // is row index here), restack the rows after it, and build any the move revealed.
5837        &ListPatch::RowSizeInvalidated { cell, height } => post_local(move || {
5838            let moved = LISTS.with(|m| {
5839                let mut m = m.borrow_mut();
5840                let Some(st) = m.get_mut(&el).filter(|st| st.stacked()) else {
5841                    return false;
5842                };
5843                let Some(row) = st.cells.iter().position(|c| *c as usize == cell) else {
5844                    return false;
5845                };
5846                // A uniform sectioned list measures only its headers; its items keep the pitch.
5847                if !st.automatic && !st.is_header(row) {
5848                    return false;
5849                }
5850                if st.heights.len() <= row {
5851                    st.heights.resize(row + 1, 0.0);
5852                }
5853                st.heights[row] = height;
5854                true
5855            });
5856            if moved {
5857                list_restack(el);
5858                list_fill_window(el);
5859            }
5860        }),
5861        ListPatch::ScrollToEnd => unsafe { day_dom_scroll_edge(el, 1, 1) },
5862        ListPatch::ScrollToRow(row) => {
5863            let y = LISTS.with(|m| {
5864                m.borrow().get(&el).map_or(0.0, |st| {
5865                    (st.row_span(*row).0 - st.pinned_above(*row)).max(0.0)
5866                })
5867            });
5868            // Also held for the next fill: a jump asked for before the first one (a list the
5869            // page scrolls as it builds) meets content with no height yet, so the browser has
5870            // nothing to scroll and no scroll event comes to build the rows.
5871            LISTS.with(|m| {
5872                if let Some(st) = m.borrow_mut().get_mut(&el) {
5873                    st.pending_scroll = Some(y);
5874                }
5875            });
5876            unsafe { day_dom_scroll_to(el, 0.0, y, 1) };
5877        }
5878        ListPatch::Selected(rows) => {
5879            LISTS.with(|m| {
5880                if let Some(st) = m.borrow_mut().get_mut(&el) {
5881                    let incoming: BTreeSet<usize> = rows.iter().copied().collect();
5882                    // An app-driven selection lands the cursor on its last row. The ECHO of a
5883                    // selection this list just made is NOT app-driven — a `selected_rows`
5884                    // binding sends the same rows straight back — and taking the cursor from it
5885                    // would drag the anchor onto the end of the range the user is extending, so
5886                    // the next shifted arrow would restart the range instead of growing it.
5887                    if incoming != st.selected {
5888                        st.selected = incoming;
5889                        st.anchor = rows.last().copied();
5890                        st.lead = st.anchor;
5891                        list_paint_selection(st);
5892                    }
5893                }
5894            });
5895        }
5896    }
5897}
5898
5899/// Apply sequential row deltas to a per-row table (docs/list.md "Splice"): each index is valid
5900/// against the table the previous deltas left; an inserted row is unmeasured (0).
5901fn splice_heights(heights: &mut Vec<f64>, deltas: &[day_spec::props::RowDelta]) {
5902    use day_spec::props::RowDelta;
5903    for d in deltas {
5904        match *d {
5905            RowDelta::Insert(i) => heights.insert(i.min(heights.len()), 0.0),
5906            RowDelta::Remove(i) => {
5907                if i < heights.len() {
5908                    heights.remove(i);
5909                }
5910            }
5911            RowDelta::Move(from, to) => {
5912                if from < heights.len() {
5913                    let h = heights.remove(from);
5914                    heights.insert(to.min(heights.len()), h);
5915                }
5916            }
5917        }
5918    }
5919}
5920
5921/// Where a row scroll leaves the viewport's top (docs/list.md "Scrolling to a row"), clamped to
5922/// the scroll range; `None` for `Nearest` on a row already fully in view. `span` is the row's
5923/// top and bottom in the content, `pin` what a pinned section header covers above it.
5924fn row_scroll_target(
5925    span: (f64, f64),
5926    pin: f64,
5927    align: day_spec::RowAlign,
5928    offset: f64,
5929    view: f64,
5930    extent: f64,
5931) -> Option<f64> {
5932    use day_spec::RowAlign;
5933    let (top, bottom) = span;
5934    let y = match align {
5935        RowAlign::Start => top - pin,
5936        RowAlign::Center => f64::midpoint(top, bottom) - view / 2.0,
5937        RowAlign::End => bottom - view,
5938        RowAlign::Nearest => {
5939            if top - pin < offset {
5940                top - pin
5941            } else if bottom > offset + view {
5942                bottom - view
5943            } else {
5944                return None;
5945            }
5946        }
5947    };
5948    Some(y.clamp(0.0, (extent - view).max(0.0)))
5949}
5950
5951/// A press on a list cell (docs/list.md): same semantics as the Qt emulated list.
5952fn list_cell_click(cell: u32, mods: u32) {
5953    let Some((host, row)) = CELL_ROWS.with(|m| m.borrow().get(&cell).copied()) else {
5954        return;
5955    };
5956    let emit_ev = LISTS.with(|m| {
5957        let mut m = m.borrow_mut();
5958        // A section header or a supplementary row is not selectable (docs/list.md).
5959        let st = m.get_mut(&host).filter(|st| st.is_item(row))?;
5960        let (ctrl, shift) = (mods & 1 != 0, mods & 2 != 0);
5961        if st.multi && ctrl {
5962            if !st.selected.remove(&row) {
5963                st.selected.insert(row);
5964            }
5965            st.anchor = Some(row);
5966            st.lead = Some(row);
5967        } else if st.multi && shift {
5968            // Shift-click extends from the anchor the same way a shifted arrow does: the pivot
5969            // stays, the lead comes to the clicked row.
5970            let a = st.anchor.unwrap_or(row);
5971            st.selected = (a.min(row)..=a.max(row))
5972                .filter(|i| st.is_item(*i))
5973                .collect();
5974            st.anchor = Some(a);
5975            st.lead = Some(row);
5976        } else {
5977            st.selected = std::iter::once(row).collect();
5978            st.anchor = Some(row);
5979            st.lead = Some(row);
5980        }
5981        list_paint_selection(st);
5982        Some((
5983            st.node,
5984            if st.multi {
5985                Event::SelectionSet(st.selected.iter().map(|r| *r as i64).collect())
5986            } else {
5987                Event::SelectionChanged(row as i64)
5988            },
5989        ))
5990    });
5991    if let Some((node, ev)) = emit_ev {
5992        emit(node, ev);
5993    }
5994}
5995
5996// ---------------------------------------------------------------------------
5997// Canvas display-list encoding (§11): a flat f64 stream + a UTF-8 string blob; shim.js
5998// interprets it onto a 2-D context. Colors pack as u32 rgba; gradients resolve to absolute
5999// geometry Rust-side so the interpreter stays dumb.
6000// ---------------------------------------------------------------------------
6001
6002fn pack_color(c: day_spec::Color) -> f64 {
6003    let r = (c.r.clamp(0.0, 1.0) * 255.0).round() as u32;
6004    let g = (c.g.clamp(0.0, 1.0) * 255.0).round() as u32;
6005    let b = (c.b.clamp(0.0, 1.0) * 255.0).round() as u32;
6006    let a = (c.a.clamp(0.0, 1.0) * 255.0).round() as u32;
6007    f64::from((r << 24) | (g << 16) | (b << 8) | a)
6008}
6009
6010fn push_shape(buf: &mut Vec<f64>, shape: &Shape) {
6011    match shape {
6012        Shape::Rect(r) => buf.extend([0.0, r.origin.x, r.origin.y, r.size.width, r.size.height]),
6013        Shape::RoundedRect(r, rad) => buf.extend([
6014            1.0,
6015            r.origin.x,
6016            r.origin.y,
6017            r.size.width,
6018            r.size.height,
6019            *rad,
6020        ]),
6021        Shape::Ellipse(r) => buf.extend([2.0, r.origin.x, r.origin.y, r.size.width, r.size.height]),
6022        Shape::Arc { rect, start, sweep } => buf.extend([
6023            3.0,
6024            rect.origin.x,
6025            rect.origin.y,
6026            rect.size.width,
6027            rect.size.height,
6028            start.degrees(),
6029            sweep.degrees(),
6030        ]),
6031        Shape::Line(a, b) => buf.extend([4.0, a.x, a.y, b.x, b.y]),
6032        // The two variable-length kinds lead with their `geometry_key` and the length of what
6033        // follows: a shim that has decoded this key before keeps the `Path2D` it built and JUMPS
6034        // the payload. The length is what makes that possible — the geometry rides this buffer
6035        // rather than a side channel, so a hit has to know how far to skip.
6036        Shape::Polygon(pts) => {
6037            buf.extend([5.0, day_spec::geometry_key(shape), 0.0]);
6038            let len_at = buf.len() - 1;
6039            buf.push(pts.len() as f64);
6040            for p in pts {
6041                buf.extend([p.x, p.y]);
6042            }
6043            buf[len_at] = (buf.len() - len_at - 1) as f64;
6044        }
6045        // Path: [6, key, len, rule, segCount, then per segment: kind + its points].
6046        Shape::Path(path) => {
6047            buf.extend([6.0, day_spec::geometry_key(shape), 0.0]);
6048            let len_at = buf.len() - 1;
6049            buf.extend([
6050                match path.rule {
6051                    day_spec::FillRule::EvenOdd => 1.0,
6052                    day_spec::FillRule::NonZero => 0.0,
6053                },
6054                path.segs.len() as f64,
6055            ]);
6056            for seg in &path.segs {
6057                match seg {
6058                    day_spec::PathSeg::Move(a) => buf.extend([0.0, a.x, a.y]),
6059                    day_spec::PathSeg::Line(a) => buf.extend([1.0, a.x, a.y]),
6060                    day_spec::PathSeg::Quad(c, a) => buf.extend([2.0, c.x, c.y, a.x, a.y]),
6061                    day_spec::PathSeg::Cubic(c1, c2, a) => {
6062                        buf.extend([3.0, c1.x, c1.y, c2.x, c2.y, a.x, a.y]);
6063                    }
6064                    day_spec::PathSeg::Close => buf.push(4.0),
6065                }
6066            }
6067            buf[len_at] = (buf.len() - len_at - 1) as f64;
6068        }
6069    }
6070}
6071
6072fn push_paint(buf: &mut Vec<f64>, paint: &Paint, bounds: Rect) {
6073    match paint {
6074        Paint::Solid(c) => buf.extend([0.0, pack_color((*c).resolved())]),
6075        Paint::Linear(g) => {
6076            let (o, sz) = (bounds.origin, bounds.size);
6077            buf.extend([
6078                1.0,
6079                o.x + g.start.x * sz.width,
6080                o.y + g.start.y * sz.height,
6081                o.x + g.end.x * sz.width,
6082                o.y + g.end.y * sz.height,
6083                g.stops.len() as f64,
6084            ]);
6085            for (off, c) in &g.stops {
6086                buf.extend([*off, pack_color((*c).resolved())]);
6087            }
6088        }
6089        Paint::Radial(g) => {
6090            let (o, sz) = (bounds.origin, bounds.size);
6091            buf.extend([
6092                2.0,
6093                o.x + g.center.x * sz.width,
6094                o.y + g.center.y * sz.height,
6095                g.radius * sz.width,
6096                g.radius * sz.height,
6097                g.stops.len() as f64,
6098            ]);
6099            for (off, c) in &g.stops {
6100                buf.extend([*off, pack_color((*c).resolved())]);
6101            }
6102        }
6103        // [3, cx, cy, startDeg, stopCount, stops…] (docs/canvas.md "Conic gradients"): the
6104        // center in canvas points, the start angle as recorded. The shim hands it to
6105        // `createConicGradient`, whose angle runs clockwise from +x as the spec's does.
6106        Paint::Conic(g) => {
6107            let (o, sz) = (bounds.origin, bounds.size);
6108            buf.extend([
6109                3.0,
6110                o.x + g.center.x * sz.width,
6111                o.y + g.center.y * sz.height,
6112                g.start.degrees(),
6113                g.stops.len() as f64,
6114            ]);
6115            for (off, c) in &g.stops {
6116                buf.extend([*off, pack_color((*c).resolved())]);
6117            }
6118        }
6119    }
6120}
6121
6122/// The stroke style bytes shared by `Stroke` and a stroked `Stamp`: width, cap, join, miter,
6123/// dash phase, dash count, then the dashes.
6124fn push_stroke_style(buf: &mut Vec<f64>, style: &day_spec::StrokeStyle) {
6125    buf.extend([
6126        style.width,
6127        match style.cap {
6128            day_spec::LineCap::Butt => 0.0,
6129            day_spec::LineCap::Round => 1.0,
6130            day_spec::LineCap::Square => 2.0,
6131        },
6132        match style.join {
6133            day_spec::LineJoin::Miter => 0.0,
6134            day_spec::LineJoin::Round => 1.0,
6135            day_spec::LineJoin::Bevel => 2.0,
6136        },
6137        style.miter_limit,
6138        style.dash_phase,
6139        style.dash.len() as f64,
6140    ]);
6141    buf.extend(style.dash.iter().copied());
6142}
6143
6144fn encode_ops(ops: &[DrawOp]) -> (Vec<f64>, Vec<u8>) {
6145    let mut buf = Vec::with_capacity(ops.len() * 8);
6146    let mut strs: Vec<u8> = Vec::new();
6147    for op in ops {
6148        match op {
6149            DrawOp::Fill(shape, paint) => {
6150                buf.push(0.0);
6151                push_paint(&mut buf, paint, shape.bounds());
6152                push_shape(&mut buf, shape);
6153            }
6154            DrawOp::Stamp(st) => {
6155                // [7, strokeFlag, (stroke style…)?, count, x0,y0 …, paint, template shape].
6156                // This encoder is variable-length already, so the coordinates ride it directly —
6157                // no separate record kind and no padding (docs/canvas.md "Stamping").
6158                buf.push(7.0);
6159                match &st.stroke {
6160                    None => buf.push(0.0),
6161                    Some(style) => {
6162                        buf.push(1.0);
6163                        push_stroke_style(&mut buf, style);
6164                    }
6165                }
6166                buf.push(st.at.len() as f64);
6167                for p in &st.at {
6168                    buf.push(p.x);
6169                    buf.push(p.y);
6170                }
6171                // The paint resolves against the TEMPLATE's bounds, which is the batch's own
6172                // geometry repeated — a gradient therefore shades each copy identically rather
6173                // than across the group, matching what a per-mark fill would have done.
6174                push_paint(&mut buf, &st.paint, st.shape.bounds());
6175                push_shape(&mut buf, &st.shape);
6176            }
6177            DrawOp::Stroke(shape, paint, style) => {
6178                // [1, width, cap, join, miter, dashPhase, dashCount, dashes…] then paint, then
6179                // shape. Style is inline rather than a separate record: this encoder is already
6180                // variable-length, so there is nothing to gain from a modifier record here.
6181                buf.push(1.0);
6182                push_stroke_style(&mut buf, style);
6183                push_paint(&mut buf, paint, shape.bounds());
6184                push_shape(&mut buf, shape);
6185            }
6186            DrawOp::Clip(shape) => {
6187                buf.push(6.0);
6188                push_shape(&mut buf, shape);
6189            }
6190            DrawOp::Text {
6191                text,
6192                at,
6193                size,
6194                color,
6195                anchor,
6196                font,
6197            } => {
6198                let off = strs.len() as f64;
6199                strs.extend_from_slice(text.as_bytes());
6200                let fam_off = strs.len() as f64;
6201                strs.extend_from_slice(font.family_str().as_bytes());
6202                buf.extend([
6203                    2.0,
6204                    pack_color(*color),
6205                    *size,
6206                    anchor.pack(),
6207                    at.x,
6208                    at.y,
6209                    off,
6210                    text.len() as f64,
6211                    // The font (docs/fonts.md): CSS weight (0 = default), italic, family bytes.
6212                    f64::from(font.css_weight()),
6213                    f64::from(u8::from(font.italic)),
6214                    fam_off,
6215                    font.family_str().len() as f64,
6216                ]);
6217            }
6218            DrawOp::Save => buf.push(3.0),
6219            DrawOp::Restore => buf.push(4.0),
6220            // [8, id, x, y, w, h, opacity] (docs/images.md). The id is a number, so it rides
6221            // this buffer like any coordinate. Note this encoder's numbering is its OWN — it is
6222            // not day-spec's frozen wire table, and the two have never agreed.
6223            DrawOp::Image {
6224                image,
6225                rect,
6226                opacity,
6227                source: None,
6228            } => buf.extend([
6229                8.0,
6230                image.0 as f64,
6231                rect.origin.x,
6232                rect.origin.y,
6233                rect.size.width,
6234                rect.size.height,
6235                *opacity,
6236            ]),
6237            // [9, id, x, y, w, h, opacity, sx, sy, sw, sh]: the same with a source region in
6238            // bitmap pixels, the 9-argument `drawImage`. Its own code rather than four more
6239            // slots on 8, so a whole-image draw encodes exactly as it always did.
6240            DrawOp::Image {
6241                image,
6242                rect,
6243                opacity,
6244                source: Some(src),
6245            } => buf.extend([
6246                9.0,
6247                image.0 as f64,
6248                rect.origin.x,
6249                rect.origin.y,
6250                rect.size.width,
6251                rect.size.height,
6252                *opacity,
6253                src.origin.x,
6254                src.origin.y,
6255                src.size.width,
6256                src.size.height,
6257            ]),
6258            DrawOp::Concat(m) => buf.extend([5.0, m.a, m.b, m.c, m.d, m.tx, m.ty]),
6259            // [10, dx, dy, blur, color] (docs/canvas.md "Shadows"): points, which the shim
6260            // turns into backing-store pixels. A clear color is "no shadow", so `None` needs
6261            // no code of its own.
6262            DrawOp::Shadow(shadow) => {
6263                let sh = shadow.unwrap_or(day_spec::Shadow::new(day_spec::Color::CLEAR, 0.0));
6264                buf.extend([10.0, sh.dx, sh.dy, sh.blur, pack_color(sh.color.resolved())]);
6265            }
6266            // [11, mode] (docs/canvas.md "Blend modes"), numbered as `BlendMode::wire`.
6267            DrawOp::Blend(mode) => buf.extend([11.0, f64::from(mode.wire())]),
6268        }
6269    }
6270    (buf, strs)
6271}
6272
6273// ---------------------------------------------------------------------------
6274// Presentation (docs/dialogs.md): <dialog>-backed alert/confirm/sheet/prompt.
6275// ---------------------------------------------------------------------------
6276
6277fn present_json(spec: &PresentSpec) -> Option<String> {
6278    use std::fmt::Write as _;
6279    let mut j = String::from("{");
6280    match spec {
6281        PresentSpec::Dialog {
6282            title,
6283            message,
6284            buttons,
6285            sheet,
6286        } => {
6287            j.push_str("\"kind\":\"dialog\",\"title\":");
6288            json_str(&mut j, title);
6289            if let Some(m) = message {
6290                j.push_str(",\"message\":");
6291                json_str(&mut j, m);
6292            }
6293            let _ = write!(j, ",\"sheet\":{sheet},\"buttons\":[");
6294            for (i, b) in buttons.iter().enumerate() {
6295                if i > 0 {
6296                    j.push(',');
6297                }
6298                push_button(&mut j, b);
6299            }
6300            j.push(']');
6301        }
6302        PresentSpec::Prompt {
6303            title,
6304            message,
6305            placeholder,
6306            initial,
6307            ok,
6308            cancel,
6309        } => {
6310            j.push_str("\"kind\":\"prompt\",\"title\":");
6311            json_str(&mut j, title);
6312            if let Some(m) = message {
6313                j.push_str(",\"message\":");
6314                json_str(&mut j, m);
6315            }
6316            j.push_str(",\"placeholder\":");
6317            json_str(&mut j, placeholder);
6318            j.push_str(",\"initial\":");
6319            json_str(&mut j, initial);
6320            j.push_str(",\"ok\":");
6321            json_str(&mut j, ok);
6322            j.push_str(",\"cancel\":");
6323            json_str(&mut j, cancel);
6324        }
6325        // The open picker: the shim clicks a hidden `<input type=file>` (with `multiple` set
6326        // for a several-files pick) and answers with each chosen file's name and bytes through
6327        // `day_dom_present_file_stage` / `day_dom_present_files`.
6328        PresentSpec::OpenFile {
6329            title,
6330            filters,
6331            multiple,
6332        } => {
6333            j.push_str("\"kind\":\"open\",\"title\":");
6334            json_str(&mut j, title);
6335            let accept: Vec<String> = filters
6336                .iter()
6337                .flat_map(|f| f.extensions.iter())
6338                .map(|e| format!(".{e}"))
6339                .collect();
6340            j.push_str(",\"accept\":");
6341            json_str(&mut j, &accept.join(","));
6342            j.push_str(if *multiple {
6343                ",\"multiple\":true"
6344            } else {
6345                ",\"multiple\":false"
6346            });
6347        }
6348        // A browser has no folder chooser that hands back a path (`Cap::FolderDialog` is
6349        // Unsupported): the request resolves as Dismissed.
6350        #[expect(
6351            clippy::match_same_arms,
6352            reason = "the two flows resolve here for different, separately documented reasons"
6353        )]
6354        PresentSpec::OpenFolder { .. } => return None,
6355        // Save rides its own FFI arm (bytes attached); reaching here means a non-web build.
6356        PresentSpec::SaveFile { .. } => return None,
6357    }
6358    j.push('}');
6359    Some(j)
6360}
6361
6362fn push_button(j: &mut String, b: &PresentButton) {
6363    use std::fmt::Write as _;
6364    j.push_str("{\"label\":");
6365    json_str(j, &b.label);
6366    let role = match b.role {
6367        day_spec::present::ButtonRole::Default => "default",
6368        day_spec::present::ButtonRole::Cancel => "cancel",
6369        day_spec::present::ButtonRole::Destructive => "destructive",
6370    };
6371    let _ = write!(j, ",\"role\":\"{role}\"}}");
6372}
6373
6374// ---------------------------------------------------------------------------
6375// Exports the shim calls back through.
6376// ---------------------------------------------------------------------------
6377
6378/// Allocate `len` bytes inside wasm memory for the shim to write UTF-8 into (freed by the
6379/// export that consumes the pointer).
6380#[unsafe(no_mangle)]
6381pub extern "C" fn day_dom_alloc(len: usize) -> *mut u8 {
6382    let mut v = Vec::<u8>::with_capacity(len);
6383    let ptr = v.as_mut_ptr();
6384    std::mem::forget(v);
6385    ptr
6386}
6387
6388/// Consume the final module's declaration sections before the application starts.
6389#[allow(clippy::not_unsafe_ptr_arg_deref)] // allocated by day_dom_alloc in the trusted shim
6390#[unsafe(no_mangle)]
6391pub extern "C" fn day_dom_install_ids(ptr: *mut u8, len: usize) {
6392    // SAFETY: the shim allocated and initialized exactly len bytes with day_dom_alloc.
6393    let bytes = unsafe { take_bytes(ptr, len) };
6394    if let Err(error) = day_core::element_id::install_web_registry(&bytes) {
6395        log::error!("element registry: {error}");
6396    }
6397}
6398
6399/// Install expectations captured before linking and run registration constructors once.
6400#[allow(clippy::not_unsafe_ptr_arg_deref)] // allocated by the trusted shim
6401#[unsafe(no_mangle)]
6402pub extern "C" fn day_dom_install_tests(ptr: *mut u8, len: usize) {
6403    // SAFETY: the shim initialized exactly len bytes from day_dom_alloc.
6404    let bytes = unsafe { take_bytes(ptr, len) };
6405    if let Err(error) = day_core::conformance::install_web_registry(&bytes) {
6406        // Keep the host alive to report a nonretryable dayscript infrastructure error.
6407        log::error!("{error}");
6408    }
6409}
6410
6411/// Take ownership of a `day_dom_alloc(len)` allocation the shim filled.
6412///
6413/// # Safety
6414///
6415/// `ptr` must come from `day_dom_alloc(len)`, hold `len` initialized bytes, and not be used
6416/// again by the caller.
6417#[expect(
6418    clippy::same_length_and_capacity,
6419    reason = "`day_dom_alloc(len)` made the allocation with capacity `len`"
6420)]
6421pub(crate) unsafe fn take_bytes(ptr: *mut u8, len: usize) -> Vec<u8> {
6422    // SAFETY: the caller's contract, stated above.
6423    unsafe { Vec::from_raw_parts(ptr, len, len) }
6424}
6425
6426fn take_string(ptr: *mut u8, len: usize) -> String {
6427    // SAFETY: the shim wrote exactly `len` bytes into a `day_dom_alloc(len)` allocation.
6428    let v = unsafe { take_bytes(ptr, len) };
6429    String::from_utf8_lossy(&v).into_owned()
6430}
6431
6432/// The reorder guard's verdict for a hovered drop, called synchronously by the shim's drag
6433/// handler (docs/list.md): the ACCEPTED target index, or -1 to deny (also when out of bounds or
6434/// the list has no reorder seam). The Rc is cloned out first, so the app's guard runs with no
6435/// `LISTS` borrow held.
6436#[unsafe(no_mangle)]
6437pub extern "C" fn day_dom_list_can_move(host: u32, from: u32, to: u32) -> i32 {
6438    // Every export below that runs closures or dispatches events is contained
6439    // (day_spec::ffi_guard): a panic unwinding a wasm `extern "C"` frame traps the
6440    // instance, so a caught panic reports and returns the arm's safe default instead.
6441    day_spec::ffi_guard::contain(-1, || {
6442        let r = LISTS.with(|m| {
6443            m.borrow()
6444                .get(&host)
6445                .and_then(|st| st.source.as_ref().map(|s| ((s.len)(), s.reorder.clone())))
6446        });
6447        let Some((len, Some(r))) = r else { return -1 };
6448        let (from, to) = (from as usize, to as usize);
6449        if from >= len || to >= len {
6450            return -1;
6451        }
6452        ((r.can_move)(from, to) as i32).min(len.saturating_sub(1) as i32)
6453    })
6454}
6455
6456/// The row whose span holds content offset `y`, clamped to the rows; -1 for an empty or
6457/// unknown list. The shim's pointer-drag reorder reads its rows through this, since rows of a
6458/// self-sizing or sectioned list stand at their own heights rather than a pitch.
6459#[unsafe(no_mangle)]
6460pub extern "C" fn day_dom_list_row_at(host: u32, y: f64) -> i32 {
6461    day_spec::ffi_guard::contain(-1, || {
6462        LISTS.with(|m| {
6463            let m = m.borrow();
6464            let Some(st) = m.get(&host) else { return -1 };
6465            let n = st.source.as_ref().map_or(0, |src| (src.len)());
6466            if n == 0 {
6467                return -1;
6468            }
6469            let row = if st.stacked() {
6470                st.tops(n)
6471                    .partition_point(|top| *top <= y)
6472                    .saturating_sub(1)
6473            } else {
6474                (y.max(0.0) / st.row_height.max(1.0)) as usize
6475            };
6476            row.min(n - 1) as i32
6477        })
6478    })
6479}
6480
6481/// Commit a drop the guard accepts: rotate Day's snapshot (deferring the app callback), then
6482/// reposition + rebind the pooled cells to the new order. Returns 1 on commit, 0 on deny.
6483#[unsafe(no_mangle)]
6484pub extern "C" fn day_dom_list_move(host: u32, from: u32, to: u32) -> u32 {
6485    day_spec::ffi_guard::contain(0, || {
6486        let accepted = day_dom_list_can_move(host, from, to);
6487        if accepted < 0 {
6488            return 0;
6489        }
6490        let r = LISTS.with(|m| {
6491            m.borrow()
6492                .get(&host)
6493                .and_then(|st| st.source.as_ref().and_then(|s| s.reorder.clone()))
6494        });
6495        let Some(r) = r else { return 0 };
6496        if accepted as u32 != from {
6497            (r.move_row)(from as usize, accepted as usize);
6498        }
6499        // Re-bind every pooled cell in the rotated order (the emulated "move animation").
6500        post_local(move || list_populate(host));
6501        1
6502    })
6503}
6504
6505#[unsafe(no_mangle)]
6506pub extern "C" fn day_dom_event(el: u32, kind: u32, a: f64, b: f64, c: f64, d: f64) {
6507    day_spec::ffi_guard::contain((), || day_dom_event_inner(el, kind, a, b, c, d));
6508}
6509
6510/// A menu button's press (docs/menus.md "Menu buttons"): ask the provider now, so the entries
6511/// are current, and hand them to the toolbar pull-down's popover under the button. Reduced to
6512/// what the web can answer, as the app menu is. Called from the shim's click, outside any
6513/// day-core borrow.
6514fn open_button_menu(el: u32, f: &day_spec::ContextMenuFn) {
6515    // The provider may remove this button; then no menu opens (docs/menus.md).
6516    let Some(items) =
6517        day_spec::resolve_button_menu(f, || BUTTON_MENUS.with(|t| t.get(el as usize)).is_some())
6518    else {
6519        return;
6520    };
6521    let items = web_menu_items(&items);
6522    if items.is_empty() {
6523        return;
6524    }
6525    let mut json = String::new();
6526    menu_items_json(&mut json, &items);
6527    // SAFETY: `json` outlives the call; the shim copies the string out before returning.
6528    unsafe { day_dom_button_menu(el, json.as_ptr(), json.len()) };
6529}
6530
6531fn day_dom_event_inner(el: u32, kind: u32, a: f64, b: f64, c: f64, d: f64) {
6532    if kind == ev::CLICK && CELL_ROWS.with(|m| m.borrow().contains_key(&el)) {
6533        #[expect(
6534            clippy::float_cmp,
6535            reason = "the shim sends these flags as exact small integers"
6536        )]
6537        let (double, activates) = (b == 2.0, c == 1.0);
6538        if !double {
6539            list_cell_click(el, a as u32);
6540        }
6541        if double || activates {
6542            // A section header activates nothing (docs/list.md "Sections").
6543            let row = CELL_ROWS
6544                .with(|m| m.borrow().get(&el).copied())
6545                .filter(|(host, row)| {
6546                    LISTS.with(|m| m.borrow().get(host).is_some_and(|st| st.is_item(*row)))
6547                });
6548            if let Some((host, row)) = row
6549                && let Some(node) = node_of(host)
6550            {
6551                emit(node, Event::ListActivated(row));
6552            }
6553        }
6554        return;
6555    }
6556    if kind == ev::CLICK
6557        && let Some(f) = BUTTON_MENUS.with(|t| t.get(el as usize))
6558    {
6559        open_button_menu(el, &f);
6560        return;
6561    }
6562    let Some(node) = node_of(el) else { return };
6563    let event = match kind {
6564        ev::CLICK => Event::Pressed,
6565        ev::SUBMIT => Event::Submitted,
6566        ev::TOGGLE => Event::ToggleChanged(a != 0.0),
6567        ev::VALUE => Event::ValueChanged(a),
6568        ev::VALUE_COMMITTED => Event::ValueCommitted(a),
6569        ev::SELECT => Event::SelectionChanged(a as i64),
6570        ev::FOCUS => Event::FocusChanged(a != 0.0),
6571        ev::TAP => Event::Tap(Point::new(a, b)),
6572        ev::DRAG_BEGAN | ev::DRAG_MOVED | ev::DRAG_ENDED => Event::Drag {
6573            phase: match kind {
6574                ev::DRAG_BEGAN => day_spec::DragPhase::Began,
6575                ev::DRAG_MOVED => day_spec::DragPhase::Changed,
6576                _ => day_spec::DragPhase::Ended,
6577            },
6578            location: Point::new(a, b),
6579            translation: Point::new(c, d),
6580        },
6581        ev::HOVER_ENTER | ev::HOVER_MOVED | ev::HOVER_LEFT => Event::Hover {
6582            phase: match kind {
6583                ev::HOVER_ENTER => day_spec::DragPhase::Began,
6584                ev::HOVER_LEFT => day_spec::DragPhase::Ended,
6585                _ => day_spec::DragPhase::Changed,
6586            },
6587            location: Point::new(a, b),
6588        },
6589        ev::PAN => Event::Pan {
6590            phase: day_spec::DragPhase::Changed,
6591            location: Point::new(a, b),
6592            delta: Point::new(c, d),
6593        },
6594        ev::PINCH_BEGAN | ev::PINCH_MOVED | ev::PINCH_ENDED => Event::Pinch {
6595            phase: match kind {
6596                ev::PINCH_BEGAN => day_spec::DragPhase::Began,
6597                ev::PINCH_ENDED => day_spec::DragPhase::Ended,
6598                _ => day_spec::DragPhase::Changed,
6599            },
6600            scale: c,
6601            location: Point::new(a, b),
6602        },
6603        ev::ROTATE_BEGAN | ev::ROTATE_MOVED | ev::ROTATE_ENDED => Event::Rotate {
6604            phase: match kind {
6605                ev::ROTATE_BEGAN => day_spec::DragPhase::Began,
6606                ev::ROTATE_ENDED => day_spec::DragPhase::Ended,
6607                _ => day_spec::DragPhase::Changed,
6608            },
6609            rotation: c,
6610            location: Point::new(a, b),
6611        },
6612        ev::LONG_PRESS => Event::LongPress(Point::new(a, b)),
6613        ev::DOUBLE_TAP => Event::DoubleTap(Point::new(a, b)),
6614        ev::PRESS => Event::Press {
6615            pressed: c != 0.0,
6616            location: Point::new(a, b),
6617        },
6618        ev::SCROLL => Event::ScrollChanged(Point::new(a, b)),
6619        ev::SCROLL_PHASE => Event::ScrollPhase(match a as u32 {
6620            1 => day_spec::ScrollPhase::Dragging,
6621            2 => day_spec::ScrollPhase::Coasting,
6622            _ => day_spec::ScrollPhase::Idle,
6623        }),
6624        ev::CONTEXT => Event::ContextMenu {
6625            local: Point::new(a, b),
6626            window: Point::new(c, d),
6627        },
6628        ev::RESIZED => Event::FrameChanged(Size::new(a, b)),
6629        ev::NAV_BACK => Event::NavBack {
6630            already_popped: false,
6631        },
6632        _ => return,
6633    };
6634    emit(node, event);
6635}
6636
6637/// A piece-defined Custom event from the shim (docs/extending.md §8.2's open channel): `num` is
6638/// the piece's own discriminator (the inline web view's link reports use -1, per
6639/// day-piece-webview's docs/webview.md) and `text` the payload. The mirror of the Android
6640/// bridge's kind-12 and ArkUI's `pieceEvent`.
6641#[unsafe(no_mangle)]
6642pub extern "C" fn day_dom_piece_event(el: u32, num: f64, ptr: *mut u8, len: usize) {
6643    let t = take_string(ptr, len);
6644    day_spec::ffi_guard::contain((), move || {
6645        if let Some(node) = node_of(el) {
6646            emit(
6647                node,
6648                Event::Custom {
6649                    tag: "",
6650                    num,
6651                    text: t,
6652                },
6653            );
6654        }
6655    });
6656}
6657
6658#[unsafe(no_mangle)]
6659pub extern "C" fn day_dom_event_text(el: u32, kind: u32, ptr: *mut u8, len: usize) {
6660    let t = take_string(ptr, len);
6661    day_spec::ffi_guard::contain((), move || {
6662        if let Some(node) = node_of(el) {
6663            // The kinds that carry a string. `16` is a styled run's link (docs/text-runs.md):
6664            // the anchor's own navigation is cancelled in the shim, so the app decides.
6665            emit(
6666                node,
6667                match kind {
6668                    16 => Event::LinkActivated(t),
6669                    // The piece channel (§8.2), as the Android and ArkTS bridges spell it: the
6670                    // payload IS the event, since no tag survives the boundary.
6671                    17 => Event::Custom {
6672                        tag: "",
6673                        num: 0.0,
6674                        text: t,
6675                    },
6676                    // Raw contacts (docs/gestures.md "Touches"), the shim's touches wire.
6677                    18 => Event::Touches(parse_touches(&t)),
6678                    _ => Event::TextChanged(t),
6679                },
6680            );
6681        }
6682    });
6683}
6684
6685/// The browser answering a decode (docs/images.md): `w`/`h` are the decoded PIXEL size, or 0 when
6686/// the bytes were not an image this engine reads.
6687#[unsafe(no_mangle)]
6688pub extern "C" fn day_dom_image_decoded(req: u32, id: f64, w: f64, h: f64) {
6689    let id = day_spec::BitmapId(id as u64);
6690    day_spec::ffi_guard::contain((), move || {
6691        let event = if w > 0.0 && h > 0.0 {
6692            // The format and alpha were recorded when the decode was asked for; only the size
6693            // was unknown until now.
6694            let info = BITMAP_INFO.with(|m| {
6695                let mut m = m.borrow_mut();
6696                let info = m.entry(id.0).or_insert(day_spec::BitmapInfo {
6697                    pixels: Size::new(0.0, 0.0),
6698                    scale: 1.0,
6699                    format: None,
6700                    has_alpha: true,
6701                });
6702                info.pixels = Size::new(w, h);
6703                *info
6704            });
6705            Event::ImageDecoded {
6706                req: u64::from(req),
6707                result: Ok(info),
6708            }
6709        } else {
6710            BITMAP_INFO.with(|m| {
6711                m.borrow_mut().remove(&id.0);
6712            });
6713            Event::ImageDecoded {
6714                req: u64::from(req),
6715                result: Err(day_spec::ImageError::Decode),
6716            }
6717        };
6718        emit(day_spec::WINDOW_NODE, event);
6719    });
6720}
6721
6722/// The browser answering a canvas export (docs/canvas.md "Exporting"): `ok` is 1 when the bitmap
6723/// is stored under `id`; otherwise `ptr`/`len` are a `day_dom_alloc` buffer holding the engine's
6724/// error text (or empty), to take ownership of.
6725#[unsafe(no_mangle)]
6726pub extern "C" fn day_dom_bitmap_rendered(req: u32, id: f64, ok: u32, ptr: *mut u8, len: usize) {
6727    let id = day_spec::BitmapId(id as u64);
6728    let why = if ok == 0 && !ptr.is_null() && len > 0 {
6729        take_string(ptr, len)
6730    } else {
6731        String::new()
6732    };
6733    day_spec::ffi_guard::contain((), move || {
6734        let result = if ok != 0 {
6735            // `render_bitmap` recorded the size and scale when it asked. An id released while
6736            // the browser was still rendering has no record left; the shim's fresh entry goes too.
6737            BITMAP_INFO
6738                .with(|m| m.borrow().get(&id.0).copied())
6739                .ok_or_else(|| {
6740                    // SAFETY: an id the shim has just stored; releasing it is always valid.
6741                    unsafe { day_dom_image_release(id.0 as f64) };
6742                    day_spec::ExportError::Failed(
6743                        "the bitmap was released before it rendered".into(),
6744                    )
6745                })
6746        } else {
6747            BITMAP_INFO.with(|m| {
6748                m.borrow_mut().remove(&id.0);
6749            });
6750            Err(day_spec::ExportError::Failed(if why.is_empty() {
6751                "the canvas could not render".into()
6752            } else {
6753                why
6754            }))
6755        };
6756        emit(
6757            day_spec::WINDOW_NODE,
6758            Event::BitmapRendered {
6759                req: u64::from(req),
6760                result,
6761            },
6762        );
6763    });
6764}
6765
6766/// The browser answering an encode: `ptr`/`len` are a `day_dom_alloc` buffer to take ownership
6767/// of, or 0 when the canvas could not produce that type.
6768#[allow(clippy::not_unsafe_ptr_arg_deref)] // a live `day_dom_alloc` allocation from the shim
6769#[unsafe(no_mangle)]
6770pub extern "C" fn day_dom_image_encoded(req: u32, ptr: *mut u8, len: usize) {
6771    let result = if ptr.is_null() || len == 0 {
6772        Err(day_spec::ImageError::Encode)
6773    } else {
6774        // SAFETY: the shim wrote exactly `len` bytes into a `day_dom_alloc(len)` allocation, and
6775        // ownership passes here — the same contract `take_string` relies on.
6776        Ok(unsafe { take_bytes(ptr, len) })
6777    };
6778    day_spec::ffi_guard::contain((), move || {
6779        emit(
6780            day_spec::WINDOW_NODE,
6781            Event::ImageEncoded {
6782                req: u64::from(req),
6783                result,
6784            },
6785        );
6786    });
6787}
6788
6789#[unsafe(no_mangle)]
6790pub extern "C" fn day_dom_present_result(req: u32, which: i32, ptr: *mut u8, len: usize) {
6791    let result = if which == -1 {
6792        PresentResult::Dismissed
6793    } else if len > 0 {
6794        PresentResult::Text(take_string(ptr, len))
6795    } else {
6796        PresentResult::Button(i64::from(which))
6797    };
6798    day_spec::ffi_guard::contain((), move || {
6799        emit(
6800            day_spec::WINDOW_NODE,
6801            Event::PresentResult {
6802                req: u64::from(req),
6803                result,
6804            },
6805        );
6806    });
6807}
6808
6809thread_local! {
6810    /// The files of a several-files pick the shim has handed over so far, by request: each
6811    /// `day_dom_present_file_stage` adds one, and the closing `day_dom_present_files` drains
6812    /// them into the one `PresentResult::Files` answer (docs/files.md).
6813    static STAGED_FILES: RefCell<HashMap<u32, Vec<String>>> = RefCell::new(HashMap::new());
6814}
6815
6816/// Park a picked file's bytes in the `web_files` store under a fresh `/day-web/<id>/<leaf>`
6817/// path and return that path. `bytes` is `None` for a save flow, whose bytes already left as a
6818/// download.
6819fn store_picked_file(name: &str, bytes: Option<Vec<u8>>) -> String {
6820    static NEXT_FILE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(1);
6821    // The last path component only — a hostile/odd name must not escape the store's prefix.
6822    let leaf = name.rsplit(['/', '\\']).next().unwrap_or("file");
6823    let id = NEXT_FILE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6824    let path = format!("/day-web/{id}/{leaf}");
6825    #[cfg(all(target_family = "wasm", target_os = "unknown"))]
6826    if let Some(b) = bytes {
6827        day_spec::present::web_files::write(&path, b);
6828    }
6829    #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
6830    drop(bytes);
6831    path
6832}
6833
6834/// One file of a several-files pick, every one but the last: parked under its virtual path and
6835/// held for `req` until `day_dom_present_files` closes the pick with the final file.
6836#[allow(clippy::not_unsafe_ptr_arg_deref)] // both buffers are live `day_dom_alloc` allocations from the shim
6837#[unsafe(no_mangle)]
6838pub extern "C" fn day_dom_present_file_stage(
6839    req: u32,
6840    name_ptr: *mut u8,
6841    name_len: usize,
6842    bytes_ptr: *mut u8,
6843    bytes_len: usize,
6844) {
6845    let name = take_string(name_ptr, name_len);
6846    // SAFETY: the shim wrote exactly `bytes_len` bytes into a `day_dom_alloc` allocation.
6847    let bytes = (bytes_len > 0).then(|| unsafe { take_bytes(bytes_ptr, bytes_len) });
6848    day_spec::ffi_guard::contain((), move || {
6849        let path = store_picked_file(&name, bytes);
6850        STAGED_FILES.with(|s| s.borrow_mut().entry(req).or_default().push(path));
6851    });
6852}
6853
6854/// A file picker's answer: `name` is the chosen file's display name; `bytes` its content for
6855/// an open flow (len 0 for a save flow, whose bytes already left as a download). The bytes
6856/// land in the `web_files` store under `/day-web/<name>`, and that virtual path — after any
6857/// files staged for the same request — answers the awaiting flow as `PresentResult::Files`;
6858/// the pieces layer reads each back like a local path (docs/files.md).
6859#[allow(clippy::not_unsafe_ptr_arg_deref)] // both buffers are live `day_dom_alloc` allocations from the shim
6860#[unsafe(no_mangle)]
6861pub extern "C" fn day_dom_present_files(
6862    req: u32,
6863    name_ptr: *mut u8,
6864    name_len: usize,
6865    bytes_ptr: *mut u8,
6866    bytes_len: usize,
6867) {
6868    let name = take_string(name_ptr, name_len);
6869    // SAFETY: the shim wrote exactly `bytes_len` bytes into a `day_dom_alloc` allocation.
6870    let bytes = (bytes_len > 0).then(|| unsafe { take_bytes(bytes_ptr, bytes_len) });
6871    day_spec::ffi_guard::contain((), move || {
6872        let path = store_picked_file(&name, bytes);
6873        let mut paths = STAGED_FILES
6874            .with(|s| s.borrow_mut().remove(&req))
6875            .unwrap_or_default();
6876        paths.push(path);
6877        if req == 0 {
6878            day_core::request_open_files(paths);
6879            return;
6880        }
6881        emit(
6882            day_spec::WINDOW_NODE,
6883            Event::PresentResult {
6884                req: u64::from(req),
6885                result: PresentResult::Files(paths),
6886            },
6887        );
6888    });
6889}
6890
6891/// A document-level clipboard event (the browser's own ⌘X/⌘C/⌘V route, or the Edit menu of
6892/// the browser itself) that no editable element claimed — the shim's `copy`/`cut`/`paste`
6893/// listeners forward it here while the event is still live, so day-part-clipboard's
6894/// synchronous calls inside the app's handler read and write the event's `clipboardData`
6895/// (docs/menus.md).
6896/// The browser's text size moved (a resize or a return to the page re-read it): every tracked
6897/// reader and every capped label follow (docs/text.md "Text size").
6898#[unsafe(no_mangle)]
6899pub extern "C" fn day_dom_text_scale_changed() {
6900    day_spec::ffi_guard::contain((), || {
6901        MEASURE_CACHE.with(|c| c.borrow_mut().clear());
6902        post_local(day_core::note_text_size_changed);
6903    });
6904}
6905
6906/// The reader's selection in a reporting label changed (docs/text.md "Selection"): `start` and
6907/// `end` are UTF-16 offsets into the element's text, equal when the selection left it.
6908#[unsafe(no_mangle)]
6909pub extern "C" fn day_dom_label_selected(el: u32, start: u32, end: u32) {
6910    day_spec::ffi_guard::contain((), || {
6911        let Some((start, end)) = LABELS.with(|t| {
6912            let mut t = t.borrow_mut();
6913            let st = t.get_mut(&el)?;
6914            let a = utf16_to_byte(&st.text, start as usize);
6915            let b = utf16_to_byte(&st.text, end as usize).max(a);
6916            st.selected = b > a;
6917            Some((a, b))
6918        }) else {
6919            return;
6920        };
6921        if let Some(node) = node_of(el) {
6922            emit(node, Event::TextSelected { start, end });
6923        }
6924    });
6925}
6926
6927/// The device behind the latest pointer down or hover changed (docs/gestures.md "Input kind"):
6928/// `kind` 0 touch, 1 mouse, 2 stylus.
6929#[unsafe(no_mangle)]
6930pub extern "C" fn day_dom_pointer_kind_changed(kind: u32) {
6931    day_spec::ffi_guard::contain((), || {
6932        emit(
6933            day_spec::WINDOW_NODE,
6934            Event::PointerKindChanged(pointer_kind(kind)),
6935        );
6936    });
6937}
6938
6939#[unsafe(no_mangle)]
6940pub extern "C" fn day_dom_edit(op: u32) {
6941    day_spec::ffi_guard::contain((), || {
6942        let op = match op {
6943            0 => day_spec::EditOp::Cut,
6944            1 => day_spec::EditOp::Copy,
6945            2 => day_spec::EditOp::Paste,
6946            _ => day_spec::EditOp::SelectAll,
6947        };
6948        emit(day_spec::WINDOW_NODE, Event::Edit(op));
6949    });
6950}
6951
6952/// A non-text key pressed while this canvas has focus (docs/menus.md): `code` 0–5 is an arrow
6953/// or a delete key, 10–19 a digit; `modifiers` the day mask, with bit 8 for a repeat and bit 9
6954/// for the release of a press this element claimed. Returns whether the app claimed it — a
6955/// canvas nobody hung a key handler on keeps none of them, so the browser's own scrolling still
6956/// works underneath it.
6957#[unsafe(no_mangle)]
6958pub extern "C" fn day_dom_canvas_key(el: u32, code: u32, modifiers: u32) -> u32 {
6959    day_spec::ffi_guard::contain(0, || {
6960        let key = match code {
6961            0 => "ArrowLeft",
6962            1 => "ArrowRight",
6963            2 => "ArrowUp",
6964            3 => "ArrowDown",
6965            4 => "Delete",
6966            5 => "Backspace",
6967            10..=19 => day_spec::KeyEvent::DIGITS[(code - 10) as usize],
6968            _ => return 0,
6969        };
6970        let Some(node) = node_of(el) else {
6971            return 0;
6972        };
6973        if !day_spec::keys::handled(node) {
6974            return 0;
6975        }
6976        emit(node, Event::Key(phased_key(key, None, modifiers)));
6977        1
6978    })
6979}
6980
6981/// A text field's Up, Down or Escape (docs/textfield.md "Keys"): `code` 0 is `ArrowUp`, 1
6982/// `ArrowDown`, 2 Escape, `modifiers` the day mask with the phase in bits 8 and 9. Returns whether the field claimed it, having
6983/// reported it; the shim then keeps the browser from acting on the key.
6984#[unsafe(no_mangle)]
6985pub extern "C" fn day_dom_field_key(el: u32, code: u32, modifiers: u32) -> u32 {
6986    day_spec::ffi_guard::contain(0, || {
6987        let Some(&key) = day_spec::keys::FIELD_KEYS.get(code as usize) else {
6988            return 0;
6989        };
6990        let Some(node) = node_of(el) else {
6991            return 0;
6992        };
6993        // A release follows the press the field claimed (the shim sends only those); a press
6994        // or a repeat asks again.
6995        let phase = day_spec::KeyPhase::from_wire(f64::from(modifiers));
6996        if phase != day_spec::KeyPhase::Up
6997            && !day_spec::keys::field_claims(node, key, (modifiers & 0xff) as u8)
6998        {
6999            return 0;
7000        }
7001        emit(
7002            node,
7003            Event::Key(day_spec::KeyEvent::named(key, 0).with_phase(phase)),
7004        );
7005        1
7006    })
7007}
7008
7009/// Whether this canvas took the whole keyboard (`Decorate::keyboard`, docs/menus.md): the
7010/// shim asks on every key, before it names one.
7011#[unsafe(no_mangle)]
7012pub extern "C" fn day_dom_canvas_text(el: u32) -> u32 {
7013    day_spec::ffi_guard::contain(0, || {
7014        u32::from(node_of(el).is_some_and(day_spec::keys::text))
7015    })
7016}
7017
7018/// A key on the full route (docs/menus.md "The full route"): `key`/`key_len` the browser's
7019/// `KeyboardEvent.key`, which is day's own vocabulary (empty for text no single key is
7020/// behind), `text`/`text_len` what it typed (`text_len` 0 for a key that typed nothing),
7021/// `modifiers` the day mask with the phase in bits 8 and 9. Returns whether the app claimed it.
7022#[unsafe(no_mangle)]
7023pub extern "C" fn day_dom_canvas_text_key(
7024    el: u32,
7025    key: *mut u8,
7026    key_len: usize,
7027    text: *mut u8,
7028    text_len: usize,
7029    modifiers: u32,
7030) -> u32 {
7031    let key = take_string(key, key_len);
7032    let text = (text_len > 0).then(|| take_string(text, text_len));
7033    day_spec::ffi_guard::contain(0, move || {
7034        let Some(node) = node_of(el) else {
7035            return 0;
7036        };
7037        if !day_spec::keys::handled(node) {
7038            return 0;
7039        }
7040        emit(node, Event::Key(phased_key(&key, text, modifiers)));
7041        1
7042    })
7043}
7044
7045/// The platform-standard undo shortcut (⌘Z / Ctrl+Z, shift or Ctrl+Y for redo) pressed with
7046/// no editable element focused — the shim's keydown route (the browser has no document-level
7047/// undo of its own to integrate with, so the standard keys are the platform affordance).
7048#[unsafe(no_mangle)]
7049pub extern "C" fn day_dom_undo(redo: u32) {
7050    day_spec::ffi_guard::contain((), || {
7051        emit(day_spec::WINDOW_NODE, Event::Undo { redo: redo != 0 });
7052    });
7053}
7054
7055/// A toolbar button or menu entry was chosen — the same `MenuAction` every other backend
7056/// emits. The action id crosses as an f64: it is a small counter, far inside the range an f64
7057/// represents exactly.
7058#[unsafe(no_mangle)]
7059pub extern "C" fn day_dom_toolbar_action(action: f64) {
7060    day_spec::ffi_guard::contain((), || {
7061        emit(day_spec::WINDOW_NODE, Event::MenuAction(action as u64));
7062    });
7063}
7064
7065/// A toolbar toggle flipped.
7066#[unsafe(no_mangle)]
7067pub extern "C" fn day_dom_toolbar_on(action: f64, on: u32) {
7068    day_spec::ffi_guard::contain((), || {
7069        emit(
7070            day_spec::WINDOW_NODE,
7071            Event::ToolbarChanged {
7072                action: action as u64,
7073                value: day_spec::ToolbarValue::On(on != 0),
7074            },
7075        );
7076    });
7077}
7078
7079/// A toolbar segmented control's choice changed.
7080#[unsafe(no_mangle)]
7081pub extern "C" fn day_dom_toolbar_value(action: f64, index: u32) {
7082    day_spec::ffi_guard::contain((), || {
7083        emit(
7084            day_spec::WINDOW_NODE,
7085            Event::ToolbarChanged {
7086                action: action as u64,
7087                value: day_spec::ToolbarValue::Selected(index as usize),
7088            },
7089        );
7090    });
7091}
7092
7093/// A toolbar search field's text changed. `take_string` takes ownership of the shim's
7094/// allocation, the way the other text callbacks here do.
7095#[unsafe(no_mangle)]
7096pub extern "C" fn day_dom_toolbar_text(action: f64, ptr: *mut u8, len: usize) {
7097    let text = take_string(ptr, len);
7098    day_spec::ffi_guard::contain((), move || {
7099        emit(
7100            day_spec::WINDOW_NODE,
7101            Event::ToolbarChanged {
7102                action: action as u64,
7103                value: day_spec::ToolbarValue::Text(text),
7104            },
7105        );
7106    });
7107}
7108
7109/// A toolbar search field was submitted with Return (docs/search.md). The shim has already sent
7110/// the field's latest text through [`day_dom_toolbar_text`] when it differed from the last one.
7111#[unsafe(no_mangle)]
7112pub extern "C" fn day_dom_toolbar_submit(action: f64, ptr: *mut u8, len: usize) {
7113    let text = take_string(ptr, len);
7114    day_spec::ffi_guard::contain((), move || {
7115        emit(
7116            day_spec::WINDOW_NODE,
7117            Event::ToolbarChanged {
7118                action: action as u64,
7119                value: day_spec::ToolbarValue::Submit(text),
7120            },
7121        );
7122    });
7123}
7124
7125#[unsafe(no_mangle)]
7126pub extern "C" fn day_dom_posted() {
7127    // The closures queued when this turn began, taken one at a time and each contained, so one
7128    // that fails cannot drop the ones queued behind it. A panic is caught here. A JavaScript
7129    // exception from an import is not: it unwinds through every wasm frame up to the shim's
7130    // microtask without running a destructor. The closures behind it must then still be in
7131    // the queue, where the turns already scheduled for them (one per post) run them. Drained
7132    // up front, they would be lost, and with them day-reactive's coalesced drain, whose
7133    // "posted" flag then stays set: no later signal write would reach its effects. Closures
7134    // posted from here wait for their own turn.
7135    let queued = POSTED.with(|q| q.borrow().len());
7136    for _ in 0..queued {
7137        let Some(f) = POSTED.with(|q| q.borrow_mut().pop_front()) else {
7138            break;
7139        };
7140        day_spec::ffi_guard::contain((), f);
7141    }
7142}
7143
7144#[unsafe(no_mangle)]
7145pub extern "C" fn day_dom_delayed(token: u32) {
7146    if let Some(f) = DELAYED.with(|m| m.borrow_mut().remove(&token)) {
7147        day_spec::ffi_guard::contain((), f);
7148    }
7149}
7150
7151#[unsafe(no_mangle)]
7152pub extern "C" fn day_dom_frame(token: f64, ts: f64) {
7153    day_core::frame::native::deliver(token as u64, day_spec::FrameStamp::new(ts));
7154}
7155
7156#[unsafe(no_mangle)]
7157pub extern "C" fn day_dom_resized(w: f64, h: f64) {
7158    day_spec::ffi_guard::contain((), || {
7159        LAST_VIEWPORT.with(|v| v.set(Size::new(w, h)));
7160        // day-core re-buckets the window's size class from this (docs/size-classes.md) — a
7161        // backend reports geometry, not classes, so there is one breakpoint table rather than
7162        // nine.
7163        emit(day_spec::WINDOW_NODE, Event::WindowResized(Size::new(w, h)));
7164    });
7165}
7166
7167/// The page's display state, as the browser last reported it.
7168///
7169/// Called by the shim on `fullscreenchange` (entering, leaving, the user's Esc) with
7170/// `declined` = 0, and when the browser refuses a request (no user gesture, a permissions
7171/// policy) with `declined` = 1 and the state the page kept.
7172#[unsafe(no_mangle)]
7173pub extern "C" fn day_dom_window_state(code: i32, declined: u32) {
7174    day_spec::ffi_guard::contain((), || {
7175        report_window_state(day_spec::WindowState::from_code(code), declined != 0);
7176    });
7177}
7178
7179/// Report the page's display state on `WINDOW_NODE`, deduped against the last report. A
7180/// declined request reports even when nothing changed, so day-core's optimistic `state()`
7181/// signal settles back on the truth (docs/windows.md "Window properties").
7182fn report_window_state(state: day_spec::WindowState, declined: bool) {
7183    let was = WINDOW_STATE.with(|c| c.replace(state));
7184    if declined {
7185        log::debug!("web: window state request declined, still {state:?}");
7186    } else if was == state {
7187        return;
7188    } else {
7189        log::debug!("web: window state now {state:?}");
7190    }
7191    emit(day_spec::WINDOW_NODE, Event::WindowStateChanged(state));
7192}
7193
7194/// How far an installed app's window-controls overlay reaches into the page, from the shim on
7195/// every `geometrychange` after boot (`run` seeds the boot value); 0 while the user shows the
7196/// title bar. Only an Overlay primary reports, as its safe-area top inset
7197/// (docs/window-chrome.md). A fresh browser task: the tree is free.
7198#[unsafe(no_mangle)]
7199pub extern "C" fn day_dom_titlebar_inset(top: f64) {
7200    day_spec::ffi_guard::contain((), || {
7201        log::debug!("web: title bar overlay inset {top}");
7202        day_core::set_safe_area(day_spec::Insets {
7203            top,
7204            ..Default::default()
7205        });
7206    });
7207}
7208
7209/// Put the effective appearance on the page: the window's override, else the app-wide one,
7210/// else the browser's `prefers-color-scheme`.
7211fn apply_appearance() {
7212    let (app, window) = APPEARANCE.with(std::cell::Cell::get);
7213    let mode = match window.or(app) {
7214        Some(false) => 0,
7215        Some(true) => 1,
7216        None => 2,
7217    };
7218    let effective = unsafe { day_dom_set_dark(mode) };
7219    DARK.with(|d| d.set(effective == 1));
7220}
7221
7222/// Whether the browser has the Window Controls Overlay API, read once.
7223fn window_controls_overlay() -> bool {
7224    thread_local! {
7225        static WCO: std::cell::OnceCell<bool> = const { std::cell::OnceCell::new() };
7226    }
7227    WCO.with(|c| *c.get_or_init(|| env("wco") == "1"))
7228}
7229
7230/// `document.fullscreenEnabled`, read once: whether this page can go fullscreen at all.
7231fn fullscreen_enabled() -> bool {
7232    thread_local! {
7233        static ENABLED: std::cell::OnceCell<bool> = const { std::cell::OnceCell::new() };
7234    }
7235    ENABLED.with(|c| *c.get_or_init(|| env("fullscreen") == "1"))
7236}
7237
7238/// The reduce-motion media query flipped under the app (docs/accessibility.md): day-core
7239/// re-reads the setting through `Toolkit::reduce_motion` and re-gates its transitions.
7240#[unsafe(no_mangle)]
7241pub extern "C" fn day_dom_motion_changed() {
7242    day_spec::ffi_guard::contain((), day_core::note_motion_changed);
7243}
7244
7245/// The browser's `prefers-color-scheme` flipped while the page follows it (no override): the
7246/// shim has switched the page already, and every ink on it followed in CSS. Day re-reads its
7247/// palette and dark signal, which redraws canvases and re-runs appearance readers.
7248#[unsafe(no_mangle)]
7249pub extern "C" fn day_dom_appearance_changed(dark: u32) {
7250    DARK.with(|d| d.set(dark == 1));
7251    day_spec::ffi_guard::contain((), day_core::note_appearance_changed);
7252}
7253
7254#[unsafe(no_mangle)]
7255pub extern "C" fn day_dom_lifecycle(phase: u32) {
7256    let phase = match phase {
7257        0 => Lifecycle::DidBecomeActive,
7258        1 => Lifecycle::WillResignActive,
7259        // `pagehide`: the page is going away (a navigation, a reload, a closed tab), which is
7260        // the last moment the app runs (docs/lifecycle.md).
7261        2 => Lifecycle::DidExit,
7262        _ => return,
7263    };
7264    day_spec::ffi_guard::contain((), || {
7265        emit(day_spec::WINDOW_NODE, Event::Lifecycle(phase));
7266    });
7267}
7268
7269/// The host page's launch locale (`?locale=` else `navigator.languages`), for the `day::web`
7270/// glue to hand to `set_launch_locale` before the app installs its catalogs — wasm has no
7271/// process environment for a `DAY_LOCALE` variable to live in.
7272pub fn launch_locale() -> Option<String> {
7273    env("locales")
7274        .split(',')
7275        .next()
7276        .filter(|l| !l.is_empty())
7277        .map(str::to_owned)
7278}
7279
7280/// The page's launch route (the URL hash, else `?route=`), for the `day::web` glue to hand to
7281/// `set_launch_deeplink` — the web spelling of `DAY_DEEPLINK` (docs/navigation.md).
7282/// Original external protocol URL delivered by an installed PWA protocol handler.
7283#[must_use]
7284pub fn launch_open_url() -> Option<String> {
7285    let url = env("day_url");
7286    (!url.is_empty()).then_some(url)
7287}
7288#[must_use]
7289pub fn launch_route() -> Option<String> {
7290    let route = env("route");
7291    (!route.is_empty()).then_some(route)
7292}
7293
7294/// The page's dayscript token (`?dayscript=`), the query-parameter spelling of
7295/// `DAYSCRIPT_TOKEN` — present only when a `day launch` scripted/drivable session serves the
7296/// page (docs/web.md). The `day::web` glue arms the engine's web transport with it.
7297#[must_use]
7298pub fn dayscript_token() -> Option<String> {
7299    let token = env("dayscript");
7300    (!token.is_empty()).then_some(token)
7301}
7302
7303/// Send one dayscript reply line to the page (the engine's web sender — docs/web.md).
7304pub fn script_send(line: &str) {
7305    unsafe { day_dom_script_send(line.as_ptr(), line.len()) };
7306}
7307
7308/// Reclaim a shim-written string (a `day_dom_alloc` buffer) — for exports outside this crate
7309/// (the `day` umbrella defines `day_dom_script_line`, which routes to day-script; a backend
7310/// cannot depend on the engine).
7311pub fn take_alloc_string(ptr: *mut u8, len: usize) -> String {
7312    take_string(ptr, len)
7313}
7314
7315/// The URL hash changed under the app (browser back/forward, or a hand-edited hash). The shim
7316/// suppresses the echo of our own `day_dom_set_hash`, so every call here is a real request.
7317#[unsafe(no_mangle)]
7318pub extern "C" fn day_dom_hash_changed(ptr: *mut u8, len: usize) {
7319    let route = take_string(ptr, len);
7320    day_spec::ffi_guard::contain((), move || {
7321        emit(day_spec::WINDOW_NODE, Event::RouteRequested(route));
7322    });
7323}
7324
7325/// Install a panic hook that reports through the shim's console before the trap.
7326pub fn install_panic_hook() {
7327    std::panic::set_hook(Box::new(|info| {
7328        warn(&format!("day panic: {info}"));
7329    }));
7330}
7331
7332/// The browser-console sink for Day's logger (docs/logging.md).
7333///
7334/// Hand-rolled rather than `console_log` or `wasm-logger`: both require `web-sys` (and
7335/// wasm-logger `wasm-bindgen`), which this backend deliberately does without — the whole shim is
7336/// numeric ids across `extern "C"`, with no bundler and no npm. Routing an already-formatted line
7337/// to `console.*` is one call, so the dependency would buy nothing and cost the toolchain.
7338///
7339/// Pass this to `day_core::set_log_sink`; the facade does it in `day::web::start`.
7340pub fn console_sink(level: log::Level, line: &str) {
7341    unsafe { day_dom_log(level as u32, line.as_ptr(), line.len()) };
7342}
7343
7344/// The level named by `?DAY_LOG=` in the page URL, if any. The web has no process environment for
7345/// `DAY_LOG` to live in, so the launch server forwards it as a query parameter (docs/web.md) —
7346/// `day launch -t web-dom --env DAY_LOG=debug` reaches this.
7347#[must_use]
7348pub fn launch_log_level() -> Option<log::LevelFilter> {
7349    host_env("DAY_LOG").and_then(|v| v.parse().ok())
7350}