Skip to main content

nsh_core/core/
mod.rs

1mod canvas_render;
2mod classes;
3mod components;
4mod cull;
5mod focus_ring;
6mod follow;
7mod layout_scope;
8mod layout_tree;
9mod list;
10mod list_motion;
11mod measure;
12mod overlay;
13mod pace;
14mod parent_viewport;
15mod relations;
16mod renders;
17mod resize_anchor;
18mod scrollbars;
19mod selection_ends;
20mod services;
21mod slots;
22mod sticky;
23mod terminal_layout;
24#[cfg(test)]
25mod tests;
26mod touch;
27mod views;
28mod watch;
29mod web_evaluation;
30
31/// The most network image checks [`Core`] remembers for its canvases; past
32/// it, it starts over.
33const CANVAS_IMAGES: usize = 1024;
34
35/// The start of a player's error when the core refuses its source; the
36/// capability that would grant it follows (`network`, `fs`).
37pub(crate) const SOURCE_NOT_GRANTED: &str = "the source is not granted by capabilities.";
38
39use std::{rc::Rc, sync::Arc};
40
41use slab::Slab;
42use taffy::{AvailableSpace, NodeId as LayoutId, Overflow, Position};
43
44#[doc(hidden)]
45pub use self::components::set_part_requester;
46pub use self::measure::{ListScrollPosition, Measurement};
47use self::{
48    layout_tree::LayoutTree,
49    list::{ExtraKind, Follow, ListState, PendingScroll, PinTarget},
50};
51use crate::{
52    animation::AnimationProp,
53    geometry::{Bounds, Percentage, Point, Points, Size, rect, size_pt},
54    mount::{
55        InputConfig, ModalConfig, MountBatch, MountItem, NativeProps, ScreenConfig, ScrollBehavior,
56        StickyCell, VideoProps, ViewKind,
57    },
58    ops::{
59        CellSlot, Command, EventKind, EventMask, EventPayload, HeaderSlot, ImageProp, ImageSource,
60        KeyboardDismissMode, ModalAnimation, ModalProp, NativeProp, NodeId, Op, PayloadValue, Prop,
61        ROOT_ID, ResizeMode, ScreenAnimation, ScreenProp, ScrollProp, Tag,
62    },
63    props::{AccessibilityProp, EdgeInsets, GestureValues, LayoutAnimation, ViewProps},
64    style::{Color, PaintStyle, Style, StylePatch, TextAlign, TextStyle, ViewStyle},
65    tailwind::{ClassEnvironment, ClassList, ClassProps, Tailwind},
66    text::{AttributedText, MeasureCache, ResolvedTextStyle, TextEngine, TextLayout},
67};
68
69/// Slab index of a node. Internal links use keys, never ids, to avoid the
70/// id -> key indirection on hot paths.
71type Key = u32;
72
73/// A raw text run with no node of its own ([`Core::runs`]).
74struct Run {
75    text: String,
76    /// The block or span holding it; `NO_KEY` when it is not in the tree.
77    block: Key,
78}
79
80/// A view's built-in scroll bar (`scrollbars.rs`) and the theme of its own
81/// it was made with.
82/// A view's built-in bar, and the theme of the view's own it was made
83/// with (`None`: the app's).
84type Bar = (NodeId, Option<crate::ScrollbarSetting>);
85
86const NO_KEY: Key = Key::MAX;
87
88/// Rounds of binding the components' own lists per commit, at most.
89const MAX_VIRTUAL_ROUNDS: u32 = 8;
90/// The longest run without a line-break opportunity a multiline input's value is
91/// measured with unbroken (`broken_runs`): longer than a line of any input,
92/// so ordinary text measures as it is shown.
93const MEASURED_RUN: usize = 1024;
94/// Dirty flags, processed once per commit.
95mod dirty {
96    /// Emit [`crate::MountItem::ViewStyle`].
97    pub(super) const VIEW: u32 = 1 << 0;
98    /// Emit [`crate::MountItem::Events`].
99    pub(super) const EVENTS: u32 = 1 << 1;
100    /// Rebuild the attributed text of a text block.
101    pub(super) const TEXT_BUILD: u32 = 1 << 2;
102    /// Lay out the text block again and emit [`crate::MountItem::Text`].
103    pub(super) const TEXT_MOUNT: u32 = 1 << 3;
104    /// Emit [`crate::MountItem::Image`].
105    pub(super) const IMAGE: u32 = 1 << 4;
106    /// Emit [`crate::MountItem::ScrollConfig`].
107    pub(super) const SCROLL: u32 = 1 << 5;
108    /// Emit [`crate::MountItem::Refreshing`].
109    pub(super) const REFRESHING: u32 = 1 << 6;
110    /// Emit [`crate::MountItem::AnimationBindings`].
111    pub(super) const ANIMATION: u32 = 1 << 7;
112    /// Emit [`crate::MountItem::PanValues`].
113    pub(super) const PAN: u32 = 1 << 8;
114    /// Emit [`crate::MountItem::Input`].
115    pub(super) const INPUT: u32 = 1 << 9;
116    /// Emit [`crate::MountItem::InputValue`].
117    pub(super) const INPUT_VALUE: u32 = 1 << 10;
118    /// Emit [`crate::MountItem::ViewProps`].
119    pub(super) const VIEW_PROPS: u32 = 1 << 11;
120    /// Emit [`crate::MountItem::ScreenConfig`].
121    pub(super) const SCREEN: u32 = 1 << 12;
122    /// Emit [`crate::MountItem::ModalConfig`].
123    pub(super) const MODAL: u32 = 1 << 13;
124    /// Emit [`crate::MountItem::NativeProps`].
125    pub(super) const NATIVE: u32 = 1 << 14;
126    /// Emit [`crate::MountItem::ScrollBehavior`].
127    pub(super) const SCROLL_BEHAVIOR: u32 = 1 << 15;
128    /// Emit [`crate::MountItem::Canvas`].
129    pub(super) const CANVAS: u32 = 1 << 16;
130    /// Emit [`crate::MountItem::ComponentProps`].
131    pub(super) const COMPONENT: u32 = 1 << 17;
132    /// Emit [`crate::MountItem::AccessibilityLabel`] (unless
133    /// [`VIEW_PROPS`] sends everything).
134    pub(super) const LABEL: u32 = 1 << 18;
135    /// Emit [`crate::MountItem::Shader`].
136    pub(super) const SHADER: u32 = 1 << 19;
137    /// Emit [`crate::MountItem::NavShader`].
138    pub(super) const NAV_SHADER: u32 = 1 << 20;
139}
140
141/// A layout root other than the surface's: screens, modals and header
142/// items are laid out on their own, at a size their container gives them.
143#[derive(Debug, Default)]
144struct RootState {
145    /// Size the platform reported for the root (modals).
146    reported: Option<Size<Points>>,
147    /// Safe-area insets the platform reported for the root (modals).
148    insets: EdgeInsets,
149    /// Height of the header the platform measured above the content
150    /// (screens; until then, estimated from the bar's height and the safe
151    /// area).
152    header: Option<f32>,
153    /// The size and header height the root was last laid out with.
154    laid_out: Option<(Size<Points>, f32)>,
155    /// Screen options (screens).
156    screen: ScreenConfig,
157    /// Modal options (modals).
158    modal: ModalConfig,
159    /// `transitionShader` (screens and modals), as the platform gets it.
160    nav_shader: Option<crate::NavShader>,
161    /// Where a header item goes (header items).
162    slot: HeaderSlot,
163    /// A leading, trailing or title header item laid out with no width: nothing
164    /// of it shows, so the screen's options leave it out of the bar.
165    empty: bool,
166    /// `nativeID` (input accessories).
167    native_id: Option<Box<str>>,
168    /// `statusBar` (screens and modals).
169    status_bar: Option<crate::StatusBarSetting>,
170    /// Its entry in the surface's status bars, while the node is in the
171    /// tree ([`Core::sync_status_bars`]).
172    status_bar_entry: Option<crate::element::status_bar::StatusBarEntry>,
173    /// Placement and root view (overlays).
174    overlay: Option<Box<overlay::OverlayState>>,
175}
176
177/// Paragraph settings of a text block (or input).
178#[derive(Debug, Clone, Copy, PartialEq)]
179struct Paragraph {
180    /// `allowFontScaling`.
181    allow_font_scaling: bool,
182    /// `maxFontSizeMultiplier`; 0 means no limit.
183    max_font_multiplier: f32,
184    /// `selectionColor` of selectable text.
185    selection_color: Option<crate::Color>,
186    /// `adjustsFontSizeToFit`.
187    fit: bool,
188    /// `minimumFontScale`.
189    min_font_scale: f32,
190}
191
192impl Default for Paragraph {
193    fn default() -> Self {
194        Self {
195            allow_font_scaling: true,
196            max_font_multiplier: 0.0,
197            selection_color: None,
198            fit: false,
199            min_font_scale: 0.0,
200        }
201    }
202}
203
204impl Paragraph {
205    /// The factor applied to font sizes for the user's text size setting.
206    fn font_multiplier(&self, font_scale: f32) -> f32 {
207        if !self.allow_font_scaling {
208            return 1.0;
209        }
210        if self.max_font_multiplier >= 1.0 {
211            font_scale.min(self.max_font_multiplier)
212        } else {
213            font_scale
214        }
215    }
216}
217
218#[derive(Debug, Clone, Copy, PartialEq, Eq)]
219enum Kind {
220    View,
221    Text,
222    RawText,
223    Image,
224    Scroll,
225    List,
226    Cell,
227    Input,
228    Stack,
229    Screen,
230    Modal,
231    HeaderItem,
232    InputAccessory,
233    Canvas,
234    WebView,
235    Video,
236    Native,
237    Overlay,
238    Shader,
239    /// A GPU view ([`crate::gpu`]): a view whose box its renderer draws
240    /// under its children, with a native component's own props.
241    GpuView,
242}
243
244impl Kind {
245    /// Kinds whose native view hosts child views.
246    fn is_container(self) -> bool {
247        matches!(
248            self,
249            Kind::View
250                | Kind::Scroll
251                | Kind::List
252                | Kind::Cell
253                | Kind::Stack
254                | Kind::Screen
255                | Kind::Modal
256                | Kind::HeaderItem
257                | Kind::InputAccessory
258                | Kind::Overlay
259                | Kind::Shader
260                | Kind::GpuView
261        )
262    }
263
264    /// Kinds laid out as their own root, not as part of their parent.
265    fn is_root(self) -> bool {
266        matches!(
267            self,
268            Kind::Screen | Kind::Modal | Kind::HeaderItem | Kind::InputAccessory | Kind::Overlay
269        )
270    }
271
272    fn view_kind(self) -> ViewKind {
273        match self {
274            Kind::Text => ViewKind::Text,
275            Kind::Image => ViewKind::Image,
276            Kind::Scroll | Kind::List => ViewKind::Scroll,
277            Kind::Input => ViewKind::Input,
278            Kind::Stack => ViewKind::Stack,
279            Kind::Screen => ViewKind::Screen,
280            Kind::Modal => ViewKind::Modal,
281            Kind::HeaderItem => ViewKind::HeaderItem,
282            Kind::InputAccessory => ViewKind::InputAccessory,
283            Kind::Canvas => ViewKind::Canvas,
284            Kind::WebView => ViewKind::WebView,
285            Kind::Video => ViewKind::Video,
286            Kind::Native => ViewKind::Native,
287            // A shader's view is a view the platform draws its layer in
288            // (`MountItem::Shader`), under its children.
289            // A GPU view's, the view the platform shows its frames in
290            // (`MountItem::GpuView`), under its children.
291            Kind::View
292            | Kind::Cell
293            | Kind::RawText
294            | Kind::Overlay
295            | Kind::Shader
296            | Kind::GpuView => ViewKind::View,
297        }
298    }
299
300    /// Kinds whose taffy style is derived from the JS style (and must keep
301    /// the JS style around to re-derive it).
302    fn of(tag: Tag) -> Self {
303        match tag {
304            Tag::View => Kind::View,
305            Tag::Text => Kind::Text,
306            Tag::Image => Kind::Image,
307            Tag::Scroll => Kind::Scroll,
308            Tag::List => Kind::List,
309            Tag::Cell => Kind::Cell,
310            Tag::Input => Kind::Input,
311            Tag::Stack => Kind::Stack,
312            Tag::Screen => Kind::Screen,
313            Tag::Modal => Kind::Modal,
314            Tag::HeaderItem => Kind::HeaderItem,
315            Tag::InputAccessory => Kind::InputAccessory,
316            Tag::Canvas => Kind::Canvas,
317            Tag::WebView => Kind::WebView,
318            Tag::Video => Kind::Video,
319            Tag::Native => Kind::Native,
320            Tag::Overlay => Kind::Overlay,
321            Tag::Shader
322            | Tag::ShaderEffect
323            | Tag::ShaderTransition
324            | Tag::ScreenEffect
325            | Tag::ScreenTransition => Kind::Shader,
326            Tag::GpuView => Kind::GpuView,
327        }
328    }
329
330    /// Whether its layout node's style is derived from the one JS set,
331    /// which the node then keeps too ([`Node::base_layout`]).
332    fn derives_layout(self) -> bool {
333        matches!(
334            self,
335            Kind::Scroll | Kind::List | Kind::Cell | Kind::Screen | Kind::Modal | Kind::Overlay
336        )
337    }
338}
339
340/// The prop a native component's `accentColor` style reaches it as
341/// ([`Core::sync_accent`]).
342const ACCENT_PROP: &str = "accentColor";
343
344/// A registered native component: its name and properties, as JS set them.
345#[derive(Debug, Default)]
346struct ComponentState {
347    name: Option<Arc<str>>,
348    props: Vec<(Arc<str>, crate::JsonValue)>,
349    /// Properties changed since the last commit.
350    changed: Vec<Arc<str>>,
351    /// The names of its animated prop slots (`AnimationProp::ComponentSlot`):
352    /// a name keeps its slot once given one.
353    slots: Vec<Arc<str>>,
354    /// The bound slots and their animation nodes. A bound prop's value in
355    /// `props` is kept but not sent until it is unbound.
356    bound: Vec<(u16, crate::animation::NodeId)>,
357    /// `slots` changed since the platform was last told (a `Cell`: the
358    /// commit clears it while it reads the node).
359    slots_changed: std::cell::Cell<bool>,
360    /// A GPU view's renderer ([`crate::gpu`]); a native component's is
361    /// its `name`.
362    source: Option<crate::gpu::GpuSource>,
363}
364
365impl ComponentState {
366    fn is_bound(&self, name: &str) -> bool {
367        self.bound
368            .iter()
369            .any(|(s, _)| &*self.slots[*s as usize] == name)
370    }
371}
372
373#[derive(Debug)]
374struct ScrollState {
375    horizontal: bool,
376    scrollbar: crate::ScrollbarSetting,
377    /// Its built-in bar ([`Core::sync_scrollbars`]).
378    bar: Option<Bar>,
379    refreshing: bool,
380    scroll_value: Option<crate::animation::NodeId>,
381    pull_value: Option<crate::animation::NodeId>,
382    keyboard_dismiss: KeyboardDismissMode,
383    /// Last content size sent to the platform.
384    content: Option<Size<Points>>,
385    /// Where in the mount items the last `ScrollContent` was queued: a
386    /// later size in the same batch replaces it, so a row relaid in two
387    /// passes never sends the platform a transient size (which would clamp
388    /// the offset before the content grows back). With the batch it is in
389    /// ([`Core::batches`]).
390    content_item: Option<(u64, usize)>,
391    /// Its content size laid out while it was culled
392    /// ([`Core::cull_frames_in`]): the first its native view gets.
393    culled_content: Option<Size<Points>>,
394    behavior: ScrollBehavior,
395    /// Minimum milliseconds between `onScroll` events.
396    event_throttle_ms: f32,
397    /// The zoom scale the platform reported.
398    zoom: f32,
399    /// The content offset the platform reported.
400    offset: (f32, f32),
401    /// How far the platform's last report moved it, when the user (not the
402    /// core's own scrolls) did: what it makes reaches ahead by it
403    /// ([`ScrollState::lead`]).
404    step: (f32, f32),
405    /// Scrolls the core sent a plain scroll view since its native view was
406    /// made (`ScrollBy` items and `ScrollTo` commands; lists count theirs in
407    /// their state): platforms report how many they applied.
408    issued: u32,
409    /// Where the last `ScrollTo` sent scrolls it, with its number in
410    /// `issued` (moved by the `ScrollBy`s after it), until a report shows
411    /// it applied: `reveal` starts from there.
412    target: Option<(u32, (f32, f32))>,
413    /// The lists virtualized against this scroll view (`viewport="parent"`;
414    /// empty for nearly every scroll view).
415    dependents: Vec<Key>,
416    /// While it has such lists: the scrolls issued that the reports do not
417    /// show applied yet.
418    pending: Vec<(u32, PendingScroll)>,
419    /// What its lists asked of it in this commit, sent at its end.
420    asked: Option<parent_viewport::Asked>,
421    /// The sticky cells it was last sent: its lists' (its own too, when it
422    /// is a list), its sticky views' and its built-in bar's.
423    page_sticky: Vec<list::StickyRange>,
424    /// The ranges of the `position: sticky` views in it.
425    view_sticky: Vec<list::StickyRange>,
426    /// Views in its content are culled (`cull.rs`): it is in
427    /// [`Core::culling`].
428    culls: bool,
429}
430
431impl Default for ScrollState {
432    fn default() -> Self {
433        Self {
434            horizontal: false,
435            // React Native shows scroll indicators by default.
436            scrollbar: crate::ScrollbarSetting::Shown,
437            bar: None,
438            refreshing: false,
439            scroll_value: None,
440            pull_value: None,
441            keyboard_dismiss: KeyboardDismissMode::None,
442            content: None,
443            content_item: None,
444            culled_content: None,
445            behavior: ScrollBehavior::default(),
446            event_throttle_ms: 0.0,
447            zoom: 1.0,
448            offset: (0.0, 0.0),
449            step: (0.0, 0.0),
450            issued: 0,
451            target: None,
452            dependents: Vec::new(),
453            pending: Vec::new(),
454            asked: None,
455            page_sticky: Vec::new(),
456            view_sticky: Vec::new(),
457            culls: false,
458        }
459    }
460}
461
462#[derive(Debug, Default)]
463struct InputState {
464    value: String,
465    /// JS set `value` (or `defaultValue`) at least once.
466    value_set: bool,
467    /// Edits reported by the platform.
468    count: u32,
469    /// What the input shows while an input method composes in it: its
470    /// value with the composition at the caret, as the platform reports
471    /// it ([`Core::input_composing`]). Measured in place of the value, so
472    /// a composition that wraps a line grows the input as the text it
473    /// commits will; the value and `onChangeText` stay as they are.
474    composing: Option<String>,
475    /// Everything but the text style, which comes from the node's style.
476    config: InputConfig,
477    /// Last content box sent to the platform.
478    content: Option<Bounds<Points>>,
479    /// Last size `onContentSizeChange` reported.
480    content_size: Option<Size<Points>>,
481    /// The input is measured with its placeholder (its value is empty).
482    placeholder_measured: bool,
483    /// The size of an empty line in the style of the measured placeholder,
484    /// by the placeholder text's `layout_hash`: what `onContentSizeChange`
485    /// reports for an empty input.
486    empty_line: Option<(u64, Size<Points>)>,
487    /// `scrollbar`: a multiline input's bar.
488    scrollbar: crate::ScrollbarSetting,
489    /// Its built-in bar ([`Core::sync_scrollbars`]), beside it.
490    bar: Option<Bar>,
491    /// A scroll watch follows it (a bar of the app's own placed beside it,
492    /// `watch_scroll`): its platform reports its scrolling as for a
493    /// built-in bar ([`Core::sync_watched_inputs`]).
494    watched: bool,
495    /// How far the platform scrolled its text, while it has a built-in
496    /// bar or a watch ([`Core::set_input_scroll`]).
497    scroll: Option<InputScroll>,
498}
499
500/// A multiline input's scrolling, as its platform reports it.
501#[derive(Debug, Clone, Copy, PartialEq)]
502struct InputScroll {
503    offset: Point<Points>,
504    content: Size<Points>,
505    viewport: Size<Points>,
506}
507
508/// A shader node's props and the layer they make.
509#[derive(Debug, Default)]
510struct ShaderNode {
511    /// `source`, as JS set it.
512    source: Option<Arc<str>>,
513    /// The program: `source` compiled, or what Rust set.
514    shader: Option<crate::shader::Shader>,
515    uniforms: crate::shader::ShaderUniforms,
516    paused: bool,
517    /// What the layer draws: the element it is (`Shader`, `ShaderEffect`, ...).
518    role: crate::shader::ShaderRole,
519    /// `progress` (effects).
520    progress: crate::shader::ShaderProgress,
521    /// `maxSampleOffset` (effects and transitions).
522    overflow: Points,
523    /// `value` (transitions), and the one the transition last showed
524    /// (`None` before the first: it starts no transition).
525    value: Option<crate::shader::TransitionKey>,
526    shown: Option<crate::shader::TransitionKey>,
527    /// `duration` in milliseconds (transitions).
528    duration: Option<f32>,
529    /// `fallback` (transitions).
530    fallback: crate::TransitionFallback,
531    /// What the platform shows (`None`: nothing, as a view).
532    layer: Option<Arc<crate::shader::ShaderLayer>>,
533}
534
535/// How long a shader transition runs by default.
536const DEFAULT_TRANSITION_MS: f32 = 300.0;
537
538/// How long a page's or a dialog's `transitionShader` runs by default.
539const DEFAULT_NAV_SHADER_MS: f32 = 350.0;
540
541/// The role of a shader element's layer.
542fn shader_role(tag: Tag) -> Option<crate::shader::ShaderRole> {
543    use crate::shader::ShaderRole as R;
544    Some(match tag {
545        Tag::Shader => R::Fill,
546        Tag::ShaderEffect => R::Effect,
547        Tag::ShaderTransition => R::Transition,
548        Tag::ScreenEffect => R::Screen,
549        Tag::ScreenTransition => R::ScreenTransition,
550        _ => return None,
551    })
552}
553
554#[derive(Debug, Default)]
555struct ImageState {
556    source: Option<ImageSource>,
557    options: crate::mount::ImageOptions,
558    /// An `svg()` the platform draws as an image: its mount item carries the
559    /// text color ([`crate::mount::ImageOptions::current_color`]).
560    svg_current_color: bool,
561}
562
563/// A style most nodes leave at its default: stored only once set to
564/// something else, read through the shared default otherwise.
565#[derive(Default)]
566struct Sparse<T: 'static>(Option<Rc<T>>);
567
568trait SharedDefault: Sized + PartialEq + 'static {
569    fn shared_default() -> &'static Self;
570}
571
572impl SharedDefault for ViewStyle {
573    fn shared_default() -> &'static Self {
574        &ViewStyle::DEFAULT
575    }
576}
577
578impl SharedDefault for TextStyle {
579    fn shared_default() -> &'static Self {
580        &TextStyle::DEFAULT
581    }
582}
583
584impl<T: SharedDefault + Clone> Sparse<T> {
585    fn set(&mut self, value: T) {
586        // Mutate in place when uniquely owned; clear to `None` or replace
587        // with a new `Rc` when shared with a cached resolved style.
588        if let Some(rc) = &mut self.0 {
589            if let Some(inner) = Rc::get_mut(rc) {
590                *inner = value;
591                return;
592            }
593            if value == *T::shared_default() {
594                self.0 = None;
595                return;
596            }
597            if **rc == value {
598                return;
599            }
600            *rc = Rc::new(value);
601        } else if value != *T::shared_default() {
602            self.0 = Some(Rc::new(value));
603        }
604    }
605
606    fn is_default(&self) -> bool {
607        self.0.as_ref().is_none_or(|v| **v == *T::shared_default())
608    }
609}
610
611impl<T: SharedDefault> std::ops::Deref for Sparse<T> {
612    type Target = T;
613    fn deref(&self) -> &T {
614        match &self.0 {
615            Some(rc) => rc,
616            None => T::shared_default(),
617        }
618    }
619}
620
621impl<T: SharedDefault + std::fmt::Debug> std::fmt::Debug for Sparse<T> {
622    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
623        (**self).fmt(f)
624    }
625}
626
627impl<T: SharedDefault> PartialEq<T> for Sparse<T> {
628    fn eq(&self, other: &T) -> bool {
629        **self == *other
630    }
631}
632
633/// A node's flags about its children's positions among them (`first:`,
634/// `odd:`…), kept in a byte: the core keeps one record per node.
635#[derive(Debug, Clone, Copy, PartialEq, Eq)]
636struct Positional(u8);
637
638impl Positional {
639    const NONE: Self = Self(0);
640    /// A child's classes read their position among siblings.
641    const CHILDREN: Self = Self(1);
642    /// Its children moved, and it waits in `Core::position_parents` for
643    /// their positions to be looked at (`classes.rs` `flush_positions`).
644    const QUEUED: Self = Self(2);
645    /// Its children take its own position among its siblings
646    /// (`Prop::PassPosition`), which `position_used` keeps while known.
647    const PASS: Self = Self(4);
648
649    fn has(self, flag: Self) -> bool {
650        self.0 & flag.0 != 0
651    }
652
653    fn remove(&mut self, flag: Self) {
654        self.0 &= !flag.0;
655    }
656}
657
658impl std::ops::BitOrAssign for Positional {
659    fn bitor_assign(&mut self, flag: Self) {
660        self.0 |= flag.0;
661    }
662}
663
664struct Node {
665    id: NodeId,
666    kind: Kind,
667    /// Inside a text block: a nested `<text>` span or a raw text run.
668    inline: bool,
669    parent: Key,
670    children: Vec<Key>,
671    /// How many levels of views are under it, at most: what an insert
672    /// under it raised it to, and what leaves it does not lower
673    /// ([`Core::count_heights`] counts them when that matters). At least
674    /// one more than each child's.
675    height: u32,
676    /// Layout node. Present exactly for nodes that render a native view.
677    /// Raw text and spans have none.
678    layout: Option<LayoutId>,
679    /// The style JS set, for kinds whose taffy style is derived from it
680    /// and views made overlays by `position: fixed`; for a span, which has
681    /// no layout node, what a layout node takes when it is a block again.
682    base_layout: Option<Box<taffy::Style>>,
683    view_style: Sparse<ViewStyle>,
684    text_style: Sparse<TextStyle>,
685    /// SVG's paint properties as written on the node (inherited by the
686    /// canvases inside it); `None` while it sets none.
687    paint: Option<Rc<PaintStyle>>,
688    animated: Vec<(AnimationProp, crate::animation::NodeId)>,
689    /// What a canvas draws.
690    drawing: Option<Arc<crate::canvas::Drawing>>,
691    /// A shader's program, uniforms and layer.
692    shader: Option<Box<ShaderNode>>,
693    /// The `style` prop as written, applied over the class styles.
694    inline_style: StylePatch,
695    /// `class` / `classList` as set.
696    class_names: Option<Box<classes::ClassNames>>,
697    /// Their parsed form.
698    classes: Option<std::rc::Rc<ClassList>>,
699    /// Node props the classes set.
700    class_props: Option<Rc<ClassProps>>,
701    /// Interaction states (`tailwind::state` bits).
702    states: u16,
703    /// States the platform reports for the view.
704    tracked: u16,
705    /// States it shows as a part of a control (`Prop::ProjectedStates`):
706    /// its classes read them with its own, nothing else does.
707    projected: u16,
708    /// `HOVERED` while a component's hit layer passes a pointer on to it
709    /// (`ElementRef::hover_at`): its classes and the `group-hover:`
710    /// classes inside it read it with its own states.
711    passed_hover: bool,
712    /// In a terminal, its fill as it rests, while an interaction state
713    /// (hover, press, focus) styles another: the terminal's layout reads
714    /// this one, so a hover's fill never moves what is around it.
715    resting_fill: Option<Color>,
716    /// The `data-*` attributes it shows as a part of a component
717    /// (`Prop::ProjectedData`), sorted: its `data-*:` classes read them,
718    /// and the `group-data-*:` classes inside it.
719    data: Box<[&'static str]>,
720    /// What only some nodes have: state styles, the styles of a page's
721    /// header or a list's content ([`classes::NodeParts`]).
722    parts: Option<Box<classes::NodeParts>>,
723    /// What its children's positions among them are to it
724    /// ([`Positional`]).
725    positional: Positional,
726    /// Styled with the margin its parent's `space-*` gives it.
727    spaced: bool,
728    /// The text color it inherits (`None`: React Native's black), CSS's
729    /// `currentColor` unless it sets its own.
730    inherited_color: Option<Color>,
731    /// CSS's `perspective` its style gives its children.
732    child_perspective: Option<Points>,
733    /// The `ch` its classes were resolved with (`max-w-prose`).
734    ch: f32,
735    /// Its classes contain a font-relative length.
736    reads_ch: bool,
737    /// The inherited text color its classes were resolved with
738    /// (`currentColor`), and whether it waits in `Core::color_changed`.
739    color_used: Option<Color>,
740    color_queued: bool,
741    /// The [`crate::tailwind::position`] bits its classes were resolved
742    /// with (`first:`, `odd:`…); `0` while unplaced or not positional.
743    position_used: u8,
744    /// Its style says `position: fixed`.
745    wants_fixed: bool,
746    /// A view made an overlay by `position: fixed` (`overlay.rs` `fix_view`).
747    fixed_view: bool,
748    /// The built-in bar of the scroll view it is in (`scrollbars.rs`): laid
749    /// out on its own over the viewport, not one of the view's children
750    /// for their classes.
751    decoration: bool,
752    /// In a terminal, the sides its layout gives a border Cell (bits: top,
753    /// right, bottom, left): the others are mounted without a border, so
754    /// the platform draws one exactly where the layout reserved it. `None`
755    /// off a terminal: the border as styled.
756    cell_border: Option<u8>,
757    /// Its focus ring was last mounted inside its border box, as an
758    /// ancestor would clip it outside (`focus_ring.rs`).
759    ring_inside: bool,
760    /// In a terminal, its layout laid it out as its accessibility label in
761    /// place of its content (`terminal_layout`'s icon controls): mounted as
762    /// [`ViewStyle::shows_label`], so the platform draws the label exactly
763    /// where the layout gave it a row ([`ViewStyle::label_arrow_only`]
764    /// when it is a popup trigger's arrow alone).
765    cell_label: terminal_layout::Labelled,
766    /// The multiline input a built-in bar is beside, at its frame and just
767    /// above it (a bar of a scroll view draws above all of its children).
768    beside: Key,
769    /// What its view takes from the `pointer-events-*` classes around it
770    /// (`classes.rs` `update_pointer_events`); an explicit prop wins.
771    class_pointer: crate::props::PointerEvents,
772    /// A `pointer-events-auto` is inside it, under a `pointer-events-none`
773    /// (scratch of `update_pointer_events`).
774    pointer_auto_inside: bool,
775    /// `position: sticky`: its insets, where it sticks in the viewport of
776    /// the scroll view around it ([`Core::update_sticky_views`]).
777    sticky: Option<Box<taffy::Rect<taffy::LengthPercentageAuto>>>,
778    /// The element its frame follows (`View::follow`, `follow.rs`).
779    follow: Option<Box<follow::Following>>,
780    /// `objectFit` (and the `object-*` classes): how its image or video
781    /// fits its box.
782    object_fit: Option<ResizeMode>,
783    /// The inset padding and margin components set: added to the style's.
784    insets: Option<Box<[EdgeInsets; 2]>>,
785    /// Its padding's and margin's `env()` terms and the insets they came
786    /// to when its style was last applied ([`Core::sync_env`]).
787    env: Option<Box<(crate::style::EnvEdges, [EdgeInsets; 2])>>,
788    events: EventMask,
789    /// Keyboard ancestry for a portaled view: its logical parent, when the
790    /// native parent it is inserted into differs (`sync_key_parents`).
791    key_parent: Option<NodeId>,
792    /// `zIndex`: native views are ordered by it (stable) among siblings.
793    z_index: i32,
794    /// `verticalAlign`: where it sits in its line as an attachment.
795    vertical_align: crate::style::VerticalAlign,
796    /// `copyText`: what a copy of its text gives in its place as an
797    /// attachment (or as the content of a render placed there).
798    copy_text: Option<Arc<str>>,
799    /// It stands clear of the software keyboard: `env(keyboard-inset-height)`
800    /// reads 0 in it and in its subtree (`Prop::ClearsKeyboard`).
801    clears_keyboard: bool,
802    /// Laid out right to left (the resolved `direction`).
803    rtl: bool,
804    /// `direction`: `None` inherits.
805    direction: Option<bool>,
806    /// Start / end properties, if any (restyled on direction flip).
807    has_logical: bool,
808    /// Touch, accessibility and test properties; most views have none.
809    props: Option<Box<ViewProps>>,
810    /// Raw text content.
811    text: String,
812    /// Paragraph settings of a text block or input.
813    paragraph: Paragraph,
814    image: Option<Box<ImageState>>,
815    scroll: Option<Box<ScrollState>>,
816    list: Option<Box<ListState>>,
817    input: Option<Box<InputState>>,
818    /// Screens, modals and header items.
819    root: Option<Box<RootState>>,
820    /// Switches, sliders, activity indicators, web views and videos.
821    control: Option<Box<NativeProps>>,
822    /// A registered native component (`<native>`).
823    component: Option<Box<ComponentState>>,
824    /// Recycling slot (or role) of a list cell.
825    slot: Option<CellSlot>,
826    /// Animated values driven by gestures on the view.
827    gestures: GestureValues,
828    /// Keeps pan listeners and values while their native gesture is disabled.
829    pan_enabled: bool,
830    /// The native view exists.
831    created: bool,
832    /// Held back in a scroll view's content, out of its window: no native
833    /// view, its frame computed all the same (`cull.rs`).
834    culled: bool,
835    /// The stand-in of an `<Each>` row not rendered yet
836    /// ([`Op::Placeholder`]); `row_asked`: JS was asked to render it.
837    placeholder: bool,
838    row_asked: bool,
839    /// Last frame sent to the platform.
840    frame: Bounds<Points>,
841    /// The area descendants cover outside the bounds, as last mounted
842    /// (`MountItem::Overflow`).
843    overflow: Option<Bounds<Points>>,
844    dirty: u32,
845    queued: bool,
846    /// In `Core::pending_text`.
847    text_queued: bool,
848    /// A list cell whose subtree was laid out again this commit.
849    relaid: bool,
850    /// Where its layout root had the origin of the view around it (its
851    /// containing block), unrounded, and the ratio frames were rounded to
852    /// ([`Core::frame_ratio`]), when its frame and
853    /// its subtree's were last emitted: while nothing in the subtree is laid
854    /// out anew, a move of that origin by whole device pixels leaves every
855    /// frame in it as it was ([`Core::emit_frames_in`]). `None` until
856    /// emitted, or once they must be emitted again.
857    emitted: Option<(Origin, taffy::Size<f32>)>,
858    /// A view in its subtree is placed in a containing block above it (a
859    /// fixed one, or an absolute one in a static parent), so a move of the
860    /// subtree can move it in its parent.
861    escapes: bool,
862    /// A list cell without an item, until the list places it again: it
863    /// still shows its last row, so it is hidden from sight, touches and
864    /// assistive technology ([`Core::set_spare`]).
865    spare: bool,
866    /// An attachment of a text inside a hidden span (`visibility:
867    /// "hidden"`): hidden with the span's characters, from sight, touches
868    /// and assistive technology ([`Core::hide_attachments`]).
869    hidden_in_text: bool,
870    /// A list cell the render window left behind as the list scrolled: it
871    /// shows a row out of the window where that row was laid out last, so
872    /// it is left in sight (it is out of it, and soon reused) but hidden
873    /// from assistive technology, which reads the window's rows in their
874    /// order ([`Core::set_left_behind`]).
875    left_behind: bool,
876    /// `android={{ elevation }}`.
877    elevation: Points,
878    /// `ios={{ backdropMaterial }}`.
879    backdrop_material: crate::BackdropMaterial,
880    /// `macos={{ backdrop }}`.
881    macos_backdrop: Option<crate::MacOsBackdrop>,
882    /// `windows={{ backdrop }}`.
883    windows_backdrop: Option<crate::WindowsBackdrop>,
884    /// A text block: its attachments (inline views and images, in text
885    /// order) whose native views are inside its own.
886    attached: Vec<NodeId>,
887    /// What the overlays have it listen to ([`overlay::watch`]): touches
888    /// for an overlay's `onPressOutside`, the pointer for a hint's.
889    overlay_watched: u8,
890    /// Whether a child of it was ever stacked apart (`zIndex`, sticky, a
891    /// bar): its native children are placed by rank, not just in order.
892    ranked_children: bool,
893}
894
895impl Node {
896    fn is_overlay(&self) -> bool {
897        self.kind == Kind::Overlay || self.fixed_view
898    }
899
900    fn is_layout_root(&self) -> bool {
901        self.kind.is_root() || self.fixed_view || self.decoration
902    }
903
904    /// Its `scrollbar`, for a view that may show a built-in bar.
905    fn scrollbar_setting(&self) -> Option<&crate::ScrollbarSetting> {
906        match (&self.scroll, &self.input) {
907            (Some(scroll), _) => Some(&scroll.scrollbar),
908            (None, Some(input)) => Some(&input.scrollbar),
909            _ => None,
910        }
911    }
912
913    /// Its built-in bar.
914    fn bar(&self) -> Option<&Bar> {
915        match (&self.scroll, &self.input) {
916            (Some(scroll), _) => scroll.bar.as_ref(),
917            (None, Some(input)) => input.bar.as_ref(),
918            _ => None,
919        }
920    }
921
922    /// Where its built-in bar is kept, for a view that may show one.
923    fn bar_slot(&mut self) -> Option<&mut Option<Bar>> {
924        match (&mut self.scroll, &mut self.input) {
925            (Some(scroll), _) => Some(&mut scroll.bar),
926            (None, Some(input)) => Some(&mut input.bar),
927            _ => None,
928        }
929    }
930
931    /// The listeners as platforms take them: a `disabled` view takes no
932    /// presses (React Native's `Pressable` / touchables), so it shows no
933    /// press feedback either, and opens no context menu: a secondary click
934    /// on it goes on to the nearest enabled listener around it.
935    fn mounted_events(&self) -> EventMask {
936        let mut events = self.events;
937        if !self.pan_enabled {
938            events.set(EventKind::PanStart, false);
939            events.set(EventKind::PanEnd, false);
940        }
941        if self.overlay_watched != 0 {
942            events.set(EventKind::Touch, true);
943        }
944        if self.states & crate::tailwind::state::DISABLED != 0 {
945            for e in DISABLED_OFF {
946                events.set(e, false);
947            }
948        }
949        // A disabled view still shows its hint, as the desktops' do.
950        if self.overlay_watched & overlay::watch::HINT != 0 {
951            events.set(EventKind::MouseEnter, true);
952            events.set(EventKind::MouseLeave, true);
953        }
954        events
955    }
956
957    /// Where its native view goes among its siblings': by `zIndex`, then a
958    /// sticky view above the others (as above a page's in-flow boxes),
959    /// then in order; a built-in scroll bar above all of them (a list's
960    /// sticky headers included), as it draws over the viewport.
961    fn stack_rank(&self) -> (i32, bool) {
962        if self.decoration && self.beside == NO_KEY {
963            return (i32::MAX, true);
964        }
965        (self.z_index, self.sticky.is_some())
966    }
967
968    /// The view style as platforms take it: translations by a fraction of
969    /// the size resolved with the current frame, a spare list cell hidden.
970    fn mounted_view_style(&self) -> Box<ViewStyle> {
971        let mut style = Box::new(self.view_style.clone());
972        style.elevation = self.elevation;
973        style.backdrop_material = self.backdrop_material;
974        style.macos_backdrop = self.macos_backdrop;
975        style.windows_backdrop = self.windows_backdrop;
976        // A list in its parent's viewport is a plain view clipping its
977        // cells (a scroll view clips its content).
978        if self.list.as_ref().is_some_and(|l| l.parent) {
979            style.overflow_hidden = true;
980        }
981        if self.spare || self.hidden_in_text {
982            style.hidden = true;
983        }
984        style.shows_label = self.cell_label != terminal_layout::Labelled::No;
985        style.label_arrow_only = self.cell_label == terminal_layout::Labelled::Arrow;
986        if let Some(sides) = self.cell_border {
987            let w = &mut style.borders.widths;
988            for (bit, side) in [&mut w.top, &mut w.right, &mut w.bottom, &mut w.left]
989                .into_iter()
990                .enumerate()
991            {
992                if sides & (1 << bit) == 0 {
993                    *side = Points::ZERO;
994                }
995            }
996        }
997        // A canvas whose drawing fills with its background shows it there
998        // only (`Painter::fill_background_from_view`).
999        if self.kind == Kind::Canvas && self.drawing.as_ref().is_some_and(|d| d.paints_background())
1000        {
1001            style.background_color = crate::style::Color::TRANSPARENT;
1002            style.clear_background_images();
1003        }
1004        if style.transform.has_fractions() {
1005            let size = if self.frame.size.width.is_nan() {
1006                Size::default()
1007            } else {
1008                self.frame.size
1009            };
1010            style.transform = style.transform.resolve_fractions(size);
1011        }
1012        style
1013    }
1014
1015    /// The touch, accessibility and test properties as platforms take
1016    /// them: the `pointer-events-*` classes around it apply unless a prop
1017    /// says otherwise, a `disabled` view is so for screen readers too (as a
1018    /// Rust component's `disabled` and React Native's `Pressable`), and
1019    /// screen readers skip a spare list cell.
1020    fn mounted_props(&self) -> Box<ViewProps> {
1021        let mut props = self.props.clone().unwrap_or_default();
1022        props.overlay_anchor = self
1023            .root
1024            .as_ref()
1025            .and_then(|root| root.overlay.as_ref())
1026            .and_then(|overlay| overlay.native_anchor);
1027        props.tab_after = self
1028            .root
1029            .as_ref()
1030            .and_then(|root| root.overlay.as_ref())
1031            .and_then(|overlay| overlay.tab_after);
1032        props.key_parent = self.key_parent;
1033        if props.pointer_events == crate::props::PointerEvents::Auto {
1034            props.pointer_events = self.class_pointer;
1035        }
1036        if self.states & crate::tailwind::state::DISABLED != 0 {
1037            props.accessibility.state.disabled = true;
1038        }
1039        if self.spare || self.hidden_in_text || self.left_behind {
1040            props.accessibility.hidden = true;
1041        }
1042        if let Some(list) = self.list.as_ref().filter(|l| l.parent) {
1043            props.screen_order = Some(if list.horizontal {
1044                crate::geometry::Axis::Horizontal
1045            } else {
1046                crate::geometry::Axis::Vertical
1047            });
1048        }
1049        props
1050    }
1051
1052    fn new(id: NodeId, kind: Kind) -> Self {
1053        Self {
1054            id,
1055            kind,
1056            inline: false,
1057            parent: NO_KEY,
1058            children: Vec::new(),
1059            height: 0,
1060            layout: None,
1061            base_layout: None,
1062            view_style: Sparse::default(),
1063            text_style: Sparse::default(),
1064            paint: None,
1065            animated: Vec::new(),
1066            drawing: None,
1067            shader: matches!(kind, Kind::Shader).then(Box::default),
1068            inline_style: StylePatch::default(),
1069            class_names: None,
1070            classes: None,
1071            class_props: None,
1072            states: 0,
1073            // An input reports its focus from the start (`update_tracking`).
1074            tracked: if matches!(kind, Kind::Input) {
1075                crate::tailwind::state::FOCUSED
1076            } else {
1077                0
1078            },
1079            projected: 0,
1080            passed_hover: false,
1081            resting_fill: None,
1082            data: Box::default(),
1083            parts: None,
1084            positional: Positional::NONE,
1085            spaced: false,
1086            inherited_color: None,
1087            child_perspective: None,
1088            ch: 0.0,
1089            reads_ch: false,
1090            color_used: None,
1091            color_queued: false,
1092            position_used: 0,
1093            wants_fixed: false,
1094            fixed_view: false,
1095            decoration: false,
1096            cell_border: None,
1097            ring_inside: false,
1098            cell_label: terminal_layout::Labelled::No,
1099            beside: NO_KEY,
1100            class_pointer: crate::props::PointerEvents::Auto,
1101            pointer_auto_inside: false,
1102            sticky: None,
1103            follow: None,
1104            object_fit: None,
1105            insets: None,
1106            env: None,
1107            events: EventMask::default(),
1108            key_parent: None,
1109            z_index: 0,
1110            vertical_align: crate::style::VerticalAlign::Baseline,
1111            copy_text: None,
1112            clears_keyboard: false,
1113            rtl: false,
1114            direction: None,
1115            has_logical: false,
1116            props: None,
1117            text: String::new(),
1118            paragraph: Paragraph::default(),
1119            image: matches!(kind, Kind::Image).then(Box::default),
1120            scroll: matches!(kind, Kind::Scroll | Kind::List).then(Box::default),
1121            list: matches!(kind, Kind::List).then(|| Box::new(ListState::new())),
1122            input: matches!(kind, Kind::Input).then(Box::default),
1123            root: kind.is_root().then(Box::default),
1124            control: match kind {
1125                Kind::WebView => Some(NativeProps::WebView(Box::default())),
1126                Kind::Video => Some(NativeProps::Video(Box::<VideoProps>::default())),
1127                _ => None,
1128            }
1129            .map(Box::new),
1130            component: matches!(kind, Kind::Native | Kind::GpuView).then(Box::default),
1131            slot: None,
1132            gestures: GestureValues::default(),
1133            pan_enabled: true,
1134            created: false,
1135            culled: false,
1136            placeholder: false,
1137            row_asked: false,
1138            frame: Bounds::UNSET,
1139            overflow: None,
1140            attached: Vec::new(),
1141            overlay_watched: 0,
1142            ranked_children: false,
1143            elevation: Points::ZERO,
1144            backdrop_material: crate::BackdropMaterial::default(),
1145            macos_backdrop: None,
1146            windows_backdrop: None,
1147            dirty: 0,
1148            queued: false,
1149            text_queued: false,
1150            relaid: false,
1151            emitted: None,
1152            escapes: false,
1153            spare: false,
1154            hidden_in_text: false,
1155            left_behind: false,
1156        }
1157    }
1158}
1159
1160/// Taffy context of a text block.
1161struct TextContext<P> {
1162    text: Arc<AttributedText>,
1163    alignments: crate::AttachmentAlignments,
1164    /// What the block asks of its engine beyond its characters
1165    /// ([`crate::TextOptions`]: `textIndent`).
1166    options: crate::TextOptions,
1167    /// The UTF-16 offsets of the attachments of [`Self::text`] that are
1168    /// the horizontal padding of a span ([`span_padding`]), not views.
1169    spacers: Vec<u32>,
1170    /// `text.layout_hash()`, computed once per content.
1171    layout_hash: u64,
1172    /// Platform typesetting state, created on first use.
1173    prepared: Option<P>,
1174    /// Natural width of the widest UAX #14 unbreakable segment.
1175    min_content: Option<Points>,
1176    /// An input's [`FIELD_SAMPLE`] in its style: what its width comes from
1177    /// when nothing else gives it one.
1178    field: Option<Box<TextContext<P>>>,
1179    /// Last measurement: `(max_width, size)`.
1180    cache: Option<(Option<f32>, Size<Points>)>,
1181    /// Last first baseline asked for: `(width, baseline)`
1182    /// ([`TextEngine::first_baseline`]). Cleared with [`Self::cache`].
1183    baseline: Option<(f32, Option<Points>)>,
1184    /// The widths known to break its lines as the last measurement did
1185    /// ([`TextEngine::breaks_lines_greedily`]).
1186    same_lines: Option<SameLines>,
1187    /// Measuring ahead found a line taking another word: a long text finds
1188    /// one nearly every time, and would be typeset twice per width.
1189    no_ahead: bool,
1190    /// The commit of a resize that last found it near the screen
1191    /// ([`Core::mark_near_screen`]).
1192    near_screen: u32,
1193    /// Its size or layout waits for the resize to end.
1194    held: bool,
1195    /// In a scroll view's content far from its viewport, with no view yet
1196    /// (`cull.rs`): measured by an estimate, not typeset.
1197    deferred: bool,
1198    /// Its size in the layout is that estimate: measured for real once it
1199    /// is made.
1200    estimated: bool,
1201    /// Last final layout sent to the platform and the content box it was
1202    /// made for (where in the view the text goes).
1203    laid_out: Option<LaidText>,
1204    /// New test metadata must be mounted even when the glyphs are unchanged.
1205    metadata_changed: bool,
1206    /// `text-pretty`: a short last line takes words from the lines above
1207    /// ([`pretty_width`]), with the last width asked for and what it gave
1208    /// (`NAN` for none). Boxed: few texts say it.
1209    pretty: Option<Box<(f32, Points)>>,
1210}
1211
1212/// A text measures `size` at every maximum width from `narrowest` to
1213/// `widest`: a width that holds its widest line and is not above the one
1214/// measured breaks the lines at the same places.
1215#[derive(Clone, Copy)]
1216struct SameLines {
1217    narrowest: f32,
1218    widest: f32,
1219    size: Size<Points>,
1220}
1221
1222/// How far past a growing width a text is measured, so that the next widths
1223/// of a window's resize need no typesetting ([`measure_text`]).
1224const SAME_LINES_AHEAD: f32 = 8.0;
1225
1226/// The final text can have fitted font sizes, so retain it with its layout.
1227struct LaidText {
1228    content: Bounds<Points>,
1229    layout: TextLayout,
1230    text: Arc<AttributedText>,
1231}
1232
1233impl<P> TextContext<P> {
1234    fn new(text: Arc<AttributedText>) -> Self {
1235        Self {
1236            layout_hash: text.layout_hash(),
1237            alignments: Default::default(),
1238            options: Default::default(),
1239            spacers: Vec::new(),
1240            text,
1241            prepared: None,
1242            same_lines: None,
1243            no_ahead: false,
1244            near_screen: 0,
1245            held: false,
1246            deferred: false,
1247            estimated: false,
1248            min_content: None,
1249            field: None,
1250            cache: None,
1251            baseline: None,
1252            laid_out: None,
1253            metadata_changed: false,
1254            pretty: None,
1255        }
1256    }
1257    /// Remount metadata in the same box, keeping any fitted font sizes.
1258    fn remount_metadata(
1259        &mut self,
1260        content: Bounds<Points>,
1261    ) -> Option<(Arc<AttributedText>, TextLayout)> {
1262        if !self.metadata_changed {
1263            return None;
1264        }
1265        let laid = self.laid_out.as_mut().filter(|l| l.content == content)?;
1266        let text =
1267            if laid.text.spans == self.text.spans && laid.text.max_lines == self.text.max_lines {
1268                self.text.clone()
1269            } else {
1270                // A fitted text draws its scaled spans: the new metadata goes
1271                // on them.
1272                let mut text = (*laid.text).clone();
1273                text.set_metadata(&self.text);
1274                Arc::new(text)
1275            };
1276        laid.text = text.clone();
1277        self.metadata_changed = false;
1278        Some((text, laid.layout.clone()))
1279    }
1280}
1281
1282/// What an input is as wide as when nothing gives it a width, whatever it
1283/// holds: as CSS's `<input size="20">`, twenty digits.
1284const FIELD_SAMPLE: &str = "00000000000000000000";
1285
1286/// Measured leaves: text blocks and images with a known natural size.
1287enum LeafContext<P> {
1288    /// Boxed: a text's context is far larger than an image's, and a leaf
1289    /// slot of every node would carry the difference.
1290    Text(Box<TextContext<P>>),
1291    Image(Option<Size<Points>>),
1292    /// A registered native component's own size, once it reported one.
1293    Native(Option<Size<Points>>),
1294}
1295
1296/// A request for the JS runtime to render list items into cells.
1297#[derive(Debug, Clone, PartialEq, Eq)]
1298pub struct ListBind {
1299    /// The list.
1300    pub list: NodeId,
1301    /// `(slot, item index)` pairs.
1302    pub binds: Vec<(u32, u32)>,
1303}
1304
1305/// Takes list `list`'s binds still queued (`Core::list_binds`, a
1306/// component's list's that a commit's last round asked for), as its items
1307/// change: the runtime moves its cells with the items before they could
1308/// run, so they would show items at indices that are no longer theirs. The
1309/// list asks for its cells again ([`ListState::unrequest`]). Returns their
1310/// slots.
1311fn take_queued_binds(binds: &mut Vec<ListBind>, list: NodeId) -> Vec<u32> {
1312    let mut slots = Vec::new();
1313    binds.retain(|b| {
1314        if b.list != list {
1315            return true;
1316        }
1317        slots.extend(b.binds.iter().map(|&(slot, _)| slot));
1318        false
1319    });
1320    slots
1321}
1322
1323/// How deep views nest under the root: an insert that would put a view
1324/// deeper is refused ([`ApplyError::TooDeep`]). Layout, mounting and the
1325/// walks of the tree recurse once per level, on the native stack, which
1326/// neither the node quota nor the interpreter's stack limit bounds: without
1327/// this a chain of views overflows it and aborts the process. Far deeper
1328/// than a UI nests, and shallow enough for the engine thread's 8 MiB stack
1329/// in a debug build.
1330pub const MAX_TREE_DEPTH: usize = 1024;
1331
1332/// An op referenced a node in an impossible way. This is a renderer bug;
1333/// the op is skipped and the tree stays consistent.
1334#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1335pub enum ApplyError {
1336    /// The id is unknown (never created or already released).
1337    UnknownNode(NodeId),
1338    /// The id is already in use.
1339    DuplicateNode(NodeId),
1340    /// The child is not a child of the given parent.
1341    NotAChild(NodeId),
1342    /// The `before` sibling is not a child of the given parent.
1343    BadAnchor(NodeId),
1344    /// The insert would create a cycle.
1345    Cycle(NodeId),
1346    /// Creating the node would exceed the node quota ([`Core::set_max_nodes`]).
1347    TooManyNodes(usize),
1348    /// The insert would nest views deeper than the depth quota
1349    /// ([`MAX_TREE_DEPTH`]).
1350    TooDeep(usize),
1351    /// A new id far beyond the ids in use (ids index a table, so they must
1352    /// stay dense).
1353    IdOutOfRange(NodeId),
1354}
1355
1356impl ApplyError {
1357    /// The app went over a quota or sent what no runtime sends: it should
1358    /// be stopped rather than continue.
1359    pub fn is_fatal(&self) -> bool {
1360        matches!(
1361            self,
1362            ApplyError::TooManyNodes(_) | ApplyError::TooDeep(_) | ApplyError::IdOutOfRange(_)
1363        )
1364    }
1365}
1366
1367/// What [`Core::retag`] knows of the mount items of a round of renders,
1368/// which only grows at its end until the round is over.
1369#[derive(Default)]
1370struct Retags {
1371    /// The views whose `Create` is among the items looked at.
1372    made: rustc_hash::FxHashSet<NodeId>,
1373    /// The items looked at.
1374    seen: usize,
1375    /// The views that took another kind, with the number of items then:
1376    /// their `Create` and `Insert` before that go.
1377    retagged: rustc_hash::FxHashMap<NodeId, usize>,
1378}
1379
1380/// The shadow tree of one surface.
1381///
1382/// Feed it [`Op`]s with [`Core::apply`], then call [`Core::commit`] once per
1383/// JS turn to get the [`MountBatch`] for the platform. Lists may then ask
1384/// the runtime to render more items ([`Core::take_list_binds`]); the engine
1385/// runs those and commits again within the same frame.
1386pub struct Core<M: TextEngine> {
1387    nodes: Slab<Node>,
1388    /// Node id -> key + 1 (0 = none). Ids are dense, so this is a flat vec.
1389    slots: crate::id_table::IdTable<Key>,
1390    /// The extent reached by admitted ids. JS keeps issuing new ids after a page is freed.
1391    admitted_id_extent: usize,
1392    /// Raw text runs kept without a node (#1345): a run not in the tree,
1393    /// or the only child of a text block or span, which shows it. Any
1394    /// other use makes its node ([`Core::materialize_run`]).
1395    runs: rustc_hash::FxHashMap<NodeId, Run>,
1396    /// Text block or span -> the run it holds in [`Core::runs`].
1397    folded: rustc_hash::FxHashMap<Key, NodeId>,
1398    layout: LayoutTree<LeafContext<M::Prepared>>,
1399    text_engine: Rc<M>,
1400    /// The engine for [`crate::text::TextGeometry`] (`None` for an engine
1401    /// that is not `'static`).
1402    geometry_engine: Option<Rc<dyn crate::text::GeometryEngine>>,
1403    /// Final layouts kept for Rust components' `on_text_layout` until
1404    /// their `TextLayout` events are dispatched ([`keep_geometry`]).
1405    geometries: rustc_hash::FxHashMap<NodeId, crate::text::TextGeometry>,
1406    measure_cache: MeasureCache,
1407    /// Counts the commits of resizes ([`Core::mark_near_screen`]).
1408    resizing_commit: u32,
1409    /// The next layout follows a change of the viewport, or the text that
1410    /// waited through a burst of resizes: scroll views keep their place
1411    /// through it (`resize_anchor`).
1412    resize_settling: bool,
1413    /// Text blocks whose final layout must be (re)made after layout.
1414    pending_text: Vec<Key>,
1415    /// Text blocks with attachments (checked for attachments laid out
1416    /// again).
1417    attachment_blocks: Vec<Key>,
1418    /// Live list nodes.
1419    lists: Vec<Key>,
1420    /// The lists in their parent's viewport (`viewport="parent"`), outer
1421    /// ones first ([`Core::resolve_outer`]).
1422    parent_lists: Vec<Key>,
1423    /// Views moved in a tree with such lists: their views are found again.
1424    outer_moved: bool,
1425    /// Such a list changed length: the commit lays the page out again.
1426    extent_changed: bool,
1427    /// Scroll views cull their content ([`Core::set_content_culling`]).
1428    culls_content: bool,
1429    /// The scroll views with culled views in their content (`cull.rs`).
1430    culling: Vec<Key>,
1431    /// One of them scrolled, or culled a view, since they were looked at.
1432    cull_dirty: bool,
1433    /// Culled views were made in this round: their styles go out in
1434    /// another.
1435    cull_made: bool,
1436    /// A list gave the views in a cell their frames in this round, after
1437    /// culling looked at the scroll views among them (`cull.rs`).
1438    cells_framed: bool,
1439    /// The walk of [`Core::sync_culled`], kept for its buffer: each view
1440    /// with where it is in the scroll view's content and how far the
1441    /// transforms around it may move it (`cull.rs`).
1442    cull_scratch: Vec<(Key, f32, f32, f32, f32)>,
1443    /// How far the animation graph's values may go: how far an animated
1444    /// transform may move a view culling looks at
1445    /// (`animation/reach.rs`).
1446    reach: crate::animation::Reach,
1447    /// Views out of sight spread over turns (`pace.rs`).
1448    pace: pace::Pace,
1449    /// Lists' rows under this turn's layout animation (`list_motion.rs`).
1450    list_motion: list_motion::ListMotion,
1451    /// The placeholders of `<Each>` rows ([`Op::Placeholder`]), with their
1452    /// ids (a key may be another node's by now).
1453    placeholders: Vec<(Key, NodeId)>,
1454    /// The placeholders whose rows JS is asked to render next
1455    /// ([`crate::element::JsEvent::Rows`]).
1456    asked_rows: Vec<NodeId>,
1457    /// Placeholders were sized again in this round: laid out again
1458    /// before culling looks at them.
1459    placeholders_resized: bool,
1460    /// The scroll views such lists asked to scroll in this commit.
1461    outer_asked: Vec<Key>,
1462    /// The views whose lists' sticky cells changed in this commit.
1463    sticky_views: Vec<Key>,
1464    /// Views with `position: sticky` ([`Core::update_sticky_views`]).
1465    sticky_nodes: Vec<Key>,
1466    /// The scroll views their ranges were last sent to.
1467    sticky_scrollers: Vec<Key>,
1468    /// What makes the views' bars when the app draws them with the
1469    /// built-in one ([`Core::set_builtin_scrollbars`]).
1470    builtin_scrollbars: Option<(crate::element::ScrollbarSource, crate::element::AnyValue)>,
1471    /// Scroll views and lists whose built-in bar may come or go
1472    /// ([`Core::sync_scrollbars`]).
1473    scrollbars_pending: Vec<Key>,
1474    /// The multiline inputs scroll watches follow, sorted
1475    /// ([`Core::sync_watched_inputs`]).
1476    watched_inputs: Vec<NodeId>,
1477    /// Canvases fitting a view box into their box
1478    /// ([`crate::canvas::ViewPaint::Fit`]) to send once this round's
1479    /// layout gave them their size ([`Core::send_fitted`]).
1480    fitted_pending: Vec<Key>,
1481    /// Scroll views and lists that show a built-in bar.
1482    decorated: Vec<Key>,
1483    /// Sticky views came, went or moved: their ranges are worked out
1484    /// again.
1485    sticky_changed: bool,
1486    /// Views whose frame follows an element's ([`Core::place_followers`]).
1487    followers: Vec<Key>,
1488    /// Views naming other elements for assistive technologies
1489    /// ([`Core::sync_relations`]).
1490    relators: Vec<relations::Relator>,
1491    /// What they follow, or frames around them, changed since they were
1492    /// placed.
1493    follow_changed: bool,
1494    /// The warning about `bottom` / `right` sticky insets was logged.
1495    sticky_warned: bool,
1496    /// The warning about animated insets of views that are not sticky, or
1497    /// on the axis their scroll view does not scroll, was logged.
1498    inset_warned: bool,
1499    /// Compiled shaders by the hash of their source, with their errors
1500    /// (an app setting the same source again compiles it once).
1501    shaders: rustc_hash::FxHashMap<u64, Result<crate::shader::Shader, crate::shader::ShaderError>>,
1502    /// Web views whose URL `webview.hosts` does not grant, set while the
1503    /// app may add an origin at run time (`webview.runtimeOrigin`): their
1504    /// `allowOrigin` may come later in the same render, so they are
1505    /// checked when their props go out ([`Self::settle_web_urls`]).
1506    web_unchecked: rustc_hash::FxHashSet<(Key, NodeId)>,
1507    /// Shader transitions this commit starts ([`MountItem::ShaderTransition`]),
1508    /// put first in its batch.
1509    transition_starts: Vec<MountItem>,
1510    /// The shader views whose layers read pictures (`sample_content`, ...).
1511    pictured: rustc_hash::FxHashSet<NodeId>,
1512    /// The parents views left this commit, while any shader reads
1513    /// pictures: what is above them changed though their mount items no
1514    /// longer lead there ([`Core::mark_shader_inputs`]).
1515    unlinked_from: Vec<NodeId>,
1516    /// Live screens, modals and header items.
1517    roots: Vec<Key>,
1518    /// Attached input accessories by `nativeID`.
1519    accessories: rustc_hash::FxHashMap<Box<str>, NodeId>,
1520    /// Height of the native header bar of screens: normal and large title.
1521    header_heights: (Points, Points),
1522    /// Natural sizes of the platform's controls.
1523    /// The surface's safe-area insets (stacks at the top extend their
1524    /// headers under the status bar).
1525    safe_area: EdgeInsets,
1526    /// Where the root view's anchored overlays may go, in its coordinates,
1527    /// when the platform shows them beyond the root view
1528    /// ([`Core::set_overlay_area`]).
1529    overlay_bounds: Option<crate::geometry::Bounds<Points>>,
1530    /// The distance overlays without a `margin` of their own keep from the
1531    /// edges of their room ([`Core::set_snap_to_window_margin`]).
1532    snap_to_window_margin: Points,
1533    list_binds: Vec<ListBind>,
1534    /// The lists keeping items rendered ([`Core::sync_kept`]).
1535    kept_lists: Vec<Key>,
1536    /// The nodes of the last [`Core::set_kept`].
1537    selection_kept: Vec<NodeId>,
1538    /// [`Core::sync_kept`]'s buffer, reused.
1539    kept_scratch: Vec<Key>,
1540    /// The runtime's lists with overscan cells waiting to bind
1541    /// ([`Core::take_paced_list_binds`]), in the order they asked.
1542    paced_lists: Vec<NodeId>,
1543    /// [`Core::take_paced_list_binds`]'s buffer, reused.
1544    paced_scratch: Vec<(u32, u32)>,
1545    /// The events for JS, in order (the platform's and the core's events,
1546    /// Rust components' events, calls' results).
1547    events: Vec<crate::element::JsEvent>,
1548    /// Reused buffer of `(item index, cell)` for list updates.
1549    cells_scratch: Vec<(u32, Key)>,
1550    /// The list cells whose content waits for the app's render functions
1551    /// this round (sorted; [`Core::cells_awaiting_renders`]): not measured.
1552    awaiting_renders: Vec<Key>,
1553    root: Key,
1554    viewport: Size<Points>,
1555    mount: Vec<MountItem>,
1556    track_tree_order: bool,
1557    tree_order_changed: bool,
1558    /// The tree changed: the shown overlays' places in the Tab order are
1559    /// found again ([`Core::order_overlays_for_tab`]).
1560    tab_places_stale: bool,
1561    /// A key listener or capture rule changed, or an overlay moved in:
1562    /// the shown overlays' `key_parent` overrides are found again
1563    /// ([`Core::sync_key_parents`]).
1564    key_ancestry_dirty: bool,
1565    /// Mount the states nodes show as parts of a control
1566    /// ([`MountItem::ProjectStates`]).
1567    mount_projected: bool,
1568    /// Batches handed out so far: tells this batch's mount indexes from
1569    /// earlier ones'.
1570    batches: u64,
1571    /// Component roots taking their kind in this round of renders
1572    /// ([`Core::retag`]).
1573    retags: Option<Box<Retags>>,
1574    /// Imperative calls, run after everything else in the batch.
1575    commands: Vec<(NodeId, Command)>,
1576    /// Where the keyboard focus goes back to in this commit, and the popup
1577    /// it comes back from, unless a `focus()` moves it out of that popup
1578    /// ([`crate::element::ElementRef::focus_back`]); with the direction
1579    /// it moves on past it in the Tab order
1580    /// ([`crate::element::ElementRef::focus_past`]).
1581    focus_back: Option<(NodeId, Option<NodeId>, Option<bool>)>,
1582    /// The focus the popups that give it back to these nodes opened
1583    /// with, when a pointer opened them
1584    /// ([`crate::element::ElementRef::focus_back_origin`]): one per
1585    /// trigger, its latest opening.
1586    focus_origins: Vec<(NodeId, Option<(Key, NodeId)>)>,
1587    /// The trigger a popup a pointer opened gave the focus back to, off
1588    /// macOS and iOS, until the focus is reported: the pointer's focus,
1589    /// however the popup closed (`focus_by_pointer`).
1590    pointer_focus_back: Option<NodeId>,
1591    /// Animates the layout changes of the next commit.
1592    layout_animation: Option<LayoutAnimation>,
1593    /// Nodes whose change animates the frames it moves in the next commit,
1594    /// or their own frame alone when true (`layout_scope.rs`).
1595    scoped_layout: Vec<(NodeId, crate::LayoutTransition, bool)>,
1596    /// Nodes that changed size while `scoped_layout` waits.
1597    resized: Vec<Key>,
1598    /// Nodes that lost a child while `scoped_layout` waits.
1599    restructured: Vec<Key>,
1600    /// The nodes whose padding or margin uses `env()` (`Node::env`).
1601    env_styled: rustc_hash::FxHashSet<NodeId>,
1602    /// Scratch of [`Core::sync_env`].
1603    env_scratch: Vec<NodeId>,
1604    /// The keyboard's height changed since the last commit: what that
1605    /// commit moves (an `env()` term, or a style that reads the keyboard's
1606    /// height) moves with the keyboard.
1607    keyboard_moved: bool,
1608    /// The screens and modals with a `statusBar`, in the order they got
1609    /// it: few, so attaching and detaching only flag them for the commit.
1610    status_bar_nodes: Vec<Key>,
1611    /// The tree changed with `status_bar_nodes` in it: the commit checks
1612    /// which are in the tree.
1613    status_bars_moved: bool,
1614    /// The pages with a `supportedOrientations` (their
1615    /// [`crate::ModalConfig::PORTRAIT`] bits), in the order they got it.
1616    orientation_pages: Vec<(Key, u8)>,
1617    /// What [`Command::Orientations`] last said (0: the app's own).
1618    orientations_shown: u8,
1619    /// Nodes whose classes say `pointer-events-none`: without any, moving
1620    /// nodes skips what CSS's inherited `pointer-events` needs.
1621    pointer_none_classes: u32,
1622    /// The tops of the `pointer-events-*` regions that views joined or
1623    /// left, or whose classes changed, since the last round: worked out
1624    /// once each, before the round's mount items
1625    /// ([`Self::flush_pointer_events`]). Worked out on every move, a
1626    /// region's whole subtree was walked for each view inserted in it (an
1627    /// editor's highlighted rows: 1600 spans, 2500 views, 10 ms a commit).
1628    pointer_pending: Vec<Key>,
1629    /// Views whose hit slop changed since the last round: the areas of the
1630    /// views around them are worked out again after the layout
1631    /// ([`Self::update_slop_overflow`]).
1632    slop_moved: Vec<Key>,
1633    /// The view with the keyboard focus, by key and id (keys are reused),
1634    /// as the platform reports it (`classes::focus_reported`).
1635    focus: Option<(Key, NodeId)>,
1636    /// The focus and the views around it, innermost first: the views in
1637    /// `focus-within` (`classes::update_focus_within`).
1638    focus_chain: Vec<(Key, NodeId)>,
1639    /// The chain before, reused.
1640    focus_scratch: Vec<(Key, NodeId)>,
1641    /// The focus was reported or a view of its chain moved since the
1642    /// chain was last worked out: the next commit round does it once,
1643    /// whatever order the reports came in.
1644    focus_moved: bool,
1645    /// A view reported losing the focus and none took it since: the chain
1646    /// waits for the next display frame before it lets go, so a move
1647    /// that comes as a blur then a focus in two messages, with a commit
1648    /// between them, is one change of `focus-within`, not a leave and a
1649    /// new enter.
1650    blur_held: bool,
1651    /// The chain changed since the focus watches last looked
1652    /// (`ElementRef::on_focus_in`).
1653    focus_within_changed: bool,
1654    /// What the user last gave the surface input with, as the platform
1655    /// reports it (`classes::set_input_modality`); `None` before any.
1656    modality: Option<crate::platform::InputModality>,
1657    /// The focus shows (`focus-visible:`), decided when it was reported
1658    /// (`classes::focus_shows`) and again when a key is typed.
1659    focus_visible: bool,
1660    /// The keyboard moved the focus, on a platform whose tooltips follow
1661    /// it (`classes::focus_shows_hints`), decided when it was reported
1662    /// and kept until it moves again, whatever is typed meanwhile: only
1663    /// such a focus shows the hint of the anchor it comes to
1664    /// (`overlay::focus_hints`).
1665    focus_by_keyboard: bool,
1666    /// A pointer moved the focus where it is (a press, a popup a press
1667    /// used giving it back), decided when it was reported and kept until
1668    /// it moves again: the keymap's `Keymap::pointer_focus`.
1669    focus_by_pointer: bool,
1670    /// The keymap the app mounted last, while one of its bindings asks
1671    /// how the focus came ([`crate::keymap::Keymap::takes_over_pointer_focus`]),
1672    /// and the `focus_by_pointer` it was mounted with: mounted again as
1673    /// that changes.
1674    pointer_keymap: Option<(Arc<crate::keymap::Keymap>, bool)>,
1675    /// A shown modal closed; focus reports restore context until the next
1676    /// user action, rather than requesting another hint.
1677    restoring_modal_focus: bool,
1678    /// Modals made in this commit: each gives the keyboard focus to its
1679    /// first control as it opens (`focus_opened_modals`).
1680    modals_opened: Vec<(Key, NodeId)>,
1681    /// The control an opening dialog gave the focus to, until the focus
1682    /// is reported there or the user acts: that focus shows no hint, as
1683    /// a desktop dialog's first control shows no tooltip when it opens,
1684    /// so the first Escape closes the dialog (`classes::focus_reported`).
1685    modal_focus_given: Option<NodeId>,
1686    /// The view in the `FOCUS_VISIBLE` state, by key and id
1687    /// (`classes::update_focus_visible`).
1688    focus_visible_on: Option<(Key, NodeId)>,
1689    /// `focus_visible` changed with the focus staying where it is: the
1690    /// next commit round moves the state.
1691    focus_visible_moved: bool,
1692    /// The parts projected focused (`project_focused`: a tree's or a
1693    /// list's cursor), by key and id: they show `focus-visible:` while the
1694    /// focus does, restyled when it starts or stops showing
1695    /// (`classes::styled_states`).
1696    projected_focus: Vec<(Key, NodeId)>,
1697    /// Short completed presses whose `PRESSED` state is held until a
1698    /// deadline so same-turn tap-to-click gestures still render `:active`.
1699    pressed_impulses: Vec<(Key, NodeId, crate::time::Instant)>,
1700    /// The views a pointer passed on into an element is over
1701    /// (`ElementRef::hover_at`), by element, innermost first.
1702    passed_hovers: rustc_hash::FxHashMap<NodeId, Vec<NodeId>>,
1703    /// Nodes whose `position: fixed` changed: made overlays (or views again)
1704    /// as the commit starts ([`Core::sync_fixed`]).
1705    fixed_changed: Vec<(Key, NodeId)>,
1706    /// The advance of each font's `0` (CSS's `ch`), by family, size,
1707    /// weight and italic.
1708    zero_advances: rustc_hash::FxHashMap<(Option<crate::style::FontFamily>, u32, u16, bool), f32>,
1709    /// Nodes with lengths in `ch` styled since the last commit, perhaps
1710    /// before the views around them (and their fonts) were in place
1711    /// ([`Core::sync_ch`]).
1712    ch_styled: Vec<(Key, NodeId)>,
1713    /// Nodes reading font-relative lengths, so ordinary inserts do no extra walk.
1714    ch_readers: usize,
1715    /// Nodes whose inherited text color changed since they were styled
1716    /// with it (`currentColor`; [`Core::sync_colors`]).
1717    color_changed: Vec<(Key, NodeId)>,
1718    /// The user's preferred text size (1.0 is the default).
1719    font_scale: f32,
1720    /// The font text is drawn with unless it sets its own: the tokens'
1721    /// `font-sans` (`None`: the system's), as a page's is Tailwind's
1722    /// `--font-sans`.
1723    default_font: Option<crate::style::FontFamily>,
1724    queue: Vec<Key>,
1725    /// Parents whose children moved, each once: their children's positions
1726    /// are looked at before the next flush (`classes.rs` `flush_positions`),
1727    /// once however many joined or left.
1728    position_parents: Vec<Key>,
1729    needs_layout: bool,
1730    /// Parsed classes and the theme.
1731    tailwind: Tailwind,
1732    /// Resolved class styles shared by the nodes whose classes resolve alike
1733    /// (the same `ClassList` under the same inputs it reads,
1734    /// `classes::ResolvedKey`).
1735    resolved_styles:
1736        rustc_hash::FxHashMap<classes::ResolvedKey, std::rc::Rc<classes::ResolvedClassStyle>>,
1737    /// Tests resolve every class style afresh, to compare with the cache.
1738    #[cfg(test)]
1739    resolve_uncached: bool,
1740    /// What class variants read from the environment (`dark` as shown:
1741    /// [`Core::set_appearance`]).
1742    class_env: ClassEnvironment,
1743    /// The appearance the app asked for.
1744    appearance: crate::platform::Appearance,
1745    /// The platform reports dark appearance.
1746    system_dark: bool,
1747    /// [`Core::set_max_nodes`].
1748    max_nodes: usize,
1749    /// Raw text runs may go without nodes ([`Core::runs`]).
1750    fold_runs: bool,
1751    /// What the app may reach ([`Core::set_access`]).
1752    access: Arc<crate::access::Access>,
1753    /// What media sources starting with `//` resolve against
1754    /// ([`Core::set_base_url`]).
1755    base_url: Option<Arc<str>>,
1756    /// The roots local media files are read under
1757    /// ([`Core::set_media_files`]).
1758    media_files: Arc<crate::access::MediaFiles>,
1759    /// What the check answered for the network images canvases draw, by
1760    /// source: a canvas checks its images on every draw. Only answers that
1761    /// depend on nothing but the grant and the base, which clear it when
1762    /// they change; local files are resolved on every draw.
1763    canvas_images: rustc_hash::FxHashMap<Arc<str>, Option<Arc<str>>>,
1764    /// Denials already logged (each once).
1765    denied: rustc_hash::FxHashSet<String>,
1766    /// The windows' attribute records, by root node (the main window's is
1767    /// the root's): what was sent the platform and what was set since.
1768    windows: rustc_hash::FxHashMap<NodeId, crate::desktop::window::WindowRecord>,
1769    /// The windows of the app's own, by the app's id: their root nodes,
1770    /// and whether their placement is kept.
1771    window_ids: rustc_hash::FxHashMap<String, (NodeId, bool)>,
1772    /// Explicit quit mode set by the app (`nsh.json` `application.quitMode`,
1773    /// `Application.setQuitMode`, [`Core::set_quit_mode`]); `None` until
1774    /// the app chooses one.
1775    quit_mode: Option<crate::desktop::QuitMode>,
1776    /// Fallback quit mode when the app has not set one:
1777    /// [`crate::desktop::QuitMode::Explicit`] in a bare core,
1778    /// [`crate::desktop::QuitMode::Platform`] in an engine host.
1779    default_quit_mode: crate::desktop::QuitMode,
1780    /// nsh.json's `"window"` launch defaults ([`Core::set_main_window`]):
1781    /// the first app window inherits them, since the host has no visible
1782    /// window of its own.
1783    main_window_options: Option<crate::desktop::MainWindowOptions>,
1784    /// The launch defaults were given to the first window that opened this
1785    /// run: a later window after every window closed is not the first.
1786    launch_defaults_applied: bool,
1787    /// The main window's placement is kept (nsh.json `window.restoreBounds`,
1788    /// [`Core::set_main_window`]).
1789    keep_main_placement: bool,
1790    /// The main window has been on screen, or it opens shown: its reports
1791    /// are where the user left it ([`Core::keep_window_placement`]).
1792    main_shown: bool,
1793    /// Serves the app's clipboard calls in place of the platform
1794    /// ([`Core::set_clipboard`]).
1795    clipboard: Option<Arc<dyn crate::clipboard::ClipboardBackend>>,
1796    /// Answers the app's picks in place of the platform's picker
1797    /// ([`Core::set_picker`]).
1798    picker: Option<Arc<dyn crate::picker::PickerBackend>>,
1799    /// Opens and applies the app's windows of its own in place of the
1800    /// platform ([`Core::set_window_backend`]).
1801    window_backend: Option<Arc<dyn crate::desktop::WindowBackend>>,
1802    /// Plays the app's sound in place of the platform ([`Core::set_audio`]).
1803    audio: Option<Arc<dyn crate::audio::AudioBackend>>,
1804    /// The app's login item ([`Core::set_login_item`]); without one the app
1805    /// has none.
1806    login_item: Option<crate::desktop::LoginItems>,
1807    /// Rust components and what they rendered.
1808    components: components::Components,
1809    /// Overlay nodes, those shown in the order they were shown (the last
1810    /// on top).
1811    overlays: Vec<Key>,
1812    /// What the shown overlays listen to.
1813    overlay_state: overlay::Overlays,
1814}
1815
1816impl<M: TextEngine + 'static> Core<M> {
1817    /// Creates a core whose root view (id [`ROOT_ID`]) fills `viewport`.
1818    pub fn new(text_engine: M, viewport: Size<Points>) -> Self {
1819        let mut core = Self::with_engine(text_engine, viewport);
1820        core.geometry_engine = Some(core.text_engine.clone());
1821        // Components that run once measure text with it.
1822        let engine = core.text_engine.clone();
1823        core.components
1824            .runtime
1825            .set_measure(Rc::new(move |font, text| {
1826                crate::canvas::line_metrics(&*engine, font, text)
1827            }));
1828        core
1829    }
1830}
1831
1832impl<M: TextEngine> Core<M> {
1833    fn with_engine(text_engine: M, viewport: Size<Points>) -> Self {
1834        let mut layout = LayoutTree::with_capacity(256);
1835        let root_layout = layout.new_leaf(root_style(viewport));
1836        let mut nodes = Slab::with_capacity(256);
1837        let mut root = Node::new(ROOT_ID, Kind::View);
1838        root.layout = Some(root_layout);
1839        // The platform owns the root view.
1840        root.created = true;
1841        let root = nodes.insert(root) as Key;
1842        layout.set_tag(root_layout, root);
1843        // The root's size is the viewport's, in a terminal too.
1844        layout.set_role(
1845            root_layout,
1846            terminal_layout::Role {
1847                root: true,
1848                ..terminal_layout::Role::default()
1849            },
1850        );
1851        let mut slots = crate::id_table::IdTable::new();
1852        slots.insert(ROOT_ID as usize, root);
1853        Self {
1854            nodes,
1855            admitted_id_extent: slots.extent(),
1856            slots,
1857            layout,
1858            text_engine: Rc::new(text_engine),
1859            geometry_engine: None,
1860            geometries: Default::default(),
1861            measure_cache: MeasureCache::default(),
1862            resizing_commit: 0,
1863            resize_settling: false,
1864            pending_text: Vec::new(),
1865            attachment_blocks: Vec::new(),
1866            max_nodes: usize::MAX,
1867            fold_runs: true,
1868            access: Arc::default(),
1869            base_url: None,
1870            media_files: Arc::default(),
1871            canvas_images: Default::default(),
1872            denied: Default::default(),
1873            windows: Default::default(),
1874            window_ids: Default::default(),
1875            runs: Default::default(),
1876            folded: Default::default(),
1877            // Until the host or app sets one: a bare core keeps running
1878            // (the engine sets the default `"platform"` and any explicit
1879            // `application.quitMode` before the app runs).
1880            quit_mode: None,
1881            default_quit_mode: crate::desktop::QuitMode::Explicit,
1882            main_window_options: None,
1883            launch_defaults_applied: false,
1884            keep_main_placement: false,
1885            main_shown: false,
1886            clipboard: None,
1887            picker: None,
1888            window_backend: None,
1889            audio: None,
1890            login_item: None,
1891            components: components::Components::for_viewport(viewport),
1892            lists: Vec::new(),
1893            parent_lists: Vec::new(),
1894            outer_moved: false,
1895            extent_changed: false,
1896            culls_content: true,
1897            culling: Vec::new(),
1898            cull_dirty: false,
1899            reach: crate::animation::Reach::default(),
1900            cull_made: false,
1901            cells_framed: false,
1902            cull_scratch: Vec::new(),
1903            pace: pace::Pace::default(),
1904            list_motion: list_motion::ListMotion::default(),
1905            placeholders: Vec::new(),
1906            asked_rows: Vec::new(),
1907            placeholders_resized: false,
1908            outer_asked: Vec::new(),
1909            sticky_views: Vec::new(),
1910            sticky_nodes: Vec::new(),
1911            sticky_scrollers: Vec::new(),
1912            builtin_scrollbars: None,
1913            scrollbars_pending: Vec::new(),
1914            watched_inputs: Vec::new(),
1915            fitted_pending: Vec::new(),
1916            decorated: Vec::new(),
1917            sticky_changed: false,
1918            followers: Vec::new(),
1919            relators: Vec::new(),
1920            follow_changed: false,
1921            sticky_warned: false,
1922            inset_warned: false,
1923            shaders: Default::default(),
1924            web_unchecked: Default::default(),
1925            transition_starts: Vec::new(),
1926            pictured: Default::default(),
1927            unlinked_from: Vec::new(),
1928            roots: Vec::new(),
1929            accessories: Default::default(),
1930            header_heights: (Points(44.0), Points(96.0)),
1931            safe_area: EdgeInsets::default(),
1932            overlay_bounds: None,
1933            snap_to_window_margin: crate::overlay::DEFAULT_SNAP_TO_WINDOW_MARGIN,
1934            list_binds: Vec::new(),
1935            kept_lists: Vec::new(),
1936            selection_kept: Vec::new(),
1937            kept_scratch: Vec::new(),
1938            paced_lists: Vec::new(),
1939            paced_scratch: Vec::new(),
1940            events: Vec::new(),
1941            cells_scratch: Vec::new(),
1942            awaiting_renders: Vec::new(),
1943            root,
1944            viewport,
1945            mount: Vec::new(),
1946            track_tree_order: false,
1947            tree_order_changed: false,
1948            tab_places_stale: false,
1949            key_ancestry_dirty: false,
1950            mount_projected: false,
1951            batches: 0,
1952            retags: None,
1953            commands: Vec::new(),
1954            focus_back: None,
1955            focus_origins: Vec::new(),
1956            pointer_focus_back: None,
1957            layout_animation: None,
1958            scoped_layout: Vec::new(),
1959            resized: Vec::new(),
1960            restructured: Vec::new(),
1961            env_styled: Default::default(),
1962            env_scratch: Vec::new(),
1963            keyboard_moved: false,
1964            status_bar_nodes: Vec::new(),
1965            status_bars_moved: false,
1966            orientation_pages: Vec::new(),
1967            orientations_shown: 0,
1968            pointer_none_classes: 0,
1969            pointer_pending: Vec::new(),
1970            slop_moved: Vec::new(),
1971            focus: None,
1972            focus_chain: Vec::new(),
1973            focus_scratch: Vec::new(),
1974            focus_moved: false,
1975            blur_held: false,
1976            focus_within_changed: false,
1977            modality: None,
1978            focus_visible: false,
1979            focus_by_keyboard: false,
1980            focus_by_pointer: false,
1981            pointer_keymap: None,
1982            restoring_modal_focus: false,
1983            modals_opened: Vec::new(),
1984            modal_focus_given: None,
1985            focus_visible_on: None,
1986            focus_visible_moved: false,
1987            projected_focus: Vec::new(),
1988            pressed_impulses: Vec::new(),
1989            passed_hovers: Default::default(),
1990            fixed_changed: Vec::new(),
1991            zero_advances: Default::default(),
1992            ch_styled: Vec::new(),
1993            ch_readers: 0,
1994            color_changed: Vec::new(),
1995            font_scale: 1.0,
1996            default_font: None,
1997            queue: Vec::new(),
1998            position_parents: Vec::new(),
1999            needs_layout: true,
2000            tailwind: Tailwind::new(),
2001            resolved_styles: rustc_hash::FxHashMap::default(),
2002            #[cfg(test)]
2003            resolve_uncached: false,
2004            class_env: ClassEnvironment::default(),
2005            appearance: crate::platform::Appearance::System,
2006            system_dark: false,
2007            overlays: Vec::new(),
2008            overlay_state: overlay::Overlays::default(),
2009        }
2010    }
2011
2012    /// Sets the height of the platform's screen header bar, normal and with
2013    /// a large title (status bar excluded).
2014    pub fn set_header_heights(&mut self, normal: Points, large: Points) {
2015        if self.header_heights != (normal, large) {
2016            self.header_heights = (normal, large);
2017            self.needs_layout = true;
2018        }
2019    }
2020
2021    /// Sets the surface's safe-area insets.
2022    pub fn set_safe_area(&mut self, insets: EdgeInsets) {
2023        if self.safe_area != insets {
2024            self.safe_area = insets;
2025            self.needs_layout = true;
2026        }
2027    }
2028
2029    /// Where the root view's anchored overlays may be placed, in its
2030    /// coordinates, when the platform shows them beyond the root view: the
2031    /// web's `overlays: "viewport"` draws them over the browser window, so
2032    /// this is the window's rectangle (less its safe area) relative to the
2033    /// container. They are placed and flipped within it, less their
2034    /// `margin`, rather than within the root view's safe area. `None` (the
2035    /// default) keeps them to the root view. Overlays without an anchor
2036    /// and those of modals are laid out as before.
2037    pub fn set_overlay_area(&mut self, area: Option<crate::geometry::Bounds<Points>>) {
2038        if self.overlay_bounds == area {
2039            return;
2040        }
2041        self.overlay_bounds = area;
2042        // Their room changed: laid out and placed again. With none shown
2043        // the next one is placed in it as it shows.
2044        if self.root_overlay_shown() {
2045            self.needs_layout = true;
2046        }
2047    }
2048
2049    /// The distance the overlays without a `margin` of their own (menus,
2050    /// popovers, tooltips, popups) keep from the edges of the window's
2051    /// safe area ([`crate::element::set_snap_to_window_margin`]): they are placed,
2052    /// flipped and shrunk within it, so none touches the window's edge.
2053    pub fn set_snap_to_window_margin(&mut self, margin: Points) {
2054        let margin = Points(margin.0.max(0.0));
2055        if self.snap_to_window_margin == margin {
2056            return;
2057        }
2058        self.snap_to_window_margin = margin;
2059        for (_, node) in &mut self.nodes {
2060            if let Some(root) = node.root.as_mut()
2061                && let Some(overlay) = root.overlay.as_mut()
2062                && !overlay.margin_set
2063            {
2064                overlay.placed = None;
2065                root.laid_out = None;
2066            }
2067        }
2068        self.needs_layout = true;
2069    }
2070
2071    /// The platform presents root `id` (a modal) at `size`, with `insets`
2072    /// of it covered by system UI.
2073    pub fn set_root_size(&mut self, id: NodeId, size: Size<Points>, insets: EdgeInsets) {
2074        let Ok(key) = self.key(id) else { return };
2075        if let Some(root) = self.nodes[key as usize].root.as_mut()
2076            && (root.reported != Some(size) || root.insets != insets)
2077        {
2078            root.reported = Some(size);
2079            root.insets = insets;
2080            self.needs_layout = true;
2081        }
2082    }
2083
2084    /// The platform measured where the content of screen `id` starts below
2085    /// the header it shows (`None`: estimate it from the bar's height and
2086    /// the safe area). Used for screens that lay their content out below
2087    /// the header (not large titles or transparent headers).
2088    pub fn set_screen_header(&mut self, id: NodeId, height: Option<Points>) {
2089        let Ok(key) = self.key(id) else { return };
2090        let height = height.map(|h| h.0).filter(|h| h.is_finite() && *h >= 0.0);
2091        if let Some(root) = self.nodes[key as usize].root.as_mut()
2092            && root.header != height
2093        {
2094            root.header = height;
2095            self.needs_layout = true;
2096        }
2097    }
2098
2099    /// Sets the user's preferred text size (1.0 is the default): text that
2100    /// allows font scaling is laid out again.
2101    pub fn set_font_scale(&mut self, scale: f32) {
2102        let scale = if scale.is_finite() && scale > 0.0 {
2103            scale
2104        } else {
2105            1.0
2106        };
2107        if scale == self.font_scale {
2108            return;
2109        }
2110        self.font_scale = scale;
2111        self.ch_changed(self.root);
2112        self.relayout_text();
2113    }
2114
2115    /// Sets the font text is drawn with unless it sets its own (the
2116    /// tokens' `font-sans`): text is laid out again.
2117    pub(crate) fn set_default_font(&mut self, family: Option<crate::style::FontFamily>) {
2118        if family == self.default_font {
2119            return;
2120        }
2121        self.default_font = family;
2122        self.ch_changed(self.root);
2123        self.relayout_text();
2124    }
2125
2126    /// Lays every text and input out again.
2127    fn relayout_text(&mut self) {
2128        let blocks: Vec<(Key, Kind)> = self
2129            .nodes
2130            .iter()
2131            .filter(|(_, n)| matches!(n.kind, Kind::Text | Kind::Input) && !n.inline)
2132            .map(|(k, n)| (k as Key, n.kind))
2133            .collect();
2134        for (key, kind) in blocks {
2135            if kind == Kind::Text {
2136                self.mark(key, dirty::TEXT_BUILD);
2137            } else {
2138                self.measure_input(key);
2139                self.mark(key, dirty::INPUT);
2140            }
2141        }
2142    }
2143
2144    /// The pixel ratio went from `old` to `new`: the images whose variant
2145    /// changes are sent again (their layout does not change).
2146    fn repick_images(&mut self, old: f32, new: f32) {
2147        let changes = |s: &Option<ImageSource>| {
2148            s.as_ref()
2149                .is_some_and(|s| !s.scales.is_empty() && s.variant(old) != s.variant(new))
2150        };
2151        let images: Vec<Key> = self
2152            .nodes
2153            .iter()
2154            .filter(|(_, n)| {
2155                n.image
2156                    .as_ref()
2157                    .is_some_and(|i| changes(&i.source) || changes(&i.options.placeholder))
2158            })
2159            .map(|(k, _)| k as Key)
2160            .collect();
2161        for key in images {
2162            self.mark(key, dirty::IMAGE);
2163        }
2164    }
2165
2166    /// Number of live nodes, including the root.
2167    pub fn node_count(&self) -> usize {
2168        self.nodes.len()
2169    }
2170
2171    /// How many node ids the core's id table has room for: far above
2172    /// [`Self::node_count`] when the ids of nodes that are gone still take
2173    /// room (diagnostics).
2174    pub fn node_id_room(&self) -> usize {
2175        self.slots.len()
2176    }
2177
2178    /// Sets what the app may reach: remote images, canvas images, video
2179    /// sources, web views and the status bar are checked against it.
2180    pub fn set_access(&mut self, access: Arc<crate::access::Access>) {
2181        // `open_window` checks windows as `Window.open` does.
2182        {
2183            let _entered = self.components.runtime.enter();
2184            crate::element::global::<crate::element::desktop::WindowAccess>()
2185                .set(crate::element::desktop::WindowAccess(Some(access.clone())));
2186        }
2187        self.components.runtime.set_access(access.clone());
2188        self.access = access;
2189        self.canvas_images.clear();
2190    }
2191
2192    /// Sets the URL media sources starting with `//` resolve against, whose
2193    /// scheme they take (the page's on the web, as `fetch`'s relative
2194    /// URLs). Without one such a source names no URL, and only an app
2195    /// without capabilities loads it ([`crate::access::Access::media_url`]).
2196    /// A base marks a page: with one, `/x` and relative paths are the
2197    /// page's, not local files, so only pages set one.
2198    pub fn set_base_url(&mut self, url: Option<Arc<str>>) {
2199        self.base_url = url;
2200        self.canvas_images.clear();
2201    }
2202
2203    /// Sets the `capabilities.fs.read` roots the app's local media files
2204    /// (absolute paths, `file:` URLs) are read under; without them such a
2205    /// source of an app with capabilities loads nothing
2206    /// ([`crate::access::Access::media_url`]).
2207    pub fn set_media_files(&mut self, files: Arc<crate::access::MediaFiles>) {
2208        self.media_files = files;
2209        self.canvas_images.clear();
2210    }
2211
2212    /// Sets what the core's own image loads (an [`crate::element::svg`]'s
2213    /// bytes) go through: the app's bundled files, access policy and disk
2214    /// cache. Without it they read inline bytes, files and `asset:/` URIs
2215    /// of no base only.
2216    #[cfg(not(target_arch = "wasm32"))]
2217    pub fn set_image_context(&mut self, context: crate::image::loader::Context) {
2218        crate::image::loader::set_context(context);
2219    }
2220
2221    /// Serves the app's clipboard calls from `backend` instead of the
2222    /// platform's clipboard (`None`: the platform's, the default).
2223    pub fn set_clipboard(&mut self, backend: Option<Arc<dyn crate::clipboard::ClipboardBackend>>) {
2224        self.clipboard = backend;
2225    }
2226
2227    /// Answers the app's picks (`Picker.pickImages`) with `backend`, an
2228    /// embedding app's own picker or a test's files, instead of showing the
2229    /// platform's picker (`None`: the platform's, the default).
2230    pub fn set_picker(&mut self, backend: Option<Arc<dyn crate::picker::PickerBackend>>) {
2231        self.picker = backend;
2232    }
2233
2234    /// Sets an explicit quit mode when the app's last window closes
2235    /// (`nsh.json` `application.quitMode`, `Application.setQuitMode`).
2236    /// Overrides the implicit main window's default quit-on-close behavior.
2237    pub fn set_quit_mode(&mut self, mode: crate::desktop::QuitMode) {
2238        self.quit_mode = Some(mode);
2239    }
2240
2241    /// Sets the host's default quit mode when the app has not explicitly
2242    /// configured one: explicit `<Window>` scenes follow this mode, while a
2243    /// plain root's implicit main window still quits on close. Engine
2244    /// plumbing, not app API.
2245    #[doc(hidden)]
2246    pub fn __set_default_quit_mode(&mut self, mode: crate::desktop::QuitMode) {
2247        self.default_quit_mode = mode;
2248    }
2249
2250    /// The main window's launch-time options (nsh.json `"window"`): its
2251    /// attributes go to the main window with the next commit, as
2252    /// `currentWindow().set()` sends them (capabilities apply); with
2253    /// `restoreBounds` its placement is kept from then on as the platform
2254    /// reports it (the environment's window state), for the next launch
2255    /// to open it there ([`crate::desktop::MainWindowOptions::kept_placement`]).
2256    /// Set it after the environment ([`Core::set_environment`]): a surface
2257    /// without a window, a phone's, takes no attributes.
2258    pub fn set_main_window(&mut self, options: &crate::desktop::MainWindowOptions) {
2259        self.main_window_options = Some(options.clone());
2260        self.keep_main_placement = options.restore_bounds;
2261        self.main_shown |= options.visible_at_launch();
2262        if let Some(state) = self.components.environment.window_state {
2263            self.keep_window_placement(crate::ROOT_ID, &state);
2264        }
2265        if options.attributes.is_empty() {
2266            return;
2267        }
2268        // The launch defaults are the host's, read before the app runs:
2269        // they are not the sandboxed app acting on the main window.
2270        if self.key(crate::ROOT_ID).is_ok() {
2271            self.window_command(
2272                crate::ROOT_ID,
2273                crate::desktop::DesktopCommand::SetAttributes(Box::new(options.attributes.clone())),
2274                true,
2275            );
2276        }
2277    }
2278
2279    /// Opens and applies the app's windows of its own with `backend`, an
2280    /// embedding host's windows or a test's fake, instead of the platform
2281    /// (`None`: the platform's, the default). The main window's commands
2282    /// stay with the platform.
2283    pub fn set_window_backend(&mut self, backend: Option<Arc<dyn crate::desktop::WindowBackend>>) {
2284        self.window_backend = backend;
2285    }
2286
2287    /// Plays the app's sound (`Sound`, `AudioPlayer`) with `backend`, an
2288    /// embedding app's own audio stack or a test's fake, instead of the
2289    /// platform's (`None`: the platform's, the default).
2290    pub fn set_audio(&mut self, backend: Option<Arc<dyn crate::audio::AudioBackend>>) {
2291        self.audio = backend;
2292    }
2293
2294    /// Reads and changes the app's login item (`Application.launchAtLogin`)
2295    /// with `backend`: the platform's, which a standalone app's runner gives,
2296    /// or a test's fake. `None` (the default): the app has no login item,
2297    /// it does not launch at login ([`crate::desktop::LoginItemBackend`]).
2298    pub fn set_login_item(&mut self, backend: Option<Arc<dyn crate::desktop::LoginItemBackend>>) {
2299        self.login_item = backend.map(crate::desktop::LoginItems::new);
2300    }
2301
2302    /// Keeps the app's storage (`nsh/storage`) in `backend`; `None`: in
2303    /// memory, for the core's life.
2304    pub fn set_storage(&mut self, backend: Option<Arc<dyn crate::storage::StorageBackend>>) {
2305        self.components
2306            .runtime
2307            .set_storage(crate::storage::Store::new(backend));
2308    }
2309
2310    /// The app's own data directory, what [`crate::element::data_dir`]
2311    /// gives; `None`: it has none.
2312    pub fn set_data_dir(&mut self, dir: Option<std::path::PathBuf>) {
2313        self.components.runtime.set_data_dir(dir);
2314    }
2315
2316    /// The app as it was built, what [`crate::element::app_info`] answers
2317    /// (a Rust app's root's, [`crate::element::Root::app_info`]); `None`:
2318    /// the runner has none (a TSX app's is JS's `appInfo()`).
2319    pub fn set_app_info(&mut self, info: Option<crate::platform::AppInfo>) {
2320        self.components.runtime.set_app_info(info);
2321    }
2322
2323    /// What Rust code checks for updates with
2324    /// ([`crate::runtime::prompt_for_update`]); `None`: the app does not
2325    /// update. A JS app's VM gets its own ([`crate::element::System`]).
2326    pub fn set_updater(
2327        &mut self,
2328        updater: Option<std::sync::Arc<dyn crate::runtime::UpdaterHost>>,
2329    ) {
2330        self.components.runtime.set_updater(updater);
2331    }
2332
2333    /// Logs (once) that the app was refused `what`.
2334    fn deny(&mut self, what: String) {
2335        if self.denied.len() < 256 && self.denied.insert(what.clone()) {
2336            log::warn!(target: "js", "{what}");
2337        }
2338    }
2339
2340    /// Caps the number of nodes (each may hold a native view, whose memory
2341    /// no JS heap limit covers): creating more is a fatal [`ApplyError`].
2342    pub fn set_max_nodes(&mut self, max: usize) {
2343        self.max_nodes = max.max(1);
2344    }
2345
2346    /// A burst of resizes began (`true`) or ended. Meanwhile only text near
2347    /// the screen is measured and laid out at new widths: what is far from
2348    /// it keeps its height, and catches up in the commit after the end. A
2349    /// window's drag gets its frames from what the user sees; a long page
2350    /// has far more text than the screen shows.
2351    pub fn set_resizing(&mut self, resizing: bool) {
2352        if resizing == self.measure_cache.resizing.is_some() {
2353            return;
2354        }
2355        if resizing {
2356            self.resizing_commit = self.resizing_commit.wrapping_add(1).max(1);
2357            self.measure_cache.resizing = Some(self.resizing_commit);
2358            return;
2359        }
2360        self.measure_cache.resizing = None;
2361        let keys: Vec<(Key, LayoutId)> = self
2362            .nodes
2363            .iter()
2364            .filter_map(|(key, node)| Some((key as Key, node.layout?)))
2365            .collect();
2366        for (key, layout) in keys {
2367            let Some(LeafContext::Text(cx)) = self.layout.get_node_context_mut(layout) else {
2368                continue;
2369            };
2370            if std::mem::take(&mut cx.held) {
2371                self.layout.mark_dirty(layout);
2372                self.needs_layout = true;
2373                self.resize_settling = true;
2374                self.queue_text(key);
2375            }
2376        }
2377    }
2378
2379    /// Marks the text within a screen's height of the screen, from where
2380    /// the last commit put the views, for this commit of a resize. A text
2381    /// it finds after waiting catches up now.
2382    fn mark_near_screen(&mut self) {
2383        self.resizing_commit = self.resizing_commit.wrapping_add(1).max(1);
2384        self.measure_cache.resizing = Some(self.resizing_commit);
2385        let (width, height) = (self.viewport.width.0, self.viewport.height.0);
2386        let mut stack = vec![(self.root, 0.0f32, 0.0f32)];
2387        while let Some((key, x, y)) = stack.pop() {
2388            let node = &self.nodes[key as usize];
2389            let frame = node.frame;
2390            let (mut x, mut y) = (x, y);
2391            // Not placed yet, or of no size around what overflows it: no
2392            // telling, so it counts as near.
2393            // (`Bounds::UNSET` is NaN.)
2394            if !frame.origin.x.0.is_nan() {
2395                x += frame.origin.x.0;
2396                y += frame.origin.y.0;
2397                let (w, h) = (frame.size.width.0, frame.size.height.0);
2398                let sized = w > 0.0 && h > 0.0;
2399                if sized
2400                    && (x + w < -width || x > 2.0 * width || y + h < -height || y > 2.0 * height)
2401                {
2402                    continue;
2403                }
2404            }
2405            if let Some(scroll) = node.scroll.as_deref() {
2406                x -= scroll.offset.0;
2407                y -= scroll.offset.1;
2408            }
2409            stack.extend(node.children.iter().map(|&child| (child, x, y)));
2410            if let Some(layout) = node.layout
2411                && let Some(LeafContext::Text(cx)) = self.layout.get_node_context_mut(layout)
2412            {
2413                cx.near_screen = self.resizing_commit;
2414                if std::mem::take(&mut cx.held) {
2415                    self.layout.mark_dirty(layout);
2416                    self.queue_text(key);
2417                }
2418            }
2419        }
2420    }
2421
2422    /// Changes the size of the root view.
2423    pub fn set_viewport(&mut self, viewport: Size<Points>) {
2424        if viewport != self.viewport {
2425            self.viewport = viewport;
2426            self.resize_settling = true;
2427            let root = self.nodes[self.root as usize].layout.expect("root layout");
2428            self.layout.set_style(root, root_style(viewport));
2429            self.needs_layout = true;
2430            // Restyles what follows the window's size (`apply_environment`).
2431            self.components_viewport(viewport);
2432        }
2433    }
2434
2435    /// The platform scrolled a scroll view or list to `(x, y)`, having
2436    /// applied `applied` of the scrolls the core issued to it
2437    /// (`MountItem::ScrollBy` and `Command::ScrollTo` of lists).
2438    pub fn set_scroll_offset(&mut self, id: NodeId, offset: Point<Points>, applied: u32) {
2439        let (x, y) = (offset.x.0, offset.y.0);
2440        let Ok(key) = self.key(id) else { return };
2441        let node = &mut self.nodes[key as usize];
2442        let horizontal = node.scroll.as_ref().is_some_and(|s| s.horizontal);
2443        let mut dependents = false;
2444        let mut moved = false;
2445        if let Some(scroll) = node.scroll.as_mut() {
2446            moved = scroll.offset != (x, y);
2447            // A scroll the core sent is a jump, not the user's motion.
2448            let issued = scroll.target.is_some_and(|(n, _)| n <= applied);
2449            scroll.step = match issued {
2450                true => (0.0, 0.0),
2451                false => (x - scroll.offset.0, y - scroll.offset.1),
2452            };
2453            scroll.offset = (x, y);
2454            if issued {
2455                scroll.target = None;
2456            }
2457            if !scroll.dependents.is_empty() {
2458                scroll.pending.retain(|&(n, _)| n > applied);
2459                dependents = true;
2460            }
2461        }
2462        if let Some(list) = node.list.as_mut() {
2463            list.reported(if horizontal { x } else { y }, applied);
2464        }
2465        self.cull_moved(key);
2466        if dependents {
2467            self.dependents_dirty(key);
2468        }
2469        // Views that follow an element in what it scrolls go with it
2470        // (`follow.rs`).
2471        self.follow_changed |= moved && !self.followers.is_empty();
2472        // A link's hint placed where the pointer came over it would be left
2473        // behind by the content (`Core::overlay_scrolled`).
2474        if moved && !self.overlays.is_empty() {
2475            self.overlay_scrolled(key);
2476        }
2477    }
2478
2479    /// The user moved scroll view `id` with scroll key move `key_move`, which
2480    /// the platform animates to what it knows of the content. On a list of its
2481    /// own End queues an animated `scrollToEnd`, in order with the app's
2482    /// scroll commands, so the list follows its end and rows below that
2483    /// were never rendered, sized by their estimate, do not stop it short;
2484    /// a repeat while the list follows its end changes nothing. Any other
2485    /// key takes back an End not resolved yet and ends the target the list
2486    /// followed, as the user scrolling away does. Lists in their parent's
2487    /// viewport and inverted lists are left to the platform.
2488    pub fn key_scrolled(&mut self, id: NodeId, key_move: crate::scroll::KeyMove) {
2489        let Ok(key) = self.key(id) else { return };
2490        let queued = self.commands.iter().filter(|(to, _)| *to == id).count() as u32;
2491        let Some(list) = self.nodes[key as usize].list.as_mut() else {
2492            return;
2493        };
2494        if !list.follows_end_key() {
2495            return;
2496        }
2497        if key_move == crate::scroll::KeyMove::End {
2498            // A repeat: the last scroll queued or followed is the end.
2499            let repeat = match list.key_ends.last() {
2500                Some(&n) => n + 1 == queued,
2501                None => queued == 0 && list.follows_end(),
2502            };
2503            if !repeat {
2504                list.key_ends.push(queued);
2505                self.commands
2506                    .push((id, Command::ScrollToEnd { animated: true }));
2507            }
2508            return;
2509        }
2510        list.unpin();
2511        let ends = std::mem::take(&mut list.key_ends);
2512        // The latest first, so the places of the earlier ones hold.
2513        for &n in ends.iter().rev() {
2514            let at = self
2515                .commands
2516                .iter()
2517                .enumerate()
2518                .filter(|(_, (to, _))| *to == id)
2519                .nth(n as usize)
2520                .map(|(at, _)| at);
2521            if let Some(at) = at {
2522                self.commands.remove(at);
2523            }
2524        }
2525    }
2526
2527    /// Keeps the rows of virtual lists that hold `nodes` rendered, out of
2528    /// the render window too, until the next call: the ends of a text
2529    /// selection across a list's rows, whose texts must outlive scrolling
2530    /// away (a recycled cell would show another row). Replaces the last
2531    /// call's; none releases them. The rows holding the keyboard focus or
2532    /// an open overlay are kept anyway ([`Core::sync_kept`]).
2533    pub fn set_kept(&mut self, nodes: &[NodeId]) {
2534        self.selection_kept.clear();
2535        self.selection_kept.extend_from_slice(nodes);
2536        self.sync_kept();
2537    }
2538
2539    /// Keeps the rows of lists rendered wherever they scroll while they
2540    /// hold what must outlive scrolling away: [`Core::set_kept`]'s nodes,
2541    /// the keyboard focus and open overlays (a row's menu or popover). A
2542    /// recycled cell would show another row, drop the focus and close the
2543    /// overlay. Each list's kept rows are all that hold one; in a list in
2544    /// another list's row, both rows are kept. The rows on either side of
2545    /// the focus's are kept with it, so that the platform's Tab and
2546    /// Shift+Tab, which only reach views that exist, move on to the next
2547    /// row in the list rather than past it, however far the window lags
2548    /// (the row the focus reaches then scrolls into view, which renders
2549    /// the rows around it).
2550    fn sync_kept(&mut self) {
2551        let mut holders = std::mem::take(&mut self.kept_scratch);
2552        holders.clear();
2553        holders.extend(
2554            self.selection_kept
2555                .iter()
2556                .filter_map(|&id| self.key(id).ok()),
2557        );
2558        let focus = self
2559            .focus
2560            .filter(|&(key, id)| self.nodes.get(key as usize).is_some_and(|n| n.id == id))
2561            .map(|(key, _)| key);
2562        holders.extend(focus);
2563        holders.extend(self.overlays.iter().copied().filter(|&key| {
2564            self.overlay(key)
2565                .is_some_and(|o| o.host.is_some() && o.config.hint.is_none())
2566        }));
2567        let mut kept: Vec<(Key, u32)> = Vec::new();
2568        for &holder in &holders {
2569            let mut key = holder;
2570            // Up to each cell: an ancestor whose parent is a list holding
2571            // it in a slot.
2572            loop {
2573                let parent = self.nodes[key as usize].parent;
2574                if parent == NO_KEY {
2575                    break;
2576                }
2577                if let Some(list) = self.nodes[parent as usize].list.as_ref()
2578                    && let Some(index) = list
2579                        .slots
2580                        .iter()
2581                        .find(|s| s.cell == key)
2582                        .and_then(|s| s.index)
2583                {
2584                    kept.push((parent, index));
2585                    if focus == Some(holder) {
2586                        if index > 0 {
2587                            kept.push((parent, index - 1));
2588                        }
2589                        if index + 1 < list.count {
2590                            kept.push((parent, index + 1));
2591                        }
2592                    }
2593                }
2594                key = parent;
2595            }
2596        }
2597        self.kept_scratch = holders;
2598        if kept.is_empty() && self.kept_lists.is_empty() {
2599            return;
2600        }
2601        let mut lists: Vec<Key> = kept.iter().map(|&(list, _)| list).collect();
2602        lists.sort_unstable();
2603        lists.dedup();
2604        for &list in self.kept_lists.iter().filter(|l| !lists.contains(l)) {
2605            if let Some(state) = self
2606                .nodes
2607                .get_mut(list as usize)
2608                .and_then(|n| n.list.as_mut())
2609            {
2610                state.set_kept(Vec::new());
2611            }
2612        }
2613        for &list in &lists {
2614            let items = kept
2615                .iter()
2616                .filter(|&&(l, _)| l == list)
2617                .map(|&(_, i)| i)
2618                .collect();
2619            if let Some(state) = self.nodes[list as usize].list.as_mut() {
2620                state.set_kept(items);
2621            }
2622        }
2623        self.kept_lists = lists;
2624    }
2625
2626    /// The platform scrolled the text of multiline input `id` to `offset`,
2627    /// its text `content` large in a `viewport` (reported while a built-in
2628    /// bar or a scroll watch follows it, `InputConfig::report_scroll`).
2629    pub fn set_input_scroll(
2630        &mut self,
2631        id: NodeId,
2632        offset: Point<Points>,
2633        content: Size<Points>,
2634        viewport: Size<Points>,
2635    ) {
2636        let Ok(key) = self.key(id) else { return };
2637        if let Some(input) = self.nodes[key as usize].input.as_mut() {
2638            input.scroll = Some(InputScroll {
2639                offset,
2640                content,
2641                viewport,
2642            });
2643        }
2644    }
2645
2646    /// The platform zoomed scroll view `id` to `scale`.
2647    pub fn set_zoom(&mut self, id: NodeId, scale: f32) {
2648        let Ok(key) = self.key(id) else { return };
2649        if let Some(scroll) = self.nodes[key as usize].scroll.as_mut() {
2650            scroll.zoom = scale;
2651        }
2652    }
2653
2654    /// A registered native component reported its own size: it is laid out
2655    /// at it where its style leaves a dimension open.
2656    pub fn set_component_size(&mut self, id: NodeId, size: Size<Points>) {
2657        let Ok(key) = self.key(id) else { return };
2658        let Some(layout) = self.nodes[key as usize].layout else {
2659            return;
2660        };
2661        if let Some(LeafContext::Native(own)) = self.layout.get_node_context_mut(layout)
2662            && *own != Some(size)
2663        {
2664            *own = Some(size);
2665            self.layout.mark_dirty(layout);
2666            self.needs_layout = true;
2667        }
2668    }
2669
2670    /// What `onScroll` reports for scroll view `id`, if it listens to it:
2671    /// the minimum milliseconds between events, the content size (zoomed),
2672    /// the viewport size and the zoom scale.
2673    pub fn scroll_listener(&self, id: NodeId) -> Option<(f32, Size<Points>, Size<Points>, f32)> {
2674        let node = &self.nodes[self.key(id).ok()? as usize];
2675        if !node.events.contains(EventKind::Scroll) {
2676            return None;
2677        }
2678        let scroll = node.scroll.as_ref()?;
2679        let frame = node.frame.size;
2680        let content = scroll.content.unwrap_or(frame);
2681        let z = scroll.zoom;
2682        Some((scroll.event_throttle_ms, content * z, frame, z))
2683    }
2684
2685    /// Moves list render requests produced by the last commit into `out`:
2686    /// what must bind before the frame shows (cells whose item moved, cells
2687    /// in the viewport and just ahead of it). The rest of the overscan
2688    /// waits ([`Core::take_paced_list_binds`]).
2689    pub fn take_list_binds(&mut self, out: &mut Vec<ListBind>) {
2690        out.append(&mut self.list_binds);
2691    }
2692
2693    /// Whether lists have overscan cells waiting to bind.
2694    pub fn has_paced_list_binds(&self) -> bool {
2695        !self.paced_lists.is_empty()
2696    }
2697
2698    /// Hands out up to `cells` of the overscan cells waiting to bind, one
2699    /// per list in turn (a nested list is not starved by its parent), each
2700    /// list's nearest its leading edge first. What a list assigns now is
2701    /// what waits: cells it left or whose items went are never handed out.
2702    pub fn take_paced_list_binds(&mut self, cells: usize, out: &mut Vec<ListBind>) {
2703        let mut left = cells;
2704        let mut lists = std::mem::take(&mut self.paced_lists);
2705        let mut one = std::mem::take(&mut self.paced_scratch);
2706        let start = out.len();
2707        while left > 0 && !lists.is_empty() {
2708            lists.retain(|&id| {
2709                if left == 0 {
2710                    return true;
2711                }
2712                let Some(list) = self
2713                    .key(id)
2714                    .ok()
2715                    .and_then(|key| self.nodes[key as usize].list.as_mut())
2716                else {
2717                    return false;
2718                };
2719                one.clear();
2720                left -= list.take_paced(1, &mut one);
2721                if let Some((slot, index)) = one.pop() {
2722                    match out[start..].iter_mut().find(|b| b.list == id) {
2723                        Some(bind) => bind.binds.push((slot, index)),
2724                        None => out.push(ListBind {
2725                            list: id,
2726                            binds: vec![(slot, index)],
2727                        }),
2728                    }
2729                }
2730                list.has_paced()
2731            });
2732        }
2733        self.paced_lists = lists;
2734        self.paced_scratch = one;
2735    }
2736
2737    /// Whether events wait for [`Core::take_events`].
2738    pub fn has_events(&self) -> bool {
2739        !self.events.is_empty()
2740    }
2741
2742    /// Moves what the core hands JS (events it raised, such as
2743    /// `onLoadMore` and `onLayout`, Rust components' events, calls'
2744    /// results) into `out`, in order.
2745    pub fn take_events(&mut self, out: &mut Vec<crate::element::JsEvent>) {
2746        if !self.asked_rows.is_empty() {
2747            let rows = std::mem::take(&mut self.asked_rows);
2748            self.events.push(crate::element::JsEvent::Rows(rows));
2749        }
2750        out.append(&mut self.events);
2751        // The caller hands them to JS before the next commit: what waits for
2752        // the app's answer to them runs there ([`crate::element::after_answer`]).
2753        self.components.executor.hand_answers();
2754    }
2755
2756    /// Whether the next commit runs closures that waited for the app's
2757    /// answer to events taken already ([`crate::element::after_answer`]):
2758    /// the engine commits again rather than leave them for later input.
2759    pub fn has_due_answers(&self) -> bool {
2760        self.components.executor.has_due_answers()
2761    }
2762
2763    /// Registers a custom font (TrueType, OpenType, WOFF or WOFF2 data) with
2764    /// the text engine. Text measured before is measured again.
2765    pub fn register_font(&mut self, data: &[u8]) -> Result<(), String> {
2766        self.text_engine
2767            .register_font(&crate::text::font_data(data)?)?;
2768        self.fonts_changed();
2769        Ok(())
2770    }
2771
2772    /// The text engine's fonts changed (a font the platform loads
2773    /// asynchronously became usable): text measured before is measured
2774    /// again.
2775    pub fn fonts_changed(&mut self) {
2776        self.zero_advances.clear();
2777        self.ch_changed(self.root);
2778        self.measure_cache.clear();
2779        let blocks: Vec<Key> = self
2780            .nodes
2781            .iter()
2782            .filter(|(_, n)| {
2783                matches!(n.kind, Kind::Text | Kind::Input) && !n.inline && n.layout.is_some()
2784            })
2785            .map(|(k, _)| k as Key)
2786            .collect();
2787        for key in blocks {
2788            let layout = self.nodes[key as usize].layout.expect("text layout");
2789            let cx = self.text_cx(layout);
2790            cx.prepared = None;
2791            cx.min_content = None;
2792            cx.cache = None;
2793            cx.baseline = None;
2794            cx.same_lines = None;
2795            cx.no_ahead = false;
2796            cx.laid_out = None;
2797            if let Some(field) = &mut cx.field {
2798                field.prepared = None;
2799                field.cache = None;
2800            }
2801            self.layout.mark_dirty(layout);
2802            self.needs_layout = true;
2803            if self.nodes[key as usize].kind == Kind::Text {
2804                self.queue_text(key);
2805            } else {
2806                // The platform resolves the input's font again.
2807                self.mark(key, dirty::INPUT);
2808            }
2809        }
2810    }
2811
2812    /// The platform's views must get everything again, as new views do, and
2813    /// text is measured again: the unit the platform converted the values
2814    /// with changed (Android's density). The views stay, scrolled where they
2815    /// are.
2816    pub fn remount(&mut self) {
2817        self.fonts_changed();
2818        let keys: Vec<Key> = self
2819            .nodes
2820            .iter()
2821            .filter(|(_, n)| n.created)
2822            .map(|(k, _)| k as Key)
2823            .collect();
2824        for key in keys {
2825            let flags = self.mount_state(key);
2826            self.mark(key, flags);
2827            let node = &mut self.nodes[key as usize];
2828            if let Some(root) = node.root.as_mut() {
2829                root.laid_out = None;
2830            }
2831            // A scroll view keeps where it is scrolled to: its content size
2832            // goes again as it is, not as a first one (which would put a
2833            // right to left one at its right end). A new size from the
2834            // layout below replaces it ([`Self::set_scroll_content`]).
2835            let id = node.id;
2836            if let Some(scroll) = node.scroll.as_mut()
2837                && let Some(size) = scroll.content
2838            {
2839                scroll.content_item = Some((self.batches, self.mount.len()));
2840                self.mount.push(MountItem::ScrollContent { id, size });
2841            }
2842            if let Some(layout) = node.layout {
2843                // Every frame is sent again.
2844                self.layout.mark_dirty(layout);
2845            }
2846            // Replay pixel-based sticky state without clearing the lists'
2847            // bookkeeping (which would restack their existing cells).
2848            // If layout changes the logical ranges, its later item wins.
2849            let ranges = self.sticky_ranges(key);
2850            if !ranges.is_empty() {
2851                self.mount.push(MountItem::StickyCells {
2852                    id,
2853                    cells: ranges
2854                        .into_iter()
2855                        .map(|r| StickyCell {
2856                            cell: r.cell,
2857                            start: Points(r.start),
2858                            end: Points(r.end),
2859                            offset: r.offset,
2860                        })
2861                        .collect(),
2862                });
2863            }
2864        }
2865        self.needs_layout = true;
2866    }
2867
2868    /// A paste into input `id` (`onPaste`): its files larger than the
2869    /// input's `pasteMaxSize` go to [`crate::PasteEvent::too_large`],
2870    /// whichever platform read them, so every platform gives the app the
2871    /// same files.
2872    pub fn limit_paste(&self, id: NodeId, payload: &mut EventPayload) {
2873        let EventPayload::Paste(paste) = payload else {
2874            return;
2875        };
2876        let max = self
2877            .key(id)
2878            .ok()
2879            .and_then(|key| self.nodes[key as usize].input.as_ref())
2880            .and_then(|input| input.config.paste_max_size);
2881        if let Some(max) = max {
2882            paste.limit_files(max);
2883        }
2884    }
2885
2886    /// The user edited input `id` (before JS sees the edit): keeps the text
2887    /// for layout and for stale-value detection.
2888    pub fn input_changed(&mut self, id: NodeId, text: &str, count: u32) {
2889        let Ok(key) = self.key(id) else { return };
2890        let Some(input) = self.nodes[key as usize].input.as_mut() else {
2891            return;
2892        };
2893        input.count = count;
2894        if input.value != text {
2895            input.value.clear();
2896            input.value.push_str(text);
2897            self.measure_input(key);
2898        }
2899    }
2900
2901    /// An input method composes in input `id`: `shown` is what the input
2902    /// shows meanwhile (its text with the composition at the caret), `None`
2903    /// once the composition ends. The input is measured with it, so it
2904    /// grows as the composition wraps; its value and edit count stay as
2905    /// they are (the platform reports the committed text as an edit).
2906    pub fn input_composing(&mut self, id: NodeId, shown: Option<&str>) {
2907        let Ok(key) = self.key(id) else { return };
2908        let Some(input) = self.nodes[key as usize].input.as_mut() else {
2909            return;
2910        };
2911        if input.composing.as_deref() == shown {
2912            return;
2913        }
2914        input.composing = shown.map(str::to_owned);
2915        self.measure_input(key);
2916    }
2917
2918    /// Applies one op from JS.
2919    pub fn apply(&mut self, op: Op) -> Result<(), ApplyError> {
2920        let _entered = self.components.runtime.enter();
2921        // Ops on a component's host go to its component, calls of a UI
2922        // set's modules to the module; the components learn whether JS
2923        // listens to the back button and JS's shortcuts even before one
2924        // mounts, so a component's own join them rather than replace them.
2925        if self.components.instances.is_empty()
2926            && !matches!(
2927                op,
2928                Op::Command {
2929                    command: Command::Native { .. },
2930                    ..
2931                } | Op::Listen {
2932                    id: ROOT_ID,
2933                    event: EventKind::BackPress | EventKind::BackProgress | EventKind::KeyCommand,
2934                    ..
2935                } | Op::SetProp {
2936                    id: ROOT_ID,
2937                    prop: Prop::Keymap(_),
2938                }
2939            )
2940        {
2941            return self.apply_op(op);
2942        }
2943        match self.intercept(op)? {
2944            Some(op) => self.apply_op(op),
2945            None => Ok(()),
2946        }
2947    }
2948
2949    /// Applies one op as is (also for the nodes components expand).
2950    fn apply_op(&mut self, op: Op) -> Result<(), ApplyError> {
2951        if !self.runs.is_empty()
2952            && let Op::Evaluate { id, .. }
2953            | Op::Draw { id, .. }
2954            | Op::SetStyle { id, .. }
2955            | Op::SetProp { id, .. }
2956            | Op::Listen { id, .. }
2957            | Op::Placeholder { id }
2958            | Op::Command { id, .. } = op
2959        {
2960            self.materialize_run(id)?;
2961        }
2962        match op {
2963            Op::Evaluate {
2964                id,
2965                call,
2966                script,
2967                timeout,
2968            } => {
2969                self.start_js_web_evaluation(id, call, script, timeout);
2970                Ok(())
2971            }
2972            Op::RenderCanvas { call, request } => {
2973                self.start_js_canvas_render(call, *request);
2974                Ok(())
2975            }
2976            Op::Rust(op) => {
2977                self.run_rust(op);
2978                Ok(())
2979            }
2980            Op::Create { id, tag } => self.create(id, tag),
2981            Op::CreateText { id, text } => {
2982                let idx = id as usize;
2983                if self.slots.contains(idx) || self.runs.contains_key(&id) {
2984                    return Err(ApplyError::DuplicateNode(id));
2985                }
2986                self.check_id_range(id)?;
2987                if self.fold_runs {
2988                    if self.nodes.len().saturating_add(self.runs.len()) >= self.max_nodes {
2989                        return Err(ApplyError::TooManyNodes(self.max_nodes));
2990                    }
2991                    self.runs.insert(
2992                        id,
2993                        Run {
2994                            text,
2995                            block: NO_KEY,
2996                        },
2997                    );
2998                    self.admitted_id_extent = self.admitted_id_extent.max(idx.saturating_add(1));
2999                    return Ok(());
3000                }
3001                let key = self.alloc(id, Kind::RawText)?;
3002                self.nodes[key as usize].text = text;
3003                Ok(())
3004            }
3005            Op::SetText { id, text } => {
3006                if let Some(run) = self.runs.get_mut(&id) {
3007                    if run.text != text {
3008                        run.text = text;
3009                        let block = run.block;
3010                        if block != NO_KEY {
3011                            self.mark_text_block(block);
3012                        }
3013                    }
3014                    return Ok(());
3015                }
3016                let key = self.key(id)?;
3017                let node = &mut self.nodes[key as usize];
3018                if node.text != text {
3019                    node.text = text;
3020                    if node.inline {
3021                        self.mark_text_block(key);
3022                    }
3023                }
3024                Ok(())
3025            }
3026            Op::SetStyle { id, style, patch } => self.set_inline_style(id, style, patch),
3027            Op::SetProp { id, prop } => {
3028                let role = matches!(
3029                    prop,
3030                    Prop::Accessibility(
3031                        AccessibilityProp::Role(_)
3032                            | AccessibilityProp::Label(_)
3033                            | AccessibilityProp::State(_)
3034                    ) | Prop::Scrollbar(_)
3035                        | Prop::Horizontal(_)
3036                );
3037                let result = self.set_prop(id, prop);
3038                if role && let Ok(key) = self.key(id) {
3039                    self.sync_grid_role(key);
3040                }
3041                result
3042            }
3043            Op::Listen { id, event, enabled } => {
3044                let key = self.key(id)?;
3045                let node = &mut self.nodes[key as usize];
3046                let before = node.events;
3047                node.events.set(event, enabled);
3048                if PRESSES.contains(&event) || HANDLED.contains(&event) {
3049                    self.sync_grid_role(key);
3050                }
3051                if event == EventKind::Layout && enabled && !before.contains(event) {
3052                    self.report_frame(key);
3053                }
3054                let node = &self.nodes[key as usize];
3055                let key_events = matches!(event, EventKind::KeyDown | EventKind::KeyUp);
3056                if node.events != before {
3057                    let relink = node.inline && (pressable(before) || pressable(node.events));
3058                    let overlay_listeners = node.is_overlay()
3059                        && matches!(event, EventKind::PressOutside | EventKind::Cancel);
3060                    self.mark(key, dirty::EVENTS);
3061                    if overlay_listeners {
3062                        self.dirty_overlay_listeners();
3063                    }
3064                    if key_events {
3065                        self.key_ancestry_dirty = true;
3066                    }
3067                    // Pressable spans are part of their block's text.
3068                    if relink {
3069                        self.mark_text_block(key);
3070                    }
3071                }
3072                // A list in its parent's viewport scrolls with the view
3073                // around it: its own scroll events never come.
3074                if enabled
3075                    && matches!(
3076                        event,
3077                        EventKind::Scroll
3078                            | EventKind::Refresh
3079                            | EventKind::ScrollEnd
3080                            | EventKind::ScrollDragStart
3081                            | EventKind::ScrollDragEnd
3082                            | EventKind::MomentumStart
3083                            | EventKind::MomentumEnd
3084                    )
3085                    && self.nodes[key as usize]
3086                        .list
3087                        .as_ref()
3088                        .is_some_and(|l| l.parent)
3089                {
3090                    self.warn_ignored(key);
3091                }
3092                Ok(())
3093            }
3094            Op::Insert {
3095                parent,
3096                child,
3097                before,
3098            } => self.insert(parent, child, before),
3099            Op::Remove { parent, child } => {
3100                let parent = self.key(parent)?;
3101                if let Some(run) = self.runs.get(&child) {
3102                    if run.block != parent {
3103                        return Err(ApplyError::NotAChild(child));
3104                    }
3105                    self.unfold_run(child);
3106                    return Ok(());
3107                }
3108                let child = self.key(child)?;
3109                if self.nodes[child as usize].parent != parent {
3110                    return Err(ApplyError::NotAChild(self.nodes[child as usize].id));
3111                }
3112                self.detach(child);
3113                Ok(())
3114            }
3115            Op::Release { id } => self.release(id),
3116            Op::Placeholder { id } => {
3117                let key = self.key(id)?;
3118                self.placeholder(key);
3119                Ok(())
3120            }
3121            Op::Animation(op) => {
3122                // A view culled for where its transform may take it may
3123                // reach further now (`cull.rs`).
3124                if self.reach.apply(&op) && !self.culling.is_empty() {
3125                    self.cull_dirty = true;
3126                }
3127                self.mount.push(MountItem::Animation(op));
3128                Ok(())
3129            }
3130            Op::Draw { id, mut drawing } => {
3131                let key = self.key(id)?;
3132                if self.nodes[key as usize].kind != Kind::Canvas {
3133                    return Ok(());
3134                }
3135                self.check_canvas_images(&mut drawing);
3136                let node = &mut self.nodes[key as usize];
3137                let slots_changed = node
3138                    .drawing
3139                    .as_ref()
3140                    .map_or(!drawing.slots.is_empty(), |d| d.slots != drawing.slots);
3141                if node.drawing.as_deref() == Some(&*drawing) {
3142                    return Ok(());
3143                }
3144                // An empty drawing on a canvas that has drawn nothing shows
3145                // nothing new (a component's canvas before its first layout).
3146                if node.drawing.is_none() && drawing.ops.is_empty() && drawing.nodes.is_empty() {
3147                    return Ok(());
3148                }
3149                // Whether the view draws its background (it does not where
3150                // the drawing fills with it).
3151                let background_moved = node.drawing.as_ref().is_some_and(|d| d.paints_background())
3152                    != drawing.paints_background();
3153                // A drawing fitting a view box lays its canvas out at its
3154                // natural size, as an image.
3155                let natural = drawing.fit().map(|fit| fit.size);
3156                if node
3157                    .drawing
3158                    .as_ref()
3159                    .and_then(|d| d.fit())
3160                    .map(|fit| fit.size)
3161                    != natural
3162                    && let Some(layout) = node.layout
3163                {
3164                    self.layout
3165                        .set_node_context(layout, natural.map(|n| LeafContext::Image(Some(n))));
3166                    self.layout.mark_dirty(layout);
3167                    self.needs_layout = true;
3168                }
3169                let node = &mut self.nodes[key as usize];
3170                node.drawing = Some(Arc::from(drawing));
3171                let flags = dirty::CANVAS
3172                    | if slots_changed { dirty::ANIMATION } else { 0 }
3173                    | if background_moved { dirty::VIEW } else { 0 };
3174                self.mark(key, flags);
3175                Ok(())
3176            }
3177            Op::Command {
3178                id: crate::ROOT_ID,
3179                command: Command::LayoutAnimation(animation),
3180            } => {
3181                self.layout_animation = Some(animation);
3182                Ok(())
3183            }
3184            // Sent to a node: the frames its change moves.
3185            Op::Command {
3186                id,
3187                command: Command::LayoutAnimation(animation),
3188            } => {
3189                self.key(id)?;
3190                if let Some(transition) = animation.update {
3191                    self.scope_layout_animation(id, transition);
3192                }
3193                Ok(())
3194            }
3195            Op::Command {
3196                id: crate::ROOT_ID,
3197                command: Command::SetStatusBar(patch),
3198            } => {
3199                self.components.status_bars.set_base(patch);
3200                Ok(())
3201            }
3202            // JS's responder blocks native scroll views as the components'
3203            // does: the core sends both sides' blocks.
3204            Op::Command {
3205                id,
3206                command: Command::SetJsResponder { block },
3207            } => {
3208                self.key(id)?;
3209                self.block_native(touch::Side::Js, block.then_some(id));
3210                Ok(())
3211            }
3212            Op::Command {
3213                id,
3214                command: Command::CancelPress,
3215            } => {
3216                self.key(id)?;
3217                self.cancel_press(id);
3218                Ok(())
3219            }
3220            Op::Command {
3221                command: Command::ClearJsResponder,
3222                ..
3223            } => {
3224                self.block_native(touch::Side::Js, None);
3225                Ok(())
3226            }
3227            // A released node: no layout, but the call is answered.
3228            Op::Command {
3229                id,
3230                command: Command::Measure { call },
3231            } if self.key(id).is_err() => {
3232                self.answer_measure(id, call);
3233                Ok(())
3234            }
3235            Op::Command {
3236                id,
3237                command: Command::MeasureScrollPosition { call },
3238            } if self.key(id).is_err() => {
3239                self.answer_scroll_position(id, call);
3240                Ok(())
3241            }
3242            // A window's attributes go into its record, sent once per
3243            // commit; opening one is checked and resolved here.
3244            Op::Command {
3245                id,
3246                command: Command::Desktop(desktop),
3247            } if desktop.is_core_handled() => {
3248                self.key(id)?;
3249                self.window_command(id, *desktop, false);
3250                Ok(())
3251            }
3252            Op::Command { id, command } => {
3253                self.key(id)?;
3254                self.commands.push((id, command));
3255                Ok(())
3256            }
3257        }
3258    }
3259
3260    /// A command about window `id` (its root node): attributes join its
3261    /// record ([`Core::flush_windows`] sends what changed), opening one is
3262    /// checked against the capabilities and resolved, a placement is fitted
3263    /// on the displays there are.
3264    fn window_command(
3265        &mut self,
3266        id: NodeId,
3267        command: crate::desktop::DesktopCommand,
3268        launch: bool,
3269    ) {
3270        use crate::desktop::{
3271            DesktopCommand, WindowPlacement, WindowRequest,
3272            window::{WindowRecord, placement_key},
3273        };
3274        match command {
3275            // The quit mode reaches past the app's view, as quitting does:
3276            // a sandboxed app without `application` keeps the platform's.
3277            DesktopCommand::SetQuitMode(_) if !self.access.allows_application() => {
3278                self.deny(
3279                    "the application (its main window, menu, tray, global shortcuts, quitting and restarting) is not granted: add `\"application\": true` to capabilities in nsh.json".into(),
3280                );
3281            }
3282            // nsh.json's launch attributes are the host's, applied before
3283            // the app runs; the app's own sets still need `application`.
3284            DesktopCommand::SetAttributes(_)
3285                if id == crate::ROOT_ID && !launch && !self.access.allows_application() =>
3286            {
3287                self.deny(
3288                    "the application (its main window, menu, tray, global shortcuts, quitting and restarting) is not granted: add `\"application\": true` to capabilities in nsh.json".into(),
3289                );
3290            }
3291            DesktopCommand::Request(WindowRequest::SetPlacement(_))
3292                if id == crate::ROOT_ID && !self.access.allows_application() =>
3293            {
3294                self.deny(
3295                    "the application (its main window, menu, tray, global shortcuts, quitting and restarting) is not granted: add `\"application\": true` to capabilities in nsh.json".into(),
3296                );
3297            }
3298            DesktopCommand::SetAttributes(_) if !self.has_window() => {
3299                log::debug!("window attributes of view {id}: the surface has no window");
3300            }
3301            DesktopCommand::SetAttributes(mut attributes) => {
3302                attributes.sanitize();
3303                let denied = self.access.deny_window_attributes(&mut attributes);
3304                if !denied.is_empty() {
3305                    self.deny(format!(
3306                        "nsh/desktop: the window attributes {} are not granted by capabilities.windows: left as they are",
3307                        denied.join(", ")
3308                    ));
3309                }
3310                // Fitting the content or not lays the window's root out
3311                // again ([`Core::fit_window`]).
3312                if attributes.size_to_content.is_some()
3313                    && let Ok(key) = self.key(id)
3314                    && let Some(layout) = self.nodes[key as usize].layout
3315                {
3316                    self.layout.mark_dirty(layout);
3317                    self.needs_layout = true;
3318                }
3319                self.windows
3320                    .entry(id)
3321                    .or_default()
3322                    .pending
3323                    .merge(&attributes);
3324            }
3325            DesktopCommand::SetQuitMode(mode) => {
3326                self.quit_mode = Some(mode);
3327            }
3328            DesktopCommand::OpenWindow(mut open) => {
3329                let options = &mut open.options;
3330                // `Window.open` checked it already and threw; this guards
3331                // every other way in.
3332                let open_now = self
3333                    .window_ids
3334                    .values()
3335                    .filter(|(node, _)| *node != id && self.key(*node).is_ok())
3336                    .count();
3337                // The first app window of the run inherits nsh.json's
3338                // `"window"` launch defaults and the host's size: the host is
3339                // invisible, so those defaults describe the window the app
3340                // shows first. A later window after every one closed opens
3341                // as it asked, not as the launch defaults say.
3342                if !self.launch_defaults_applied {
3343                    if let Some(defaults) = self.main_window_options.clone() {
3344                        if options.default_size.is_none() {
3345                            options.default_size = defaults.default_size;
3346                        }
3347                        if options.default_position.is_none() {
3348                            options.default_position = defaults.default_position;
3349                        }
3350                        if options.display.is_none() {
3351                            options.display = defaults.display;
3352                        }
3353                        if options.default_mode.is_none() {
3354                            options.default_mode = defaults.default_mode;
3355                        }
3356                        if !options.restore_bounds {
3357                            options.restore_bounds = defaults.restore_bounds;
3358                        }
3359                        let mut attributes = defaults.attributes;
3360                        attributes.merge(&options.attributes);
3361                        options.attributes = attributes;
3362                    }
3363                    if let Some(state) = self.components.environment.window_state {
3364                        if options.default_size.is_none() {
3365                            options.default_size = Some(state.content_bounds.size);
3366                        }
3367                        if options.default_position.is_none() {
3368                            options.default_position =
3369                                Some(crate::desktop::WindowPosition::At(state.bounds.origin));
3370                        }
3371                    }
3372                }
3373                // A released app's implicit first window is the main window
3374                // it always had, not one of its own: no grant to check.
3375                if !open.implicit
3376                    && let Err(message) =
3377                        self.access
3378                            .check_window(options.kind, &options.attributes, open_now)
3379                {
3380                    self.deny(format!("nsh/desktop: {message}: the window does not open"));
3381                    return;
3382                }
3383                // A refused first window does not consume the launch
3384                // defaults: the next admitted window still gets them.
3385                self.launch_defaults_applied = true;
3386                options.attributes.sanitize();
3387                options.attributes =
3388                    crate::desktop::WindowAttributes::resolve(options.kind, &options.attributes);
3389                // `"main"` is a window id like any other: a parent is the
3390                // window the registry has open under that id.
3391                open.parent = options
3392                    .parent
3393                    .as_deref()
3394                    .and_then(|parent| self.window_ids.get(parent).map(|(node, _)| *node));
3395                if options.restore_bounds {
3396                    let _entered = self.components.runtime.enter();
3397                    open.placement = crate::storage::Storage::get_item(&placement_key(&options.id))
3398                        .and_then(|json| serde_json::from_str::<WindowPlacement>(&json).ok())
3399                        .map(|p| self.components.runtime.fit_window_placement(p));
3400                }
3401                let size = open
3402                    .placement
3403                    .map(|p| p.bounds.size)
3404                    .or(options.default_size);
3405                self.windows.insert(
3406                    id,
3407                    WindowRecord::opened(options.attributes.clone(), size, open.implicit),
3408                );
3409                self.window_ids
3410                    .insert(options.id.clone(), (id, options.restore_bounds));
3411                self.key_ancestry_dirty = true;
3412                self.commands.push((
3413                    id,
3414                    Command::Desktop(Box::new(DesktopCommand::OpenWindow(open))),
3415                ));
3416            }
3417            // Saved placements go onto the displays there are now, whichever
3418            // side (Rust or JS) restores them.
3419            DesktopCommand::Request(WindowRequest::SetPlacement(placement)) => {
3420                let placement = self.components.runtime.fit_window_placement(placement);
3421                self.commands.push((
3422                    id,
3423                    Command::Desktop(Box::new(DesktopCommand::Request(
3424                        WindowRequest::SetPlacement(placement),
3425                    ))),
3426                ));
3427            }
3428            other => self.commands.push((id, Command::Desktop(Box::new(other)))),
3429        }
3430    }
3431
3432    /// Sends each window's attributes that changed since the last commit,
3433    /// one command per window; forgets the windows whose root is gone.
3434    fn flush_windows(&mut self) {
3435        if self.windows.is_empty() {
3436            return;
3437        }
3438        let had_windows = !self.window_ids.is_empty();
3439        let gone: Vec<NodeId> = self
3440            .windows
3441            .keys()
3442            .copied()
3443            // Released, or out of the tree: a closed window's root that
3444            // something still holds (a development host keeps the mounted
3445            // app for hot updates) is not released yet, but it is gone.
3446            .filter(|&id| {
3447                !self
3448                    .key(id)
3449                    .is_ok_and(|k| id == crate::ROOT_ID || self.nodes[k as usize].parent != NO_KEY)
3450            })
3451            .collect();
3452        let mut closed_implicit = false;
3453        for id in gone {
3454            if let Some(record) = self.windows.remove(&id) {
3455                closed_implicit |= record.implicit;
3456            }
3457            self.window_ids.retain(|_, (node, _)| *node != id);
3458        }
3459        // The last window went: the quit mode decides whether that ends the
3460        // app. The app's own close path has run by now (its root is gone),
3461        // and the core's listeners had their turn (a Rust listener turning
3462        // the mode to `"explicit"` keeps the app running). A JS listener
3463        // runs in a later commit, after this decision: an app that keeps
3464        // running with no windows sets `quitMode: "explicit"` before the
3465        // last close, not from `lastWindowClosed`. A listener that opens a
3466        // window again does so in the next commit, which by then is not the
3467        // last window (with the mode `"explicit"`).
3468        //
3469        // A plain root's implicit main window has no `<Window>` scenes or
3470        // reopen flow of its own: unless the app explicitly chose a quit
3471        // mode, closing it quits on every platform instead of leaving a
3472        // windowless Dock process on macOS.
3473        if had_windows && self.window_ids.is_empty() {
3474            self.last_window_closed();
3475            let mode = self.quit_mode.unwrap_or(if closed_implicit {
3476                crate::desktop::QuitMode::LastWindowClosed
3477            } else {
3478                self.default_quit_mode
3479            });
3480            if mode.quits(self.components.environment.os) {
3481                self.commands.push((
3482                    ROOT_ID,
3483                    Command::Desktop(Box::new(crate::desktop::DesktopCommand::Quit)),
3484                ));
3485            }
3486        }
3487        let mut ids: Vec<NodeId> = self.windows.keys().copied().collect();
3488        ids.sort_unstable();
3489        for id in ids {
3490            let Some(diff) = self.windows.get_mut(&id).and_then(|r| r.take_diff()) else {
3491                continue;
3492            };
3493            // Before the commit's first request to the window, so a window
3494            // shown in the commit that set `activate: false` is not activated.
3495            let at = self
3496                .commands
3497                .iter()
3498                .position(|(to, c)| {
3499                    *to == id
3500                        && matches!(c, Command::Desktop(d)
3501                            if matches!(**d, crate::desktop::DesktopCommand::Request(_)))
3502                })
3503                .unwrap_or(self.commands.len());
3504            self.commands.insert(
3505                at,
3506                (
3507                    id,
3508                    Command::Desktop(Box::new(crate::desktop::DesktopCommand::SetAttributes(
3509                        Box::new(diff),
3510                    ))),
3511                ),
3512            );
3513        }
3514    }
3515
3516    /// A window that fits its content (`sizeToContent`), the main one or
3517    /// one of the app's own: its root was laid out at its content's size on
3518    /// those sides; the window is sized to it when it changes. The platforms do nothing for
3519    /// it but carry out the request.
3520    fn fit_window(&mut self, key: Key, layout: LayoutId) {
3521        let id = self.nodes[key as usize].id;
3522        let Some(record) = self.windows.get_mut(&id) else {
3523            return;
3524        };
3525        let (width, height) = record.fits();
3526        if !width && !height {
3527            record.fitted = None;
3528            return;
3529        }
3530        let laid_out = self.layout.unrounded_layout(layout).size;
3531        let size = crate::geometry::size(
3532            Points(laid_out.width.ceil()),
3533            Points(laid_out.height.ceil()),
3534        );
3535        if record.fitted == Some(size) {
3536            return;
3537        }
3538        record.fitted = Some(size);
3539        self.commands.push((
3540            id,
3541            Command::Desktop(Box::new(crate::desktop::DesktopCommand::Request(
3542                crate::desktop::WindowRequest::SetContentSize {
3543                    width: width.then_some(size.width),
3544                    height: height.then_some(size.height),
3545                },
3546            ))),
3547        ));
3548    }
3549
3550    /// The size of modal `key`'s root view: what the platform reported
3551    /// (`set_root_size`), else, for the root of a window of the app's own,
3552    /// the window's size as the core knows it (its content's with
3553    /// `sizeToContent`, the placement's or `defaultSize`), else a dialog's
3554    /// main window's. `None`: a window whose size only its platform knows,
3555    /// laid out at its content's size until the platform reports it, never
3556    /// at the main window's.
3557    pub(crate) fn root_view_size(&self, key: Key) -> Option<Size<Points>> {
3558        let node = &self.nodes[key as usize];
3559        if let Some(size) = node.root.as_ref().and_then(|r| r.reported) {
3560            return Some(size);
3561        }
3562        if self.window_ids.values().any(|(id, _)| *id == node.id) {
3563            return self.windows.get(&node.id).and_then(|r| r.fitted.or(r.size));
3564        }
3565        Some(self.viewport)
3566    }
3567
3568    /// The window node `key` shows in: the root of the nearest window of
3569    /// the app's own around it, else the main window ([`ROOT_ID`]).
3570    pub(crate) fn window_of(&self, key: Key) -> NodeId {
3571        if self.window_ids.is_empty() {
3572            return crate::ROOT_ID;
3573        }
3574        let mut k = self.nodes[key as usize].parent;
3575        while k != NO_KEY {
3576            let n = &self.nodes[k as usize];
3577            if n.kind == Kind::Modal && self.window_ids.values().any(|(node, _)| *node == n.id) {
3578                return n.id;
3579            }
3580            k = n.parent;
3581        }
3582        crate::ROOT_ID
3583    }
3584
3585    /// The surface is in a window whose attributes its platform applies: a
3586    /// desktop's (the OSes `nsh/desktop`'s `isAvailable` answers for), or
3587    /// a browser's page, whose title is the main window's. A mobile surface
3588    /// is a view in its app's screen: window attributes have nothing to
3589    /// apply to there, so none are kept or sent.
3590    fn has_window(&self) -> bool {
3591        let os = self.components.environment.os;
3592        os.is_desktop() || os == crate::platform::Os::Web
3593    }
3594
3595    /// Keeps the placement of window `id` (its root node) a platform
3596    /// reported, when the app asked to restore its bounds. A main window
3597    /// hidden since launch (`defaultVisible: false`) is not where the user
3598    /// left it until it first shows: it has yet to take the mode it opens
3599    /// in, and GTK has yet to size it. Once it has shown, its reports are,
3600    /// hidden ones too: one hidden right after a move or resize reports
3601    /// where it was left only then. (A development host's reload starts a
3602    /// new core: there such a window shown before the reload counts as
3603    /// hidden since launch until it shows again.)
3604    pub(crate) fn keep_window_placement(
3605        &mut self,
3606        id: NodeId,
3607        state: &crate::desktop::WindowState,
3608    ) {
3609        if id == crate::ROOT_ID {
3610            self.main_shown |= state.visible;
3611            if !self.main_shown {
3612                return;
3613            }
3614        }
3615        let key = if id == crate::ROOT_ID {
3616            self.keep_main_placement
3617                .then(|| crate::desktop::window::placement_key("main"))
3618        } else {
3619            self.window_ids
3620                .iter()
3621                .find(|(_, (node, keep))| *node == id && *keep)
3622                .map(|(key, _)| crate::desktop::window::placement_key(key))
3623        };
3624        let Some(key) = key else {
3625            return;
3626        };
3627        if let Ok(json) = serde_json::to_string(&state.placement) {
3628            let _entered = self.components.runtime.enter();
3629            if crate::storage::Storage::get_item(&key).as_deref() != Some(json.as_str()) {
3630                let _ = crate::storage::Storage::set_item(key, json);
3631            }
3632        }
3633    }
3634
3635    /// The bottom edge of the logical root's in-flow children, in surface points.
3636    ///
3637    /// Read after [`Self::commit`] for settled geometry, from the same frames
3638    /// reported to layout listeners. Detached layout roots (such as overlays
3639    /// and modals) and fixed or absolutely positioned children do not contribute.
3640    /// `None` means there is no laid-out in-flow content. This does not run an
3641    /// intrinsic-size pass or change the viewport.
3642    pub fn content_height(&self) -> Option<Points> {
3643        self.nodes[self.root as usize]
3644            .children
3645            .iter()
3646            .filter_map(|&key| {
3647                let node = &self.nodes[key as usize];
3648                let layout = node.layout?;
3649                if node.is_layout_root()
3650                    || self.layout.displays_none(layout)
3651                    || matches!(
3652                        self.layout.style(layout).position,
3653                        Position::Absolute | Position::Fixed
3654                    )
3655                    || node.frame.origin.y.0.is_nan()
3656                {
3657                    return None;
3658                }
3659                Some(node.frame.origin.y.0 + node.frame.size.height.0)
3660            })
3661            .reduce(f32::max)
3662            .map(Points)
3663    }
3664
3665    /// Finishes a turn: rebuilds text, runs layout, updates lists and
3666    /// returns the mount items, or `None` when nothing changed.
3667    pub fn commit(&mut self) -> Option<MountBatch> {
3668        // The last round's events were dispatched: a geometry no one took
3669        // is stale (its node went).
3670        self.geometries.clear();
3671        // The downloads' file work and deadlines: their events and
3672        // commands go out with this commit.
3673        self.poll_downloads();
3674        // JS has handled the events taken before this commit and its ops
3675        // are applied: what waited for that sees the app's props, and what
3676        // it changes renders with them.
3677        if self.components.executor.has_due_answers() {
3678            self.run_answers();
3679        }
3680        self.pace_commit();
3681        self.sync_quit_requests();
3682        self.commit_round();
3683        // The components' own lists bind the cells the layout asked for
3684        // here, and lay out again (JS's lists ask JS, through the engine);
3685        // a list in its parent's viewport that changed length lays the
3686        // page out again, so it settles in this batch.
3687        // Views watching scroll views they did not make hear what this
3688        // round moved, and what they change goes out in this batch too.
3689        for _ in 0..MAX_VIRTUAL_ROUNDS {
3690            let watched = self.sync_watches();
3691            // A built-in bar asked for while this round rendered (the app
3692            // set its theme) is made in this batch too.
3693            if !self.bind_virtual_lists()
3694                && !std::mem::take(&mut self.extent_changed)
3695                && !watched
3696                && !std::mem::take(&mut self.cull_made)
3697                && !std::mem::take(&mut self.placeholders_resized)
3698                && self.scrollbars_pending.is_empty()
3699            {
3700                break;
3701            }
3702            self.commit_round();
3703        }
3704        if !self.outer_asked.is_empty() {
3705            self.send_outer_scrolls();
3706        }
3707        // What mounted in the rounds listens already.
3708        if self.sync_quit_requests() {
3709            self.commit_round();
3710        }
3711        self.split_scoped_frames();
3712        self.mark_shader_inputs();
3713        if !self.transition_starts.is_empty() {
3714            // Before the changes they are about: the platform pictures what
3715            // showed before them.
3716            let starts = std::mem::take(&mut self.transition_starts);
3717            self.mount.splice(0..0, starts);
3718        }
3719        if std::mem::take(&mut self.tab_places_stale) && !self.overlays.is_empty() {
3720            self.order_overlays_for_tab();
3721        }
3722        if std::mem::take(&mut self.tree_order_changed) {
3723            let mut order = Vec::new();
3724            let mut pending = vec![self.root];
3725            let mut cells = Vec::new();
3726            while let Some(key) = pending.pop() {
3727                let node = &self.nodes[key as usize];
3728                if node.created {
3729                    order.push(node.id);
3730                }
3731                match &node.list {
3732                    // A list recycles its cells, so they are not in their
3733                    // rows' order among its children: they go as they are
3734                    // on screen, along the list's axis, then across it.
3735                    Some(list) if node.children.len() > 1 => {
3736                        cells.clear();
3737                        cells.extend_from_slice(&node.children);
3738                        let start = |k: &Key| {
3739                            let at = self.nodes[*k as usize].frame.origin;
3740                            if list.horizontal {
3741                                (at.x.0, at.y.0)
3742                            } else {
3743                                (at.y.0, at.x.0)
3744                            }
3745                        };
3746                        cells.sort_by(|a, b| {
3747                            let (a, b) = (start(a), start(b));
3748                            a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1))
3749                        });
3750                        pending.extend(cells.iter().rev().copied());
3751                    }
3752                    _ => pending.extend(node.children.iter().rev().copied()),
3753                }
3754            }
3755            self.mount.push(MountItem::TreeOrder(order));
3756        }
3757        if self.mount.is_empty() || matches!(self.mount[..], [MountItem::LayoutAnimation(_)]) {
3758            self.mount.clear();
3759            None
3760        } else {
3761            self.batches += 1;
3762            Some(MountBatch {
3763                items: std::mem::take(&mut self.mount),
3764            })
3765        }
3766    }
3767
3768    /// Include logical document order in mount batches for a platform's focus traversal.
3769    /// Native sibling insertions describe paint order and can differ because of `zIndex`.
3770    pub fn set_tree_order_tracking(&mut self, enabled: bool) {
3771        self.track_tree_order = enabled;
3772        self.tree_order_changed = enabled;
3773    }
3774
3775    /// Mount the states views show as parts of a control
3776    /// ([`MountItem::ProjectStates`]: a list's highlighted option, the
3777    /// code input's next cell) for a platform that marks them itself, as
3778    /// a terminal does: elsewhere the app's classes alone show them. Set
3779    /// before the first commit.
3780    pub fn set_projected_state_mounting(&mut self, enabled: bool) {
3781        self.mount_projected = enabled;
3782    }
3783
3784    /// One round of a commit: views, layout, lists, commands, into the
3785    /// mount items.
3786    fn commit_round(&mut self) {
3787        // Pointers components pass on, onto the layout they were over.
3788        if !self.components.hovers.is_empty() {
3789            self.pass_hovers();
3790        }
3791        // The built-in scroll bars that come, rendered with the rest.
3792        if !self.scrollbars_pending.is_empty() {
3793            self.sync_scrollbars();
3794        }
3795        // The views' patches and the views to make first.
3796        self.render_components();
3797        // The children that moved, the app's and those the components just
3798        // placed, styled at their places before anything reads their styles
3799        // (`position: fixed`, the color they pass on).
3800        self.flush_positions();
3801        self.prepare_reveals();
3802        // The focus reported since, after the components made and released
3803        // what they did: one change of the chain, the views both chains
3804        // share untouched.
3805        let visible_moved = std::mem::take(&mut self.focus_visible_moved);
3806        // A blur no focus followed yet waits for the frame (`blur_held`).
3807        let held = self.blur_held && self.focus.is_none() && !self.focus_chain.is_empty();
3808        if self.focus_moved && !held {
3809            self.update_focus_within();
3810            self.update_focus_visible();
3811            // The hints the focus came to or left.
3812            if !self.overlays.is_empty() {
3813                self.focus_hints();
3814            }
3815        } else if visible_moved {
3816            // A key typed with the focus where it is shows its ring, and no
3817            // hint: a hint shows only for a focus the keyboard moved.
3818            self.update_focus_visible();
3819        }
3820        self.sync_pointer_keymap();
3821        self.sync_colors();
3822        self.sync_ch();
3823        self.sync_fixed();
3824        self.sync_overlays();
3825        if std::mem::take(&mut self.key_ancestry_dirty) {
3826            self.sync_key_parents();
3827            self.sync_key_contents();
3828        }
3829        // The rows holding the focus or an open overlay stay rendered,
3830        // before the lists update their windows.
3831        if self.focus.is_some() || !self.overlays.is_empty() || !self.kept_lists.is_empty() {
3832            self.sync_kept();
3833        }
3834        self.sync_back();
3835        self.sync_back_progress();
3836        self.sync_keys();
3837        // Platforms animate the frames, insertions and removals that follow
3838        // in the batch; ops may already have queued some.
3839        self.sync_env();
3840        if let Some(animation) = self.layout_animation.take() {
3841            self.note_list_motion(animation);
3842            self.mount.insert(0, MountItem::LayoutAnimation(animation));
3843        }
3844        self.flush_pointer_events();
3845        if !self.relators.is_empty() {
3846            self.sync_relations();
3847        }
3848        self.flush_dirty();
3849        let relayout = self.needs_layout;
3850        if relayout {
3851            self.needs_layout = false;
3852            let settling = std::mem::take(&mut self.resize_settling);
3853            let anchors = if settling || self.measure_cache.resizing.is_some() {
3854                self.resize_anchors()
3855            } else {
3856                Vec::new()
3857            };
3858            if self.measure_cache.resizing.is_some() {
3859                self.mark_near_screen();
3860            }
3861            // Boundaries first: what they give back may dirty what is
3862            // around them, laid out next.
3863            let relaid = self.relayout_boundaries();
3864            // Only walk the main tree when it was laid out again (a change
3865            // inside a list cell leaves it untouched).
3866            if self.layout_main() {
3867                let root = self.root;
3868                let children = std::mem::take(&mut self.nodes[root as usize].children);
3869                for &child in &children {
3870                    if !self.nodes[child as usize].is_layout_root() {
3871                        self.emit_frames(child);
3872                    }
3873                }
3874                self.nodes[root as usize].children = children;
3875            }
3876            // Screens and modals, then list cells (lists may live in them).
3877            self.layout_roots();
3878            self.layout_cells();
3879            for key in relaid {
3880                self.emit_frames(key);
3881            }
3882            self.keep_resize_anchors(anchors);
3883        }
3884        // Placeholders sized again are laid out again, in another round,
3885        // before culling looks at them.
3886        let sized = relayout && !self.placeholders.is_empty() && self.size_placeholders();
3887        if sized {
3888            self.cull_dirty = true;
3889        } else if self.cull_dirty || (relayout && !self.culling.is_empty()) {
3890            // The views a scroll view culls that came within its window.
3891            self.sync_culled();
3892        }
3893        self.update_lists(relayout);
3894        // A list gives the views in a cell their frames as it places the
3895        // cell, after culling looked: a scroll view made in a cell in this
3896        // round had no frame then, so what it culls waited, and nothing
3897        // would look at it again before the next layout or scroll (a row
3898        // bound as a scroll came to rest kept its scroll views empty).
3899        // Not while placeholders wait for their layout, as above.
3900        if std::mem::take(&mut self.cells_framed) && !sized && !self.culling.is_empty() {
3901            self.sync_culled();
3902        }
3903        if !self.slop_moved.is_empty() {
3904            self.update_slop_overflow();
3905        }
3906        // Views that waited for the budget, once lists placed their cells
3907        // (`pace.rs`).
3908        if !self.pace.waiting.is_empty() {
3909            self.sync_paced();
3910        }
3911        // After every frame of the round: what followers follow is placed.
3912        self.place_followers(relayout);
3913        if !self.decorated.is_empty() {
3914            self.layout_scrollbars();
3915        }
3916        if !self.overlays.is_empty() {
3917            self.place_overlays();
3918        }
3919        if !self.fitted_pending.is_empty() {
3920            self.send_fitted();
3921        }
3922        self.flush_text();
3923        // What this turn's status bar settings add up to, once.
3924        self.sync_status_bars();
3925        if let Some(config) = self.components.status_bars.take_changed() {
3926            self.commands
3927                .push((crate::ROOT_ID, Command::StatusBar(config)));
3928        }
3929        self.sync_orientations();
3930        // Each window's attributes, once per commit.
3931        self.flush_windows();
3932        // The components' measurements, with this commit's layout as JS's.
3933        for (id, answer) in std::mem::take(&mut self.components.measures) {
3934            answer.borrow_mut().deliver(self.measure(id));
3935        }
3936        for (id, answer) in std::mem::take(&mut self.components.scroll_positions) {
3937            answer.borrow_mut().deliver(self.list_scroll_position(id));
3938        }
3939        // And their transitions' time, with this commit's styles.
3940        for (id, answer) in std::mem::take(&mut self.components.transition_times) {
3941            answer.borrow_mut().deliver(self.transition_time(id));
3942        }
3943        // And their texts, with this commit's.
3944        for (id, answer) in std::mem::take(&mut self.components.text_contents) {
3945            answer.borrow_mut().deliver(self.text_content(id));
3946        }
3947        // Into the scroll commands of the scroll views around, in place,
3948        // with this commit's layout and the scrolls of the commands before.
3949        if self
3950            .commands
3951            .iter()
3952            .any(|(_, c)| matches!(c, Command::Reveal(_)))
3953        {
3954            let mut projected = Vec::new();
3955            for (id, command) in std::mem::take(&mut self.commands) {
3956                let commands = match command {
3957                    Command::Reveal(options) => self.reveal_scrolls(id, options, &projected),
3958                    command => vec![(id, command)],
3959                };
3960                for (id, command) in commands {
3961                    if let Some(to) = self.scrolled_to(id, &command) {
3962                        projected.push((id, to));
3963                    }
3964                    self.commands.push((id, command));
3965                }
3966            }
3967        }
3968        // Presses a component passes on, onto this commit's layout.
3969        for (id, press, answer) in std::mem::take(&mut self.components.presses) {
3970            let target = self.press_target(id, press.page_position);
3971            if let Some((node, position)) = target {
3972                self.events.push(crate::element::JsEvent::Event(
3973                    node,
3974                    EventKind::Press,
3975                    EventPayload::Press(crate::PressEvent { position, ..press }),
3976                ));
3977            }
3978            answer.borrow_mut().deliver(target.is_some());
3979        }
3980        // The downloads' listeners as this round's final masks leave them:
3981        // a web view left with neither of them cancels what it holds, and
3982        // the cancel commands go out with this batch.
3983        self.sync_download_listeners();
3984        self.focus_opened_modals();
3985        // A focus given back yields to one moved out of the popup anywhere
3986        // in this commit (in this round, or an earlier one's items),
3987        // whichever came first: the app's choice outranks a popup's
3988        // closing. A move inside the popup (its items' keys typed ahead of
3989        // the choice) or to a view that is gone does not.
3990        if let Some((id, from, past)) = self.focus_back.take() {
3991            let origin = self
3992                .focus_origins
3993                .iter()
3994                .position(|&(to, _)| to == id)
3995                .map(|i| self.focus_origins.swap_remove(i).1);
3996            let from = from.and_then(|from| self.key(from).ok());
3997            let moved_out = |to: NodeId| {
3998                self.key(to)
3999                    .is_ok_and(|key| from.is_none_or(|from| !self.is_ancestor(from, key)))
4000            };
4001            let moved = self
4002                .commands
4003                .iter()
4004                .any(|(to, c)| matches!(c, Command::Focus) && moved_out(*to))
4005                || self.mount.iter().any(|m| {
4006                    matches!(
4007                        m,
4008                        MountItem::Command {
4009                            id: to,
4010                            command: Command::Focus,
4011                        } if moved_out(*to)
4012                    )
4013                });
4014            // A Tab that closed the popup moves on from its trigger,
4015            // however the popup opened: the key says where the focus goes.
4016            let past = past.filter(|_| !moved).and_then(|forward| {
4017                let key = self.key(id).ok()?;
4018                Some(self.tab_neighbor(key, forward, from).unwrap_or(id))
4019            });
4020            if let Some(to) = past {
4021                self.commands.push((to, Command::Focus));
4022            } else if !moved {
4023                match origin {
4024                    // Opened by the keyboard (or the app after a key): back
4025                    // to the trigger the keyboard opened it from.
4026                    None => self.commands.push((id, Command::Focus)),
4027                    Some(before) if self.press_leaves_focus() => {
4028                        self.focus_back_to_origin(before, from);
4029                    }
4030                    // Elsewhere a press focused the trigger: it takes the
4031                    // focus back, still the pointer's (Escape closing the
4032                    // list a click opened leaves the app's Space to it).
4033                    Some(_) => {
4034                        self.commands.push((id, Command::Focus));
4035                        self.pointer_focus_back = Some(id);
4036                    }
4037                }
4038            }
4039        }
4040        // On laid out views; dropped for views that were never shown.
4041        let mut kept = Vec::new();
4042        for (id, mut command) in std::mem::take(&mut self.commands) {
4043            // Answered here, with this commit's layout (null for views that
4044            // are gone or not shown).
4045            if let Command::Measure { call } = command {
4046                self.answer_measure(id, call);
4047                continue;
4048            }
4049            if let Command::MeasureScrollPosition { call } = command {
4050                self.answer_scroll_position(id, call);
4051                continue;
4052            }
4053            let Ok(key) = self.key(id) else {
4054                // A download command to a node that is gone is dropped; its
4055                // reply timeout settles the session without ever treating
4056                // silence as the writer having stopped.
4057                continue;
4058            };
4059            // A culled view is made for it.
4060            if !self.nodes[key as usize].created && !self.uncull(key) {
4061                continue;
4062            }
4063            let node = &self.nodes[key as usize];
4064            if id != crate::ROOT_ID
4065                && let Some(backend) = &self.window_backend
4066                && let Command::Desktop(desktop) = &command
4067                && desktop.is_window_command()
4068            {
4069                backend.command(id, desktop);
4070                continue;
4071            }
4072            // A list in its parent's viewport not placed in its view yet
4073            // keeps its scroll commands for the update that places it.
4074            if node.list.as_ref().is_some_and(|l| l.parent)
4075                && matches!(
4076                    command,
4077                    Command::ScrollTo { .. }
4078                        | Command::ScrollToIndex { .. }
4079                        | Command::ScrollToEnd { .. }
4080                )
4081            {
4082                kept.push((id, command));
4083                continue;
4084            }
4085            // `Image.getSize` / `prefetch` load what the check granted
4086            // (`Access::media_url`).
4087            if let Command::ImageInfo { id: request, uri } = &mut command {
4088                match self.media_source(uri) {
4089                    Some(granted) => {
4090                        if let Some(url) = granted {
4091                            *uri = url.to_string();
4092                        }
4093                    }
4094                    None => {
4095                        let message = media_not_granted(
4096                            "Image.getSize / prefetch of",
4097                            uri,
4098                            self.base_url.as_deref(),
4099                        );
4100                        self.answer_image_info(*request, Err(message.clone()));
4101                        self.deny(message);
4102                        continue;
4103                    }
4104                }
4105            }
4106            // Menu and tray icons load what the check granted
4107            // (`Access::media_url`), as an `<Image>` does.
4108            if let Command::Desktop(desktop) = &mut command {
4109                self.check_menu_icons(desktop);
4110                if id == crate::ROOT_ID {
4111                    self.remember_app_menu(desktop);
4112                }
4113            }
4114            // Lists resolved theirs in `update_lists`; a scroll view can
4115            // still scroll to its end.
4116            match &command {
4117                Command::SetClipboard(_)
4118                | Command::SetClipboardItem(_)
4119                | Command::ReadClipboard { .. }
4120                | Command::SetClipboardImage(_)
4121                | Command::ReadClipboardImage { .. }
4122                | Command::ReadClipboardFiles { .. }
4123                    if !self.access.allows_clipboard() =>
4124                {
4125                    if let Command::ReadClipboard { id: request, .. }
4126                    | Command::ReadClipboardImage { id: request, .. }
4127                    | Command::ReadClipboardFiles { id: request } = &command
4128                    {
4129                        self.answer_clipboard(*request, components::ClipboardAnswer::default());
4130                    }
4131                    if matches!(
4132                        command,
4133                        Command::SetClipboard(_) | Command::SetClipboardItem(_)
4134                    ) {
4135                        self.answer_clipboard_write(crate::element::ClipboardWrite::Failed);
4136                    }
4137                    self.deny("the clipboard is not granted: add `\"clipboard\": true` to capabilities in nsh.json".into());
4138                    continue;
4139                }
4140                // A clipboard of the embedder's own answers in place of
4141                // the platform's.
4142                Command::SetClipboard(_)
4143                | Command::SetClipboardItem(_)
4144                | Command::ReadClipboard { .. }
4145                | Command::SetClipboardImage(_)
4146                | Command::ReadClipboardImage { .. }
4147                | Command::ReadClipboardFiles { .. }
4148                    if self.clipboard.is_some() =>
4149                {
4150                    let clipboard = self.clipboard.clone().expect("a clipboard");
4151                    match &command {
4152                        Command::SetClipboard(text) => {
4153                            clipboard.set_text(Some(text.clone()));
4154                            self.answer_clipboard_write(crate::element::ClipboardWrite::Written);
4155                        }
4156                        Command::SetClipboardItem(item) => {
4157                            clipboard.set_item(Some(item.clone()));
4158                            self.answer_clipboard_write(crate::element::ClipboardWrite::Written);
4159                        }
4160                        Command::SetClipboardImage(_) => clipboard.set_item(None),
4161                        Command::ReadClipboard {
4162                            id: request,
4163                            has_only,
4164                        } => {
4165                            let text = clipboard.text();
4166                            let answer = components::ClipboardAnswer {
4167                                has: text.is_some(),
4168                                text: text.filter(|_| !has_only),
4169                                ..Default::default()
4170                            };
4171                            self.answer_clipboard(*request, answer);
4172                        }
4173                        Command::ReadClipboardImage { id: request, .. }
4174                        | Command::ReadClipboardFiles { id: request } => {
4175                            self.answer_clipboard(*request, components::ClipboardAnswer::default());
4176                        }
4177                        _ => {}
4178                    }
4179                    continue;
4180                }
4181                // A platform that cannot tell whether the system took a
4182                // write answers it now; the others report it.
4183                Command::SetClipboard(_) | Command::SetClipboardItem(_)
4184                    if !self.components.environment.clipboard_write_result =>
4185                {
4186                    self.answer_clipboard_write(crate::element::ClipboardWrite::Requested);
4187                }
4188                // Checked before the grants: a host may put the name in a
4189                // path or a URL, where `user.x/../admin` leaves `user.*`.
4190                Command::HostCall { name, .. } | Command::HostPost { name, .. } => {
4191                    if let Some(error) = crate::host_channel::refusal(&self.access, name) {
4192                        self.deny(error.to_string());
4193                        if let Command::HostCall { id: call, .. } = command {
4194                            self.answer_host(call, Err(error));
4195                        }
4196                        continue;
4197                    }
4198                }
4199                Command::SendInput(_) if !self.access.allows_web_input() => {
4200                    self.deny("trusted web view input is not granted: add `\"input\": true` to capabilities.webview in nsh.json".into());
4201                    continue;
4202                }
4203                // As a `src` the capability does not allow: the page is
4204                // not loaded, so its headers go nowhere.
4205                Command::Load(load)
4206                    if !self
4207                        .access
4208                        .allows_webview_with(&load.src, self.web_origin(key)) =>
4209                {
4210                    self.deny(not_granted("the web page", &load.src, "webview.hosts"));
4211                    continue;
4212                }
4213                Command::StatusBar(_) if !self.access.allows_status_bar() => {
4214                    self.deny("the status bar is not granted: add `\"statusBar\": true` to capabilities in nsh.json".into());
4215                    continue;
4216                }
4217                // A context menu shows in the app's own view, and the
4218                // windows the app opens are `capabilities.windows`'
4219                // (`Access::check_window`): neither needs `application`. The
4220                // main window, the application menu, the tray, global
4221                // shortcuts and quitting reach past the app's view and do.
4222                // The core-handled window commands (a window's attributes, a
4223                // placement, opening one) are checked where they are applied,
4224                // so that nsh.json's launch attributes reach the main window
4225                // while the app's own sets need `application`. Fitting a
4226                // window's content is the core's own follow-up.
4227                Command::Desktop(desktop)
4228                    if !self.access.allows_application()
4229                        && !desktop.is_core_handled()
4230                        && !matches!(
4231                            **desktop,
4232                            crate::desktop::DesktopCommand::PopupMenu { .. }
4233                                | crate::desktop::DesktopCommand::Request(
4234                                    crate::desktop::WindowRequest::SetContentSize { .. }
4235                                )
4236                        )
4237                        && (id == crate::ROOT_ID || !desktop.is_window_command()) =>
4238                {
4239                    self.deny("the application (its main window, menu, tray, global shortcuts, quitting and restarting) is not granted: add `\"application\": true` to capabilities in nsh.json".into());
4240                    continue;
4241                }
4242                _ => {}
4243            }
4244            let node = &self.nodes[key as usize];
4245            let id = node.id;
4246            match command {
4247                Command::ScrollToEnd { animated } => {
4248                    let Some(content) = node.scroll.as_ref().and_then(|s| s.content) else {
4249                        continue;
4250                    };
4251                    let horizontal = node.scroll.as_ref().is_some_and(|s| s.horizontal);
4252                    let frame = node.frame;
4253                    let (x, y) = if horizontal {
4254                        (
4255                            (content.width - frame.size.width).max(Points::ZERO),
4256                            Points::ZERO,
4257                        )
4258                    } else {
4259                        (
4260                            Points::ZERO,
4261                            (content.height - frame.size.height).max(Points::ZERO),
4262                        )
4263                    };
4264                    command = Command::ScrollTo { x, y, animated };
4265                }
4266                Command::ScrollToIndex { .. } => continue,
4267                _ => {}
4268            }
4269            // Platforms count the scrolls they applied; lists count theirs.
4270            if let Command::ScrollTo { x, y, animated } = command
4271                && self.nodes[key as usize].kind == Kind::Scroll
4272            {
4273                let horizontal = self.nodes[key as usize]
4274                    .scroll
4275                    .as_ref()
4276                    .is_some_and(|s| s.horizontal);
4277                let to = if horizontal { x.0 } else { y.0 };
4278                self.scroll_issued(
4279                    key,
4280                    PendingScroll::To {
4281                        offset: to,
4282                        animated,
4283                    },
4284                );
4285                if let Some(scroll) = self.nodes[key as usize].scroll.as_mut() {
4286                    scroll.target = Some((scroll.issued, (x.0, y.0)));
4287                }
4288            }
4289            self.mount.push(MountItem::Command { id, command });
4290        }
4291        self.commands.append(&mut kept);
4292    }
4293
4294    #[inline]
4295    fn key(&self, id: NodeId) -> Result<Key, ApplyError> {
4296        match self.slots.get(id as usize) {
4297            Some(&k) => Ok(k),
4298            None => Err(ApplyError::UnknownNode(id)),
4299        }
4300    }
4301
4302    fn check_id_range(&self, id: NodeId) -> Result<(), ApplyError> {
4303        if id as usize > self.admitted_id_extent.saturating_add(self.max_nodes) {
4304            return Err(ApplyError::IdOutOfRange(id));
4305        }
4306        Ok(())
4307    }
4308
4309    fn insert_key(&mut self, idx: usize, key: Key) {
4310        self.slots.insert(idx, key);
4311        self.admitted_id_extent = self.admitted_id_extent.max(self.slots.extent());
4312    }
4313
4314    fn alloc(&mut self, id: NodeId, kind: Kind) -> Result<Key, ApplyError> {
4315        let idx = id as usize;
4316        if self.nodes.len().saturating_add(self.runs.len()) >= self.max_nodes {
4317            return Err(ApplyError::TooManyNodes(self.max_nodes));
4318        }
4319        self.check_id_range(id)?;
4320        if self.slots.contains(idx) || self.runs.contains_key(&id) {
4321            return Err(ApplyError::DuplicateNode(id));
4322        }
4323        let key = self.nodes.insert(Node::new(id, kind)) as Key;
4324        self.insert_key(idx, key);
4325        // An overlay's explicit anchor may name this id for the first time.
4326        self.dirty_overlay_listeners();
4327        Ok(key)
4328    }
4329
4330    /// Makes `alias` another name of node `id`: a component whose view's
4331    /// root is another component makes that one on its own host, under a
4332    /// name of its own (the nested component's host), with no node of its
4333    /// own. What the core sends names the node by its own id.
4334    pub(super) fn alias(&mut self, alias: NodeId, id: NodeId) -> Result<(), ApplyError> {
4335        let key = self.key(id)?;
4336        let idx = alias as usize;
4337        self.check_id_range(alias)?;
4338        if self.slots.contains(idx) {
4339            return Err(ApplyError::DuplicateNode(alias));
4340        }
4341        self.insert_key(idx, key);
4342        // An overlay's explicit anchor may name this alias for the first time.
4343        self.dirty_overlay_listeners();
4344        Ok(())
4345    }
4346
4347    /// Whether `id` is another name of a node ([`Self::alias`]).
4348    pub(super) fn is_alias(&self, id: NodeId) -> bool {
4349        self.key(id).is_ok_and(|k| self.nodes[k as usize].id != id)
4350    }
4351
4352    /// Forgets alias `id` (its node stays).
4353    pub(super) fn unalias(&mut self, id: NodeId) {
4354        if self.is_alias(id) {
4355            self.slots.remove(id as usize);
4356            self.dirty_overlay_listeners();
4357        }
4358    }
4359
4360    /// The id node `id` has natively (another for an alias).
4361    pub(super) fn native_id(&self, id: NodeId) -> NodeId {
4362        self.key(id).map_or(id, |k| self.nodes[k as usize].id)
4363    }
4364
4365    fn create(&mut self, id: NodeId, tag: Tag) -> Result<(), ApplyError> {
4366        let kind = Kind::of(tag);
4367        let key = self.alloc(id, kind)?;
4368        let mut custom_layout = None;
4369        if let Some(role) = shader_role(tag) {
4370            self.nodes[key as usize]
4371                .shader
4372                .as_mut()
4373                .expect("a shader node")
4374                .role = role;
4375            if matches!(
4376                role,
4377                crate::shader::ShaderRole::Screen | crate::shader::ShaderRole::ScreenTransition
4378            ) {
4379                // A screen's effect takes no space: the surface is its box.
4380                let mut style = crate::style::unstyled_layout();
4381                style.position = taffy::Position::Absolute;
4382                style.size = taffy::Size {
4383                    width: taffy::Dimension::length(0.0),
4384                    height: taffy::Dimension::length(0.0),
4385                };
4386                custom_layout = Some(style);
4387            }
4388        }
4389        let context = leaf_context(kind);
4390        let layout = match custom_layout {
4391            Some(style) => match context {
4392                Some(context) => self.layout.new_leaf_with_context(style, context),
4393                None => self.layout.new_leaf(style),
4394            },
4395            None => self.layout.new_default_leaf(context),
4396        };
4397        self.layout.set_tag(layout, key);
4398        self.nodes[key as usize].layout = Some(layout);
4399        self.sync_grid_role(key);
4400        self.became(key);
4401        if kind == Kind::WebView && !self.components.environment.web_views {
4402            self.web_view_unavailable(id);
4403        }
4404        Ok(())
4405    }
4406
4407    /// A web view on a platform that shows none fails at once (`onError`
4408    /// with `code` `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`). Always reported:
4409    /// the `onError` listener is set after the node is made.
4410    fn web_view_unavailable(&mut self, id: NodeId) {
4411        self.events.push(crate::element::JsEvent::Event(
4412            id,
4413            EventKind::Error,
4414            EventPayload::Map(vec![
4415                (
4416                    "message",
4417                    PayloadValue::Str("web views are not available on this platform".into()),
4418                ),
4419                (
4420                    "code",
4421                    PayloadValue::Str(crate::element::codes::UNAVAILABLE.into()),
4422                ),
4423            ]),
4424        ));
4425    }
4426
4427    /// Whether node `key` is a control: a view with a control's
4428    /// accessibility role, one that takes presses, or a text input. On a
4429    /// grid surface a control is laid out one line of its content high
4430    /// ([`grid`]).
4431    fn is_control(&self, key: Key) -> bool {
4432        use crate::AccessibilityRole as R;
4433        let node = &self.nodes[key as usize];
4434        node.kind == Kind::Input
4435            || (!node.inline && pressable(node.events))
4436            || node.props.as_ref().is_some_and(|p| {
4437                matches!(
4438                    p.accessibility.role,
4439                    R::Button
4440                        | R::ImageButton
4441                        | R::Link
4442                        | R::Search
4443                        | R::Textbox
4444                        | R::Checkbox
4445                        | R::Radio
4446                        | R::Switch
4447                        | R::Tab
4448                        | R::Menuitem
4449                        | R::MenuItemCheckbox
4450                        | R::MenuItemRadio
4451                        | R::Option
4452                        | R::Combobox
4453                        | R::Adjustable
4454                        | R::Spinbutton
4455                )
4456            })
4457    }
4458
4459    /// What a terminal's layout takes from node `key` besides its style
4460    /// ([`terminal_layout::Role`]): whether it is a control
4461    /// ([`Self::is_control`]), a text, a scroll view, and whether a
4462    /// terminal leaves it out: what it cannot show at an icon's size is
4463    /// left out, never emulated (icon-sized videos, web views, shaders and
4464    /// canvases) and glyph-sized images; larger, they keep their box.
4465    fn grid_role(&self, key: Key) -> terminal_layout::Role {
4466        let kind = self.nodes[key as usize].kind;
4467        let left_out = match kind {
4468            // A native component draws itself where the platform
4469            // registered one, and is blank where it did not.
4470            Kind::Image => terminal_layout::LeftOut::Picture,
4471            Kind::Video | Kind::WebView | Kind::Shader | Kind::GpuView | Kind::Canvas => {
4472                terminal_layout::LeftOut::IfIcon
4473            }
4474            _ => terminal_layout::LeftOut::No,
4475        };
4476        let control = self.is_control(key);
4477        // A control's label in columns (a wide character takes two): what it shows
4478        // when all its content is left out (an icon button).
4479        let popup = control
4480            && self.nodes[key as usize].props.as_ref().is_some_and(|p| {
4481                p.accessibility.state.expanded.is_some() && p.accessibility.state.has_popup
4482            });
4483        let (label, word) = control
4484            .then(|| self.nodes[key as usize].props.as_ref())
4485            .flatten()
4486            .map_or((0, 0), |p| {
4487                let cols = |t: &str| terminal_layout::columns(t).min(u16::MAX as usize) as u16;
4488                let name = p
4489                    .accessibility
4490                    .label
4491                    .as_deref()
4492                    .map(str::trim)
4493                    .filter(|l| !l.is_empty());
4494                match (p.accessibility.state.expanded, name) {
4495                    // A disclosure shows whether it is open, `â–¸` or `â–¾`,
4496                    // and a popup's trigger with no name which way it
4497                    // opens, `â–¾` or `â–´`, in place of its label.
4498                    (Some(_), _) if !popup => (1, 1),
4499                    (Some(_), None) => (1, 1),
4500                    // Another popup's trigger shows its name, then the
4501                    // arrow (`Merge options â–¾`), or the arrow alone where
4502                    // words beside it name it (`terminal_layout`'s
4503                    // `arrow_only`).
4504                    (Some(_), Some(l)) => {
4505                        let first = l.split_whitespace().next().unwrap_or("");
4506                        (cols(l).saturating_add(2), cols(first).saturating_add(2))
4507                    }
4508                    (None, l) => l.map_or((0, 0), |l| {
4509                        (cols(l), cols(l.split_whitespace().next().unwrap_or("")))
4510                    }),
4511                }
4512            });
4513        let node = &self.nodes[key as usize];
4514        let view = &node.view_style;
4515        let c = view.corner_radius;
4516        let radius = [c.top_left, c.top_right, c.bottom_right, c.bottom_left]
4517            .into_iter()
4518            .map(|r| r.unwrap_or(view.border_radius).0)
4519            .fold(0.0, f32::max);
4520        let w = view.borders.widths;
4521        let border_color = [w.top, w.right, w.bottom, w.left]
4522            .iter()
4523            .position(|&v| v > Points::ZERO)
4524            .map_or(crate::Color::TRANSPARENT, |i| view.borders.colors[i]);
4525        // A text's characters other than white space, which an absolute
4526        // box pinned over it would hide.
4527        let glyphs = kind == Kind::Text
4528            && node
4529                .layout
4530                .and_then(|l| self.layout.get_node_context(l))
4531                .is_some_and(|cx| match cx {
4532                    LeafContext::Text(cx) => cx.text.text.chars().any(|ch| !ch.is_whitespace()),
4533                    _ => false,
4534                });
4535        // A text with a letter or a digit: a word, not a mark.
4536        let worded = kind == Kind::Text
4537            && node
4538                .layout
4539                .and_then(|l| self.layout.get_node_context(l))
4540                .is_some_and(|cx| match cx {
4541                    LeafContext::Text(cx) => cx.text.text.chars().any(char::is_alphanumeric),
4542                    _ => false,
4543                });
4544        // A text of limited lines, cut short with `…` when it has no room.
4545        let clamped = kind == Kind::Text
4546            && node
4547                .layout
4548                .and_then(|l| self.layout.get_node_context(l))
4549                .is_some_and(|cx| match cx {
4550                    LeafContext::Text(cx) => cx.text.max_lines > 0,
4551                    _ => false,
4552                });
4553        let disclosure = control
4554            && self.nodes[key as usize].props.as_ref().is_some_and(|p| {
4555                p.accessibility.state.expanded.is_some() && !p.accessibility.state.has_popup
4556            });
4557        // A text that shows a disclosure's mark itself (`â–¸ Storage`).
4558        let marked = kind == Kind::Text
4559            && node
4560                .layout
4561                .and_then(|l| self.layout.get_node_context(l))
4562                .is_some_and(|cx| match cx {
4563                    LeafContext::Text(cx) => {
4564                        cx.text.text.trim_start().starts_with(['â–¸', 'â–¾', 'â–¹', 'â–¿'])
4565                    }
4566                    _ => false,
4567                });
4568        terminal_layout::Role {
4569            control,
4570            label,
4571            word,
4572            popup,
4573            disclosure,
4574            marked,
4575            text: matches!(kind, Kind::Text | Kind::Input),
4576            scroll: matches!(kind, Kind::Scroll | Kind::List),
4577            root: key == self.root,
4578            fills: matches!(kind, Kind::Screen | Kind::Modal),
4579            sized: matches!(
4580                kind,
4581                Kind::Native
4582                    | Kind::List
4583                    | Kind::Image
4584                    | Kind::Video
4585                    | Kind::WebView
4586                    | Kind::Shader
4587                    | Kind::GpuView
4588            ),
4589            input: kind == Kind::Input,
4590            glyphs,
4591            worded,
4592            clamped,
4593            radius,
4594            fill: node.resting_fill.unwrap_or(view.background_color),
4595            interactive: {
4596                let events = self.nodes[key as usize].events;
4597                pressable(events) || HANDLED.iter().any(|&e| events.contains(e))
4598            },
4599            animated_fill: self.nodes[key as usize]
4600                .animated
4601                .iter()
4602                .any(|(p, _)| matches!(p, AnimationProp::BackgroundColor)),
4603            border_color,
4604            splitter: match view.cursor {
4605                crate::Cursor::ColResize => terminal_layout::Splitter::Columns,
4606                crate::Cursor::RowResize => terminal_layout::Splitter::Rows,
4607                _ => terminal_layout::Splitter::No,
4608            },
4609            left_out,
4610            overlay: kind == Kind::Overlay,
4611            meter: node.props.as_ref().is_some_and(|p| {
4612                p.accessibility.role == crate::element::AccessibilityRole::Progressbar
4613            }),
4614            // The platform's indicator: none where the app hides it or
4615            // its own built-in bar takes its place.
4616            indicator: match node.scroll.as_deref() {
4617                Some(scroll)
4618                    if scroll.scrollbar != crate::ScrollbarSetting::Hidden
4619                        && scroll.bar.is_none() =>
4620                {
4621                    if scroll.horizontal {
4622                        terminal_layout::Indicator::Horizontal
4623                    } else {
4624                        terminal_layout::Indicator::Vertical
4625                    }
4626                }
4627                _ => terminal_layout::Indicator::No,
4628            },
4629        }
4630    }
4631
4632    /// Tells the layout what its grid takes from node `key`
4633    /// ([`Self::grid_role`]).
4634    fn sync_grid_role(&mut self, key: Key) {
4635        if let Some(layout) = self.nodes[key as usize].layout {
4636            let role = self.grid_role(key);
4637            if self.layout.set_role(layout, role) {
4638                self.needs_layout = true;
4639            }
4640        }
4641    }
4642
4643    /// What a node of its kind needs once made.
4644    fn became(&mut self, key: Key) {
4645        let kind = self.nodes[key as usize].kind;
4646        if kind.derives_layout() {
4647            let style = self.nodes[key as usize]
4648                .layout
4649                .map(|l| self.layout.style(l).clone())
4650                .unwrap_or_else(crate::style::unstyled_layout);
4651            self.nodes[key as usize].base_layout = Some(Box::new(style));
4652        }
4653        let node = &mut self.nodes[key as usize];
4654        if kind == Kind::Text {
4655            node.dirty |= dirty::TEXT_BUILD;
4656        }
4657        if kind == Kind::List {
4658            self.lists.push(key);
4659        }
4660        if matches!(kind, Kind::Scroll | Kind::List | Kind::Input)
4661            && self.builtin_scrollbars.is_some()
4662        {
4663            self.scrollbars_pending.push(key);
4664        }
4665        if kind.is_root() {
4666            self.roots.push(key);
4667        }
4668        if kind == Kind::Input {
4669            self.measure_input(key);
4670        }
4671        if kind == Kind::Overlay
4672            && let Some(layout) = self.nodes[key as usize].layout
4673        {
4674            self.overlay_made(key, layout);
4675        }
4676        self.sync_layout_style(key);
4677    }
4678
4679    /// Node `id`, a view no child is in yet, becomes a `tag` (a component's
4680    /// root of another kind on its host): as if it had been made one. Only
4681    /// while its native view is not sent yet (it was made in this batch);
4682    /// whether it did.
4683    pub(super) fn retag(&mut self, id: NodeId, tag: Tag) -> bool {
4684        let Ok(key) = self.key(id) else {
4685            return false;
4686        };
4687        let kind = Kind::of(tag);
4688        let node = &self.nodes[key as usize];
4689        if node.kind == kind {
4690            return true;
4691        }
4692        let id = node.id;
4693        if node.kind != Kind::View || !node.children.is_empty() {
4694            return false;
4695        }
4696        if node.created && !self.made_in_this_batch(id) {
4697            return false;
4698        }
4699        let node = &self.nodes[key as usize];
4700        // Out of its parent, its native view never made.
4701        let parent = node.parent;
4702        let at = (parent != NO_KEY).then(|| {
4703            let siblings = &self.nodes[parent as usize].children;
4704            let i = siblings.iter().position(|&c| c == key).expect("child");
4705            let next = siblings.get(i + 1).map(|&c| self.nodes[c as usize].id);
4706            (self.nodes[parent as usize].id, next)
4707        });
4708        if parent != NO_KEY {
4709            self.unlink(key, false);
4710        }
4711        // Its `Create` and `Insert` so far go, with the other retagged
4712        // views' in one pass ([`Self::drop_retagged`]).
4713        let retags = self.retags.get_or_insert_default();
4714        retags.made.remove(&id);
4715        retags.retagged.insert(id, self.mount.len());
4716        // The kind's own state and layout.
4717        let fresh = Node::new(id, kind);
4718        let node = &mut self.nodes[key as usize];
4719        node.created = false;
4720        node.kind = kind;
4721        node.image = fresh.image;
4722        node.scroll = fresh.scroll;
4723        node.list = fresh.list;
4724        node.input = fresh.input;
4725        node.root = fresh.root;
4726        node.control = fresh.control;
4727        node.component = fresh.component;
4728        let layout = node.layout.expect("a view has a layout");
4729        self.dirty_overlays();
4730        self.layout.set_node_context(layout, leaf_context(kind));
4731        self.became(key);
4732        // A native component made in its place reads its style's accent.
4733        self.sync_accent(key);
4734        // What a terminal's layout takes from its kind (a scroll view's
4735        // unbounded content), as if it had been made one.
4736        self.sync_grid_role(key);
4737        if let Some((parent, before)) = at {
4738            let _ = self.insert(parent, id, before);
4739        }
4740        true
4741    }
4742
4743    /// Whether made view `id`'s `Create` is still in the mount items (it was
4744    /// made in this batch). Each item is looked at once a round of renders,
4745    /// not once a view.
4746    fn made_in_this_batch(&mut self, id: NodeId) -> bool {
4747        let retags = self.retags.get_or_insert_default();
4748        let from = retags.seen;
4749        retags
4750            .made
4751            .extend(self.mount[from..].iter().filter_map(|m| match m {
4752                MountItem::Create { id, .. } => Some(*id),
4753                _ => None,
4754            }));
4755        retags.seen = self.mount.len();
4756        let made = retags.made.contains(&id);
4757        self.retagging(self.mount.len() - from);
4758        made
4759    }
4760
4761    /// Drops the `Create` and `Insert` items the retagged views had before
4762    /// they took their kind ([`Self::retag`]), in one pass.
4763    pub(super) fn drop_retagged(&mut self) {
4764        let Some(retags) = self.retags.as_deref_mut() else {
4765            return;
4766        };
4767        if retags.retagged.is_empty() {
4768            return;
4769        }
4770        let retagged = std::mem::take(&mut retags.retagged);
4771        let (seen, made) = (retags.seen, &mut retags.made);
4772        let mut at = 0;
4773        self.mount.retain(|m| {
4774            let i = at;
4775            at += 1;
4776            let (MountItem::Create { id, .. } | MountItem::Insert { child: id, .. }) = m else {
4777                return true;
4778            };
4779            if retagged.get(id).is_some_and(|&then| i < then) {
4780                return false;
4781            }
4782            if i >= seen && matches!(m, MountItem::Create { .. }) {
4783                made.insert(*id);
4784            }
4785            true
4786        });
4787        retags.seen = self.mount.len();
4788        self.retagging(at);
4789    }
4790
4791    /// The round of renders is over: what [`Self::retag`] did goes into
4792    /// the mount items, and its record of them goes (other steps insert
4793    /// items among them).
4794    pub(super) fn end_retags(&mut self) {
4795        self.drop_retagged();
4796        #[cfg(test)]
4797        if self.retags.is_some() {
4798            let rounds = &self.components.retag_rounds;
4799            rounds.set(rounds.get() + 1);
4800        }
4801        self.retags = None;
4802    }
4803
4804    /// Rebuilds the text an input is measured with: what it shows while an
4805    /// input method composes, else its value, else its placeholder, else an
4806    /// empty line.
4807    fn measure_input(&mut self, key: Key) {
4808        let node = &self.nodes[key as usize];
4809        let (Some(input), Some(layout)) = (&node.input, node.layout) else {
4810            return;
4811        };
4812        let shown = input.composing.as_deref().unwrap_or(&input.value);
4813        let placeholder = shown.is_empty() && !input.config.placeholder.is_empty();
4814        let text = self.input_text(
4815            key,
4816            if placeholder {
4817                &input.config.placeholder
4818            } else {
4819                shown
4820            },
4821        );
4822        let field = self.input_text(key, FIELD_SAMPLE);
4823        let cx = self.text_cx(layout);
4824        let same = cx.text.layout_eq(&text);
4825        let same_field = cx.field.as_ref().is_some_and(|f| f.text.layout_eq(&field));
4826        let input = self.nodes[key as usize]
4827            .input
4828            .as_mut()
4829            .expect("input state");
4830        // A value that reads as the placeholder measures the same, but
4831        // its content size is the value's: laid out again to report it.
4832        if same && same_field && input.placeholder_measured == placeholder {
4833            return;
4834        }
4835        input.placeholder_measured = placeholder;
4836        let cx = self.text_cx(layout);
4837        if !same {
4838            let kept = cx.field.take();
4839            *cx = TextContext::new(Arc::new(text));
4840            cx.field = kept;
4841        }
4842        if !same_field {
4843            cx.field = Some(Box::new(TextContext::new(Arc::new(field))));
4844        }
4845        self.layout.mark_dirty(layout);
4846        self.needs_layout = true;
4847    }
4848
4849    /// `content` in the text style of input `key`, as it is measured.
4850    fn input_text(&self, key: Key, content: &str) -> AttributedText {
4851        let node = &self.nodes[key as usize];
4852        let multiline = node.input.as_ref().is_some_and(|i| i.config.multiline);
4853        let mut text = AttributedText {
4854            max_lines: if multiline { 0 } else { 1 },
4855            ..AttributedText::default()
4856        };
4857        let style = scaled(
4858            self.inherited_text_style(key).inherit(&node.text_style),
4859            node.paragraph.font_multiplier(self.font_scale),
4860        );
4861        text.paragraph_strut = Some(style);
4862        if multiline {
4863            text.push(&broken_runs(content), style);
4864        } else {
4865            text.push(content, style);
4866        }
4867        // An empty last line still takes space (a trailing line break, or no
4868        // text at all).
4869        if content.is_empty() || (multiline && content.ends_with('\n')) {
4870            text.push("\u{200b}", style);
4871        }
4872        text
4873    }
4874
4875    /// `key` holds a slot's content in a Rust component's tree (JS's holder
4876    /// of a slot or a render, or the node a view wraps its fill in): while
4877    /// nothing styles its layout and it holds one node, that node is laid
4878    /// out in its place, as the component's own child (`layout_tree`'s
4879    /// "holders laid out through"). A list's holder (an `Items` slot) is a
4880    /// list, laid out as one.
4881    pub(super) fn lay_out_through(&mut self, key: Key) {
4882        let node = &self.nodes[key as usize];
4883        if node.kind == Kind::View
4884            && let Some(layout) = node.layout
4885        {
4886            self.layout.set_holder(layout);
4887            self.needs_layout = true;
4888        }
4889    }
4890
4891    /// Pushes the effective taffy style of `key`: the JS style, adjusted
4892    /// for scroll containers and list cells.
4893    fn sync_layout_style(&mut self, key: Key) {
4894        let node = &self.nodes[key as usize];
4895        let (Some(layout), Some(base)) = (node.layout, node.base_layout.as_deref()) else {
4896            return;
4897        };
4898        let mut style = base.clone();
4899        let kind = node.kind;
4900        if let Some(root) = self.nodes[key as usize].root.as_mut() {
4901            // Laid out again with its size by `layout_roots`.
4902            root.laid_out = None;
4903        }
4904        let node = &self.nodes[key as usize];
4905        match kind {
4906            Kind::Scroll => {
4907                // Children may overflow along the scroll axis; a horizontal
4908                // scroll lays its content out in a row.
4909                let horizontal = node.scroll.as_ref().is_some_and(|s| s.horizontal);
4910                if horizontal {
4911                    style.flex_direction = taffy::FlexDirection::Row;
4912                    style.overflow.x = Overflow::Scroll;
4913                    if node.rtl {
4914                        // Laid out left to right (with the authored sides)
4915                        // and mirrored by `emit_frames`: right to left, a
4916                        // row would overflow to negative offsets.
4917                        std::mem::swap(&mut style.padding.left, &mut style.padding.right);
4918                        std::mem::swap(&mut style.border.left, &mut style.border.right);
4919                        style.direction = taffy::Direction::Ltr;
4920                    }
4921                } else {
4922                    style.overflow.y = Overflow::Scroll;
4923                }
4924            }
4925            Kind::List => {
4926                style.overflow = taffy::Point {
4927                    x: Overflow::Hidden,
4928                    y: Overflow::Hidden,
4929                }
4930            }
4931            Kind::Cell => {
4932                // Cells are their own layout roots (the list gives them a
4933                // definite cross size to stretch, or max-content to align,
4934                // and positions them): a change in one row never relayouts
4935                // the rest of the tree.
4936                let horizontal = self
4937                    .nodes
4938                    .get(node.parent as usize)
4939                    .and_then(|p| p.scroll.as_ref())
4940                    .is_some_and(|s| s.horizontal);
4941                style.position = Position::Relative;
4942                if horizontal {
4943                    style.size.height = taffy::Dimension::percent(1.0);
4944                } else {
4945                    style.size.width = taffy::Dimension::percent(1.0);
4946                }
4947            }
4948            // `position: fixed` in its root view's box.
4949            Kind::Overlay => style.position = Position::Absolute,
4950            _ => {}
4951        }
4952        if node.fixed_view {
4953            style.position = Position::Fixed;
4954        }
4955        if self.layout.set_style(layout, style) {
4956            self.needs_layout = true;
4957        }
4958    }
4959
4960    fn set_inline_style(
4961        &mut self,
4962        id: NodeId,
4963        style: Box<Style>,
4964        patch: StylePatch,
4965    ) -> Result<(), ApplyError> {
4966        let key = self.key(id)?;
4967        let node = &mut self.nodes[key as usize];
4968        node.inline_style = patch;
4969        if node.classes.is_some() || node.spaced || node.inline_style.reads_current_color() {
4970            self.restyle(key);
4971            return Ok(());
4972        }
4973        let mut props = node.class_props.as_deref().cloned().unwrap_or_default();
4974        style.node_props(&mut props);
4975        self.set_class_props(key, props);
4976        self.set_style(id, *style)
4977    }
4978
4979    fn set_style(&mut self, id: NodeId, style: Style) -> Result<(), ApplyError> {
4980        let key = self.key(id)?;
4981        let Style {
4982            mut layout,
4983            mut view,
4984            text,
4985            paint,
4986            animated,
4987            z_index,
4988            vertical_align,
4989            direction,
4990            logical,
4991            pending,
4992            perspective,
4993        } = style;
4994        if animated
4995            .iter()
4996            .any(|(p, _)| matches!(p, AnimationProp::BackgroundColor))
4997        {
4998            // The animated color must show: a gradient drawn over it would
4999            // hide it.
5000            view.clear_background_images();
5001        }
5002        if key != self.root {
5003            self.nodes[key as usize].direction = direction;
5004        }
5005        let rtl = self.resolved_rtl(key);
5006        let sticky = prepare_layout(
5007            &mut layout,
5008            &mut view,
5009            &logical,
5010            rtl,
5011            pending.sticky_position,
5012        );
5013        // An input always clips: it scrolls its own text, so text taller than
5014        // its box (a fixed height, a `maxHeight`) stays in it and must not
5015        // grow the content size of a scroll view around it.
5016        let input = self.nodes[key as usize].kind == Kind::Input;
5017        clip_overflow(&mut layout, view.overflow_hidden || input);
5018        self.install_style(
5019            key,
5020            StyleRecord {
5021                layout,
5022                view,
5023                text,
5024                paint: (paint != PaintStyle::default()).then(|| Rc::new(paint)),
5025                animated,
5026                sticky,
5027                perspective,
5028                object_fit: pending.object_fit,
5029                wants_fixed: pending.fixed_position,
5030                env: pending.env,
5031                z_index,
5032                vertical_align,
5033                has_logical: !logical.is_empty(),
5034                rtl,
5035            },
5036        );
5037        Ok(())
5038    }
5039
5040    /// Installs a cached [`classes::ResolvedClassStyle`] on `key`, sharing
5041    /// its records with the other nodes styled alike.
5042    fn apply_resolved_style(&mut self, key: Key, resolved: &classes::ResolvedClassStyle) {
5043        self.set_class_props_shared(key, resolved.props.as_ref());
5044        self.install_style(
5045            key,
5046            StyleRecord {
5047                layout: resolved.layout.clone(),
5048                view: resolved.view.clone(),
5049                text: resolved.text.clone(),
5050                paint: resolved.paint.clone(),
5051                animated: Vec::new(),
5052                sticky: resolved.sticky,
5053                perspective: resolved.perspective,
5054                object_fit: resolved.object_fit,
5055                wants_fixed: resolved.wants_fixed,
5056                env: crate::style::EnvEdges::default(),
5057                z_index: resolved.z_index,
5058                vertical_align: resolved.vertical_align,
5059                has_logical: resolved.has_logical,
5060                rtl: resolved.rtl,
5061            },
5062        );
5063    }
5064
5065    /// Makes `record` `key`'s style and marks what changed: the one path of
5066    /// a node resolved alone ([`Self::set_style`]) and of a cached class
5067    /// style ([`Self::apply_resolved_style`]).
5068    fn install_style(
5069        &mut self,
5070        key: Key,
5071        record: StyleRecord<impl LayoutSlot, impl StyleSlot<ViewStyle>, impl StyleSlot<TextStyle>>,
5072    ) {
5073        let StyleRecord {
5074            mut layout,
5075            view,
5076            text,
5077            paint,
5078            animated,
5079            sticky,
5080            perspective,
5081            object_fit,
5082            wants_fixed,
5083            env,
5084            z_index,
5085            vertical_align,
5086            has_logical,
5087            rtl,
5088        } = record;
5089        let hid_before = self.nodes[key as usize]
5090            .layout
5091            .is_some_and(|l| self.layout.displays_none(l));
5092        let node = &mut self.nodes[key as usize];
5093        node.has_logical = has_logical;
5094        if node.sticky.as_deref() != sticky.as_ref() {
5095            self.set_sticky(key, sticky.map(Box::new));
5096        }
5097        let node = &mut self.nodes[key as usize];
5098        if node.child_perspective != perspective {
5099            node.child_perspective = perspective;
5100            // Its children's transforms compose it (their animated steps
5101            // move by its steps).
5102            let children = node.children.clone();
5103            for c in children {
5104                self.mark(c, dirty::VIEW | dirty::ANIMATION);
5105            }
5106        }
5107        let node = &mut self.nodes[key as usize];
5108        if node.object_fit != object_fit {
5109            node.object_fit = object_fit;
5110            if node.image.is_some() {
5111                self.mark(key, dirty::IMAGE);
5112            } else if let Some(control) = node.control.as_mut() {
5113                // A video is contained by default.
5114                let fit = object_fit.unwrap_or(ResizeMode::Contain);
5115                apply_native(control, NativeProp::VideoResizeMode(fit));
5116                self.mark(key, dirty::NATIVE);
5117            }
5118        }
5119        let node = &mut self.nodes[key as usize];
5120        if node.wants_fixed != wants_fixed {
5121            // Made an overlay, or a view again: at once while it is in no
5122            // parent (classes are set before the node is inserted), else as
5123            // the commit starts.
5124            node.wants_fixed = wants_fixed;
5125            let id = node.id;
5126            if node.parent == NO_KEY {
5127                self.fix_or_unfix(key);
5128            } else {
5129                self.fixed_changed.push((key, id));
5130            }
5131        }
5132        // `env()`'s terms, on the edges their declarations name (left and
5133        // right are physical, right to left too).
5134        let env = (!env.is_empty()).then(|| (env, self.env_insets(key, &env)));
5135        let node = &mut self.nodes[key as usize];
5136        let id = node.id;
5137        match env {
5138            Some(env) => {
5139                node.env = Some(Box::new(env));
5140                self.env_styled.insert(id);
5141            }
5142            None => {
5143                if node.env.take().is_some() {
5144                    self.env_styled.remove(&id);
5145                }
5146            }
5147        }
5148        let node = &mut self.nodes[key as usize];
5149        let mut extra = node.insets.as_deref().copied();
5150        if let Some((_, applied)) = node.env.as_deref() {
5151            let sum = |a: EdgeInsets, b: EdgeInsets| EdgeInsets {
5152                top: a.top + b.top,
5153                right: a.right + b.right,
5154                bottom: a.bottom + b.bottom,
5155                left: a.left + b.left,
5156            };
5157            let [p, m] = extra.unwrap_or_default();
5158            extra = Some([sum(p, applied[0]), sum(m, applied[1])]);
5159        }
5160        if let Some([padding, margin]) = extra.as_ref() {
5161            let layout = layout.to_mut();
5162            // On top of points; percentages cannot take an addition.
5163            let add = |p: &mut taffy::LengthPercentage, d: f32| {
5164                if let taffy::style::ExpandedLengthPercentage::Length(v) = p.expand() {
5165                    *p = taffy::LengthPercentage::length(v + d);
5166                }
5167            };
5168            add(&mut layout.padding.top, padding.top.0);
5169            add(&mut layout.padding.right, padding.right.0);
5170            add(&mut layout.padding.bottom, padding.bottom.0);
5171            add(&mut layout.padding.left, padding.left.0);
5172            // `auto` margins stay automatic.
5173            let add = |m: &mut taffy::LengthPercentageAuto, d: f32| {
5174                if let taffy::style::ExpandedLengthPercentageAuto::Length(v) = m.expand() {
5175                    *m = taffy::LengthPercentageAuto::length(v + d);
5176                }
5177            };
5178            add(&mut layout.margin.top, margin.top.0);
5179            add(&mut layout.margin.right, margin.right.0);
5180            add(&mut layout.margin.bottom, margin.bottom.0);
5181            add(&mut layout.margin.left, margin.left.0);
5182        }
5183        let node = &mut self.nodes[key as usize];
5184        let flipped = node.rtl != rtl;
5185        node.rtl = rtl;
5186        // A shared record installed already (or an equal one) changes
5187        // nothing visual: the comparisons below are skipped.
5188        let view_same = view.same(&node.view_style);
5189        let new_view = view.get();
5190        // `objectPosition` is the image's (`MountItem::Image`), not the view's.
5191        let position_changed =
5192            !view_same && node.view_style.object_position != new_view.object_position;
5193        let view_changed = !view_same
5194            && (!position_changed
5195                || node.view_style
5196                    != ViewStyle {
5197                        object_position: node.view_style.object_position,
5198                        ..new_view.clone()
5199                    });
5200        // A span's background and visibility are part of its block's text.
5201        let span_drawing_changed = !view_same
5202            && node.inline
5203            && node.kind == Kind::Text
5204            && (span_background(&node.view_style, node.id) != span_background(new_view, node.id)
5205                || node.view_style.hidden != new_view.hidden);
5206        // Clipping decides whether a nowrap line takes its ellipsis.
5207        let clip_changed = !view_same
5208            && !node.inline
5209            && node.kind == Kind::Text
5210            && node.view_style.overflow_hidden != new_view.overflow_hidden;
5211        let text_same = text.same(&node.text_style);
5212        let text_changed = !text_same || span_drawing_changed;
5213        // What its children inherit as `currentColor`.
5214        let passed_color = |node: &Node, text: &TextStyle| text.color.or(node.inherited_color);
5215        let color_passed =
5216            !text_same && passed_color(node, &node.text_style) != passed_color(node, text.get());
5217        let animation_changed = node.animated != animated;
5218        let paint_changed = !opt_rc_eq(node.paint.as_ref(), paint.as_ref());
5219        let z_changed = node.z_index != z_index;
5220        // An attachment's place in its line is part of its block's text.
5221        let align_changed =
5222            node.vertical_align != vertical_align && node.inline && node.kind != Kind::Text;
5223        // ... and so is the content's of a render placed there.
5224        let content_align_changed = node.vertical_align != vertical_align && !node.inline;
5225        let accent_changed = !view_same && node.view_style.accent_color != new_view.accent_color;
5226        view.install(&mut node.view_style);
5227        text.install(&mut node.text_style);
5228        if paint_changed {
5229            node.paint = paint;
5230        }
5231        node.animated = animated;
5232        node.z_index = z_index;
5233        node.vertical_align = vertical_align;
5234        // Its fill, border and corners (`terminal_layout::Role`).
5235        self.sync_grid_role(key);
5236        if clip_changed {
5237            self.mark(key, dirty::TEXT_BUILD);
5238        }
5239        if align_changed {
5240            self.mark_text_block(key);
5241        } else if content_align_changed && let Some(place) = self.placed_in_text(key) {
5242            self.mark_text_block(place);
5243        }
5244        if z_changed {
5245            self.restack(key);
5246        }
5247        let node = &mut self.nodes[key as usize];
5248        fn keep_base(slot: &mut Option<Box<taffy::Style>>, layout: impl LayoutSlot) {
5249            match slot {
5250                Some(base) => **base = layout.into_owned(),
5251                None => *slot = Some(Box::new(layout.into_owned())),
5252            }
5253        }
5254        if node.kind.derives_layout() || node.fixed_view {
5255            keep_base(&mut node.base_layout, layout);
5256            self.sync_layout_style(key);
5257        } else if let Some(l) = node.layout {
5258            // A style that only changed what is painted lays nothing out.
5259            if layout.set_on(&mut self.layout, l) {
5260                self.needs_layout = true;
5261            }
5262        } else if node.kind == Kind::Text {
5263            // A span: kept for when it is a block again. Its padding is
5264            // part of its block's text (horizontal: room in the line;
5265            // vertical: its background's).
5266            let padding = |l: &taffy::Style| l.padding;
5267            let padded = node.base_layout.as_deref().map(padding) != Some(padding(layout.get()));
5268            keep_base(&mut node.base_layout, layout);
5269            if padded && node.inline {
5270                self.mark_text_block(key);
5271            }
5272        }
5273        let hid_after = self.nodes[key as usize]
5274            .layout
5275            .is_some_and(|l| self.layout.displays_none(l));
5276        if hid_before != hid_after {
5277            self.dirty_overlays();
5278        }
5279        let mut flags = 0;
5280        if view_changed {
5281            flags |= dirty::VIEW;
5282            // A drawing filling with the view's background paints the new
5283            // one.
5284            if self.nodes[key as usize]
5285                .drawing
5286                .as_ref()
5287                .is_some_and(|d| d.paints_background())
5288            {
5289                flags |= dirty::CANVAS;
5290            }
5291        }
5292        if position_changed && self.nodes[key as usize].image.is_some() {
5293            flags |= dirty::IMAGE;
5294        }
5295        if accent_changed {
5296            self.sync_accent(key);
5297        }
5298        // A sticky view's animated inset is part of its range.
5299        self.sticky_changed |= animation_changed && self.nodes[key as usize].sticky.is_some();
5300        let parent = self.nodes[key as usize].parent;
5301        let in_perspective =
5302            parent != NO_KEY && self.nodes[parent as usize].child_perspective.is_some();
5303        if animation_changed
5304            || view_changed && in_perspective && !self.nodes[key as usize].animated.is_empty()
5305        {
5306            // Its animated steps move with its parent's perspective.
5307            flags |= dirty::ANIMATION;
5308        }
5309        if flags != 0 {
5310            self.mark(key, flags);
5311        }
5312        if text_changed || flipped {
5313            match self.nodes[key as usize].kind {
5314                Kind::Text => {
5315                    self.mark_text_block(key);
5316                    // Texts inside its attachments take its color.
5317                    if color_passed {
5318                        self.mark_inheriting_text(key);
5319                    }
5320                }
5321                Kind::Input => {
5322                    self.measure_input(key);
5323                    self.mark(key, dirty::INPUT);
5324                }
5325                // Text inside inherits it (CSS).
5326                _ if text_changed => self.mark_inheriting_text(key),
5327                _ => {}
5328            }
5329        }
5330        if color_passed {
5331            let node = &self.nodes[key as usize];
5332            let color = node.text_style.color.or(node.inherited_color);
5333            self.inherit_color(key, color);
5334        }
5335        // A canvas painting with its view's style (`currentColor` too) sees
5336        // the change, and so do the ones inside it, which inherit it.
5337        if paint_changed || text_changed {
5338            self.mark_view_painted(key);
5339        }
5340        if flipped {
5341            self.update_children_direction(key);
5342            // Its own `direction` turned it: classes resolved for the other
5343            // direction (`pl-*`, `rtl:`) resolve again.
5344            if self.reads_direction(key) {
5345                self.restyle(key);
5346            }
5347        }
5348    }
5349
5350    /// Marks the canvases at and inside `key` that paint with their view's
5351    /// style ([`crate::canvas::Drawing::view_paints`]) to be sent again.
5352    fn mark_view_painted(&mut self, key: Key) {
5353        let mut stack = vec![key];
5354        while let Some(k) = stack.pop() {
5355            let node = &self.nodes[k as usize];
5356            match node.kind {
5357                Kind::Canvas => {
5358                    if node
5359                        .drawing
5360                        .as_ref()
5361                        .is_some_and(|d| !d.view_paints.is_empty())
5362                    {
5363                        self.mark(k, dirty::CANVAS);
5364                    }
5365                }
5366                Kind::Text | Kind::RawText | Kind::Input => {}
5367                // An `svg()` drawn as an image paints `currentColor` too.
5368                _ if node.image.as_ref().is_some_and(|i| i.svg_current_color) => {
5369                    self.mark(k, dirty::IMAGE);
5370                }
5371                _ => stack.extend_from_slice(&self.nodes[k as usize].children),
5372            }
5373        }
5374    }
5375
5376    /// Canvas `key`'s `drawing` as its platform gets it: its
5377    /// [`crate::canvas::Drawing::view_paints`] resolved with its style and
5378    /// its box.
5379    fn mounted_drawing(
5380        &self,
5381        key: Key,
5382        drawing: &Arc<crate::canvas::Drawing>,
5383    ) -> Arc<crate::canvas::Drawing> {
5384        if drawing.view_paints.is_empty() {
5385            return drawing.clone();
5386        }
5387        let node = &self.nodes[key as usize];
5388        let (paint, current) = self.resolved_paint(key);
5389        let style = &node.view_style;
5390        let images = style
5391            .effects
5392            .as_deref()
5393            .map_or(&[][..], |e| &e.background_images[..]);
5394        let size = if node.frame == Bounds::UNSET {
5395            Size::default()
5396        } else {
5397            node.frame.size
5398        };
5399        Arc::new(drawing.painted(&paint, current, style.background_color, images, size))
5400    }
5401
5402    /// Sends the canvases fitting a view box that changed or were given
5403    /// another size this round, with the size the layout gave them.
5404    fn send_fitted(&mut self) {
5405        let mut pending = std::mem::take(&mut self.fitted_pending);
5406        pending.sort_unstable();
5407        pending.dedup();
5408        for &key in &pending {
5409            let Some(node) = self.nodes.get(key as usize) else {
5410                continue;
5411            };
5412            if !node.created {
5413                continue;
5414            }
5415            let Some(drawing) = &node.drawing else {
5416                continue;
5417            };
5418            let (id, drawing) = (node.id, self.mounted_drawing(key, drawing));
5419            self.mount.push(MountItem::Canvas { id, drawing });
5420        }
5421        pending.clear();
5422        self.fitted_pending = pending;
5423    }
5424
5425    /// The paint properties canvas `key` paints with (its own over those
5426    /// of the views around it, as CSS inherits them) and its text color,
5427    /// for `currentColor`.
5428    fn resolved_paint(&self, key: Key) -> (PaintStyle, crate::style::Color) {
5429        let node = &self.nodes[key as usize];
5430        let mut paint = node.paint.as_deref().cloned().unwrap_or_default();
5431        let mut k = node.parent;
5432        while k != NO_KEY {
5433            if let Some(p) = self.nodes[k as usize].paint.as_deref() {
5434                paint = paint.inherit(p);
5435            }
5436            k = self.nodes[k as usize].parent;
5437        }
5438        let color = node
5439            .text_style
5440            .color
5441            .unwrap_or_else(|| self.inherited_text_style(key).color);
5442        (paint, color)
5443    }
5444
5445    /// The direction `key` lays out in: its own, else its parent's (the
5446    /// root's while detached).
5447    pub(super) fn resolved_rtl(&self, key: Key) -> bool {
5448        let node = &self.nodes[key as usize];
5449        if let Some(rtl) = node.direction {
5450            return rtl;
5451        }
5452        match node.parent {
5453            NO_KEY => key != self.root && self.nodes[self.root as usize].rtl,
5454            parent => self.nodes[parent as usize].rtl,
5455        }
5456    }
5457
5458    /// Re-resolves the direction of `key` (moved, or its parent's changed)
5459    /// and of the nodes inheriting it.
5460    fn update_direction(&mut self, key: Key) {
5461        let rtl = self.resolved_rtl(key);
5462        if self.nodes[key as usize].rtl == rtl {
5463            return;
5464        }
5465        self.flip_direction(key, rtl);
5466        self.update_children_direction(key);
5467    }
5468
5469    fn update_children_direction(&mut self, key: Key) {
5470        let children = self.nodes[key as usize].children.clone();
5471        for child in children {
5472            self.update_direction(child);
5473        }
5474    }
5475
5476    /// Lays `key` out in the other direction. Its left and right properties
5477    /// keep their sides, as in CSS; its start / end ones move with the
5478    /// direction, so it is styled again when it has some.
5479    fn flip_direction(&mut self, key: Key, rtl: bool) {
5480        let direction = if rtl {
5481            taffy::Direction::Rtl
5482        } else {
5483            taffy::Direction::Ltr
5484        };
5485        let node = &mut self.nodes[key as usize];
5486        node.rtl = rtl;
5487        if let Some(list) = node.list.as_mut() {
5488            let mirrored = rtl && list.horizontal;
5489            list.set_mirrored(mirrored);
5490        }
5491        // A spaced child's margin is on its end side.
5492        let logical = node.has_logical || node.spaced;
5493        let kind = node.kind;
5494        if let Some(base) = node.base_layout.as_deref_mut() {
5495            base.direction = direction;
5496            self.sync_layout_style(key);
5497        } else if let Some(l) = node.layout {
5498            let mut layout = self.layout.style(l).clone();
5499            layout.direction = direction;
5500            self.layout.set_style(l, layout);
5501            self.needs_layout = true;
5502        }
5503        self.mark(key, dirty::VIEW);
5504        if logical || self.reads_direction(key) {
5505            self.restyle(key);
5506        }
5507        let node = &mut self.nodes[key as usize];
5508        let id = node.id;
5509        if let Some(scroll) = node.scroll.as_mut()
5510            && scroll.horizontal
5511            && node.list.as_ref().is_none_or(|l| !l.parent)
5512        {
5513            // Back to the start side: the right end right to left (once the
5514            // content is known again).
5515            scroll.content = None;
5516            if !rtl {
5517                self.commands.push((
5518                    id,
5519                    Command::ScrollTo {
5520                        x: Points::ZERO,
5521                        y: Points::ZERO,
5522                        animated: false,
5523                    },
5524                ));
5525            }
5526            self.mark(key, dirty::SCROLL);
5527        }
5528        match kind {
5529            Kind::Text => self.mark_text_block(key),
5530            Kind::Input => {
5531                self.measure_input(key);
5532                self.mark(key, dirty::INPUT);
5533            }
5534            _ => {}
5535        }
5536    }
5537
5538    /// Media source `uri` as the app may load it ([`crate::access::Access::media_url`]
5539    /// against [`Core::set_base_url`]'s URL): `Some(None)` as written,
5540    /// `Some(Some(url))` the URL to load in its place, `None` refused.
5541    fn media_source(&self, uri: &str) -> Option<Option<Arc<str>>> {
5542        match self
5543            .access
5544            .media_url(uri, self.base_url.as_deref(), Some(&self.media_files))?
5545        {
5546            std::borrow::Cow::Borrowed(_) => Some(None),
5547            std::borrow::Cow::Owned(url) => Some(Some(url.into())),
5548        }
5549    }
5550
5551    /// The images `drawing` draws as the app may load them
5552    /// ([`crate::access::Access::media_url`] against [`Core::set_base_url`]'s
5553    /// URL and the `capabilities.fs.read` roots): one the check grants is
5554    /// rewritten to what it granted (a file's canonical path, a URL's
5555    /// serialization); one it refuses is dropped and reported. A network
5556    /// answer is remembered for the session; a file's changes with the
5557    /// disk and is never remembered. On-screen canvases check every
5558    /// drawing (`Op::Draw`); offscreen renders check the same way before
5559    /// the platform draws (`canvas_render.rs`).
5560    fn check_canvas_images(&mut self, drawing: &mut crate::canvas::Drawing) {
5561        if self.access.is_unrestricted() {
5562            return;
5563        }
5564        let access = self.access.clone();
5565        let base = self.base_url.clone();
5566        let files = self.media_files.clone();
5567        let mut refused = Vec::new();
5568        let checked = &mut self.canvas_images;
5569        // Each file's answer for this drawing: a drawing names the same
5570        // image many times (a game's map draws thousands of tiles from a
5571        // few sheets), and resolving a file is disk work, once per image.
5572        let mut files_here: rustc_hash::FxHashMap<Arc<str>, Option<Arc<str>>> =
5573            rustc_hash::FxHashMap::default();
5574        drawing.ops.retain_mut(|op| match op {
5575            crate::canvas::CanvasOp::DrawImage { image, .. } => {
5576                let granted = match checked
5577                    .get(&image.uri)
5578                    .or_else(|| files_here.get(&image.uri))
5579                {
5580                    Some(granted) => granted.clone(),
5581                    None => {
5582                        let granted = access
5583                            .media_url(&image.uri, base.as_deref(), Some(&files))
5584                            .map(|url| match url {
5585                                std::borrow::Cow::Owned(url) => Arc::from(url),
5586                                std::borrow::Cow::Borrowed(_) => image.uri.clone(),
5587                            });
5588                        if crate::access::media_capability(&image.uri, base.as_deref()) == "network"
5589                        {
5590                            if checked.len() >= CANVAS_IMAGES {
5591                                checked.clear();
5592                            }
5593                            checked.insert(image.uri.clone(), granted.clone());
5594                        } else {
5595                            files_here.insert(image.uri.clone(), granted.clone());
5596                        }
5597                        granted
5598                    }
5599                };
5600                match granted {
5601                    Some(url) => {
5602                        image.uri = url;
5603                        true
5604                    }
5605                    None => {
5606                        refused.push(image.uri.clone());
5607                        false
5608                    }
5609                }
5610            }
5611            _ => true,
5612        });
5613        // Reported once per drawing, not per draw.
5614        refused.sort_unstable();
5615        refused.dedup();
5616        for uri in refused {
5617            self.deny(media_not_granted(
5618                "a canvas image",
5619                &uri,
5620                self.base_url.as_deref(),
5621            ));
5622        }
5623    }
5624
5625    /// `desktop`'s menu and tray icons as the app may load them
5626    /// ([`Self::media_source`]): a refused icon is dropped (the item shows
5627    /// none) and reported.
5628    /// Keeps the application menu and its labels where `MenuBar` reads them
5629    /// ([`crate::element::desktop::application_menu`]).
5630    fn remember_app_menu(&mut self, desktop: &crate::desktop::DesktopCommand) {
5631        use crate::desktop::DesktopCommand;
5632        let change: Box<dyn FnOnce(&mut crate::element::menus::AppMenu)> = match desktop {
5633            DesktopCommand::SetMenu(items) => {
5634                let items = items.clone();
5635                Box::new(move |m| m.items = items)
5636            }
5637            DesktopCommand::SetMenuLabels(labels) => {
5638                let labels = (**labels).clone();
5639                Box::new(move |m| m.labels = labels)
5640            }
5641            _ => return,
5642        };
5643        let _entered = self.components.runtime.enter();
5644        let signal = crate::element::menus::app_menu(&self.components.executor.menus);
5645        signal.update(change);
5646    }
5647
5648    fn check_menu_icons(&mut self, desktop: &mut crate::desktop::DesktopCommand) {
5649        use crate::{
5650            ImageSource,
5651            desktop::{DesktopCommand, MenuItem},
5652        };
5653        if self.access.is_unrestricted() {
5654            return;
5655        }
5656        let mut check = |icon: &mut Option<ImageSource>| {
5657            let Some(source) = icon else { return };
5658            match self.media_source(&source.uri) {
5659                Some(Some(url)) => source.uri = url,
5660                Some(None) => {}
5661                None => {
5662                    let message =
5663                        media_not_granted("the menu icon", &source.uri, self.base_url.as_deref());
5664                    *icon = None;
5665                    self.deny(message);
5666                }
5667            }
5668        };
5669        fn each(items: &mut [MenuItem], check: &mut impl FnMut(&mut Option<ImageSource>)) {
5670            for item in items {
5671                match item {
5672                    MenuItem::Action(action) => check(&mut action.icon),
5673                    MenuItem::Submenu { items, icon, .. } => {
5674                        check(icon);
5675                        each(items, check);
5676                    }
5677                    MenuItem::Separator => {}
5678                }
5679            }
5680        }
5681        let checked = |items: &Arc<[MenuItem]>, check: &mut dyn FnMut(&mut Option<ImageSource>)| {
5682            let mut items = items.to_vec();
5683            each(&mut items, &mut |icon| check(icon));
5684            Arc::<[MenuItem]>::from(items)
5685        };
5686        match desktop {
5687            DesktopCommand::SetMenu(Some(items)) | DesktopCommand::PopupMenu { items, .. } => {
5688                *items = checked(items, &mut check);
5689            }
5690            DesktopCommand::SetTray(Some(tray)) => {
5691                check(&mut tray.icon);
5692                tray.menu = checked(&tray.menu, &mut check);
5693            }
5694            _ => {}
5695        }
5696    }
5697
5698    /// `prop` with what the app may not reach removed: a refused image,
5699    /// video or web view source shows nothing and fails (`onError` with
5700    /// `code` `ERR_ACCESS_DENIED`).
5701    fn check_prop(&mut self, key: Key, prop: Prop) -> Prop {
5702        let prop = match prop {
5703            Prop::Native(NativeProp::AllowOrigin(Some(origin))) => {
5704                Prop::Native(NativeProp::AllowOrigin(self.check_allow_origin(&origin)))
5705            }
5706            Prop::Native(NativeProp::AllowNavigation(Some(hosts))) => {
5707                match crate::access::WebHosts::parse(&hosts) {
5708                    Ok(_) => Prop::Native(NativeProp::AllowNavigation(Some(hosts))),
5709                    Err(e) => {
5710                        self.deny(format!("`allowNavigation`: {e}"));
5711                        Prop::Native(NativeProp::AllowNavigation(None))
5712                    }
5713                }
5714            }
5715            prop => prop,
5716        };
5717        if self.access.is_unrestricted() {
5718            return prop;
5719        }
5720        let node = &self.nodes[key as usize];
5721        let (id, kind) = (node.id, node.kind);
5722        // With `webview.runtimeOrigin`, a URL `webview.hosts` does not
5723        // grant waits for the web view's `allowOrigin`, which may come
5724        // after it in this render: it is checked when the props go out.
5725        if kind == Kind::WebView
5726            && self.access.allows_runtime_origin()
5727            && let Some(url) = web_url(&prop)
5728            && !url.is_empty()
5729            && !self.access.allows_webview_with(url, self.web_origin(key))
5730        {
5731            self.web_unchecked.insert((key, id));
5732            return prop;
5733        }
5734        // Always reported: the `onError` listener may be set after the
5735        // source (JS finds the handler when the event is delivered).
5736        let report = |core: &mut Self, message: String| core.report_access_denied(id, message);
5737        let refuse = |core: &mut Self, what: &str, uri: &str, capability: &str| {
5738            report(core, not_granted(what, uri, capability));
5739        };
5740        let refuse_media = |core: &mut Self, what: &str, uri: &str| {
5741            let message = media_not_granted(what, uri, core.base_url.as_deref());
5742            report(core, message);
5743        };
5744        let no_webviews = |core: &mut Self| {
5745            report(
5746                core,
5747                "web views are not granted: add `webview` to capabilities in nsh.json".into(),
5748            );
5749        };
5750        match prop {
5751            // A loader loads what the check granted (`Access::media_url`).
5752            Prop::Source(Some(mut source)) => match self.media_source(&source.uri) {
5753                Some(granted) => {
5754                    source.uri = granted.unwrap_or(source.uri);
5755                    Prop::Source(Some(source))
5756                }
5757                None => {
5758                    refuse_media(self, "the image", &source.uri);
5759                    Prop::Source(None)
5760                }
5761            },
5762            Prop::Image(ImageProp::Placeholder(Some(mut source))) => {
5763                match self.media_source(&source.uri) {
5764                    Some(granted) => {
5765                        source.uri = granted.unwrap_or(source.uri);
5766                        Prop::Image(ImageProp::Placeholder(Some(source)))
5767                    }
5768                    None => {
5769                        refuse_media(self, "the placeholder", &source.uri);
5770                        Prop::Image(ImageProp::Placeholder(None))
5771                    }
5772                }
5773            }
5774            Prop::Native(NativeProp::Src(Some(url))) if kind == Kind::Video => {
5775                match self.media_source(&url) {
5776                    Some(granted) => Prop::Native(NativeProp::Src(Some(granted.unwrap_or(url)))),
5777                    None => {
5778                        refuse_media(self, "the video", &url);
5779                        Prop::Native(NativeProp::Src(None))
5780                    }
5781                }
5782            }
5783            Prop::Native(NativeProp::Poster(Some(url))) if kind == Kind::Video => {
5784                match self.media_source(&url) {
5785                    Some(granted) => Prop::Native(NativeProp::Poster(Some(granted.unwrap_or(url)))),
5786                    None => {
5787                        refuse_media(self, "the poster", &url);
5788                        Prop::Native(NativeProp::Poster(None))
5789                    }
5790                }
5791            }
5792            Prop::Native(NativeProp::Src(Some(url)))
5793                if kind == Kind::WebView
5794                    && !self.access.allows_webview_with(&url, self.web_origin(key)) =>
5795            {
5796                refuse(self, "the web page", &url, "webview.hosts");
5797                Prop::Native(NativeProp::Src(None))
5798            }
5799            Prop::Native(NativeProp::Html(Some(_)))
5800                if kind == Kind::WebView && !self.access.allows_webviews() =>
5801            {
5802                no_webviews(self);
5803                Prop::Native(NativeProp::Html(None))
5804            }
5805            Prop::Native(NativeProp::Source(crate::WebSource::Uri(uri))) if kind == Kind::Video => {
5806                match self.media_source(&uri) {
5807                    Some(granted) => Prop::Native(NativeProp::Source(crate::WebSource::Uri(
5808                        granted.unwrap_or(uri),
5809                    ))),
5810                    None => {
5811                        refuse_media(self, "the video", &uri);
5812                        Prop::Native(NativeProp::Source(crate::WebSource::None))
5813                    }
5814                }
5815            }
5816            Prop::Native(NativeProp::Source(crate::WebSource::Uri(uri)))
5817                if kind == Kind::WebView
5818                    && !self.access.allows_webview_with(&uri, self.web_origin(key)) =>
5819            {
5820                refuse(self, "the web page", &uri, "webview.hosts");
5821                Prop::Native(NativeProp::Source(crate::WebSource::None))
5822            }
5823            Prop::Native(NativeProp::Source(crate::WebSource::Html { .. }))
5824                if kind == Kind::WebView && !self.access.allows_webviews() =>
5825            {
5826                no_webviews(self);
5827                Prop::Native(NativeProp::Source(crate::WebSource::None))
5828            }
5829            // Inline HTML with a base URL runs at that URL's origin (WebKit's
5830            // `loadHTMLString:baseURL:`, Android's `loadDataWithBaseURL`,
5831            // Windows answering the base URL's request with it): the base
5832            // URL takes the grant a page there would, and without it the
5833            // HTML loads with no base. Without web views at all, the arms
5834            // above refuse the HTML itself, and that is the one error.
5835            Prop::Native(NativeProp::BaseUrl(Some(url)))
5836                if kind == Kind::WebView
5837                    && !url.is_empty()
5838                    && self.access.allows_webviews()
5839                    && !self.access.allows_webview_with(&url, self.web_origin(key)) =>
5840            {
5841                refuse(self, "the base URL", &url, "webview.hosts");
5842                Prop::Native(NativeProp::BaseUrl(None))
5843            }
5844            Prop::Native(NativeProp::Source(crate::WebSource::Html {
5845                html,
5846                base_url: Some(url),
5847            })) if kind == Kind::WebView
5848                && !url.is_empty()
5849                && !self.access.allows_webview_with(&url, self.web_origin(key)) =>
5850            {
5851                refuse(self, "the base URL", &url, "webview.hosts");
5852                Prop::Native(NativeProp::Source(crate::WebSource::Html {
5853                    html,
5854                    base_url: None,
5855                }))
5856            }
5857            prop => prop,
5858        }
5859    }
5860
5861    /// `allowOrigin` as the web view keeps it: the origin in its one
5862    /// written form, or none (with a message) when it is not an origin or
5863    /// the app may not add one (`webview.runtimeOrigin`).
5864    fn check_allow_origin(&mut self, origin: &str) -> Option<Arc<str>> {
5865        match crate::access::WebOrigin::parse(origin) {
5866            Err(e) => {
5867                self.deny(format!("`allowOrigin`: {e}"));
5868                None
5869            }
5870            Ok(_) if !self.access.is_unrestricted() && !self.access.allows_runtime_origin() => {
5871                self.deny(
5872                    "`allowOrigin` is not granted: add `\"runtimeOrigin\": true` to capabilities.webview in nsh.json"
5873                        .into(),
5874                );
5875                None
5876            }
5877            Ok(o) => Some(o.to_string().into()),
5878        }
5879    }
5880
5881    /// The `allowOrigin` of the web view `key`, when it has one.
5882    fn web_origin(&self, key: Key) -> Option<&crate::access::WebOrigin> {
5883        match self.nodes[key as usize].control.as_deref() {
5884            Some(NativeProps::WebView(p)) => p.allow_origin.as_ref(),
5885            _ => None,
5886        }
5887    }
5888
5889    /// Checks the URLs of web view `key` that waited for its `allowOrigin`
5890    /// ([`Self::web_unchecked`]) as its props go out: what neither
5891    /// `webview.hosts` nor its origin grants is refused as a prop would be
5892    /// (`onError` with `ERR_ACCESS_DENIED`, and nothing loaded).
5893    fn settle_web_urls(&mut self, key: Key) {
5894        let id = self.nodes[key as usize].id;
5895        if !self.web_unchecked.remove(&(key, id)) {
5896            return;
5897        }
5898        let access = &self.access;
5899        let Some(NativeProps::WebView(p)) = self.nodes[key as usize].control.as_deref_mut() else {
5900            return;
5901        };
5902        let origin = p.allow_origin.clone();
5903        let refuses =
5904            |url: &str| !url.is_empty() && !access.allows_webview_with(url, origin.as_ref());
5905        let mut messages = Vec::new();
5906        // `src`, also while `html` shows instead: clearing `html` loads it.
5907        let src = p.src.take_if(|url| refuses(url));
5908        if let Some(url) = &src {
5909            messages.push(not_granted("the web page", url, "webview.hosts"));
5910        }
5911        // What loads: `src`, or a URL Rust set as the source.
5912        if let crate::WebSource::Uri(url) = &p.source
5913            && refuses(url)
5914        {
5915            if src.as_ref() != Some(url) {
5916                messages.push(not_granted("the web page", url, "webview.hosts"));
5917            }
5918            p.source = crate::WebSource::None;
5919        }
5920        let base = p.base_url.take_if(|url| refuses(url));
5921        if let Some(url) = &base {
5922            messages.push(not_granted("the base URL", url, "webview.hosts"));
5923        }
5924        if let crate::WebSource::Html { base_url, .. } = &mut p.source
5925            && let Some(url) = base_url.take_if(|url| refuses(url))
5926            && base.as_ref() != Some(&url)
5927        {
5928            messages.push(not_granted("the base URL", &url, "webview.hosts"));
5929        }
5930        for message in messages {
5931            self.report_access_denied(id, message);
5932        }
5933    }
5934
5935    /// A refused source of node `id`: its `onError` (`ERR_ACCESS_DENIED`)
5936    /// and the app's console.
5937    fn report_access_denied(&mut self, id: NodeId, message: String) {
5938        self.events.push(crate::element::JsEvent::Event(
5939            id,
5940            EventKind::Error,
5941            EventPayload::Map(vec![
5942                ("message", PayloadValue::Str(message.clone())),
5943                (
5944                    "code",
5945                    PayloadValue::Str(crate::element::codes::ACCESS_DENIED.into()),
5946                ),
5947            ]),
5948        ));
5949        self.deny(message);
5950    }
5951
5952    /// `source` compiled, once per source while the cache keeps it (its
5953    /// error too): views that share a source, a source set again and the
5954    /// pages and dialogs that come through it use the compiled shader.
5955    fn compile(
5956        &mut self,
5957        source: &str,
5958    ) -> Result<crate::shader::Shader, crate::shader::ShaderError> {
5959        let hash = crate::shader::source_hash(source);
5960        let cached = self.shaders.get(&hash).filter(|c| match c {
5961            Ok(shader) => shader.source() == source,
5962            Err(_) => true,
5963        });
5964        if let Some(compiled) = cached {
5965            return compiled.clone();
5966        }
5967        let compiled = crate::shader::compile_source(source);
5968        // Bounded: an app making sources on the fly does not keep them all.
5969        if self.shaders.len() >= 64 {
5970            self.shaders.clear();
5971        }
5972        self.shaders.insert(hash, compiled.clone());
5973        compiled
5974    }
5975
5976    /// A page's or a dialog's `transitionShader`: compiled (once per source)
5977    /// into the layer the platform draws its coming and going through.
5978    fn set_nav_shader(&mut self, key: Key, spec: Option<crate::shader::NavShaderSpec>) {
5979        let id = self.nodes[key as usize].id;
5980        if self.nodes[key as usize].root.is_none() {
5981            log::warn!(target: "js", "`transitionShader` is a page's or a dialog's; node {id} is neither");
5982            return;
5983        }
5984        let shader = spec.and_then(|spec| {
5985            let shader = self
5986                .compile(&spec.source)
5987                .map_err(|e| log::warn!(target: "js", "the transitionShader of node {id}: {e}"))
5988                .ok()?;
5989            let mut warnings = Vec::new();
5990            let layer = crate::shader::ShaderLayer::new(shader, &spec.uniforms.0, &mut warnings)
5991                .with_role(crate::shader::ShaderRole::Transition);
5992            for warning in warnings {
5993                log::warn!(target: "js", "the transitionShader of node {id}: {warning}");
5994            }
5995            let ms = spec.duration.unwrap_or(DEFAULT_NAV_SHADER_MS).max(0.0);
5996            Some(crate::NavShader {
5997                layer: Arc::new(layer),
5998                duration: std::time::Duration::from_micros((f64::from(ms) * 1000.0).round() as u64),
5999            })
6000        });
6001        let root = self.nodes[key as usize]
6002            .root
6003            .as_mut()
6004            .expect("checked above");
6005        if root.nav_shader != shader {
6006            root.nav_shader = shader;
6007            self.mark(key, dirty::NAV_SHADER);
6008        }
6009    }
6010
6011    /// Tells the platform which shaders' pictures this commit changed
6012    /// ([`MountItem::ShaderInput`]): the effects and transitions with a
6013    /// changed view in their subtree (themselves included) or one that left
6014    /// it; every shader that reads what is behind it once a view drawn
6015    /// before it changed ([`Core::draws_before`]: not the view, what it holds
6016    /// or what draws over it), or anything that shows everywhere (the
6017    /// appearance, the tree's order); and every screen effect or
6018    /// transition, once anything changed.
6019    fn mark_shader_inputs(&mut self) {
6020        let unlinked_from = std::mem::take(&mut self.unlinked_from);
6021        // A batch that is only a layout animation is dropped (`commit`):
6022        // nothing in it changed what the pictures show.
6023        if self.pictured.is_empty()
6024            || self
6025                .mount
6026                .iter()
6027                .all(|item| matches!(item, MountItem::LayoutAnimation(_)))
6028        {
6029            return;
6030        }
6031        use crate::shader::{ShaderInput as I, ShaderRole as R};
6032        let ids: Vec<NodeId> = self.pictured.iter().copied().collect();
6033        let mut marked: Vec<NodeId> = Vec::new();
6034        let mut subtrees: Vec<(NodeId, Key)> = Vec::new();
6035        let mut backdrops: Vec<(NodeId, Key)> = Vec::new();
6036        for id in ids {
6037            let Ok(key) = self.key(id) else {
6038                self.pictured.remove(&id);
6039                continue;
6040            };
6041            let Some(layer) = self.nodes[key as usize]
6042                .shader
6043                .as_ref()
6044                .and_then(|s| s.layer.as_ref())
6045            else {
6046                continue;
6047            };
6048            let inputs = layer.shader.inputs();
6049            if matches!(layer.role, R::Screen | R::ScreenTransition) {
6050                marked.push(id);
6051                continue;
6052            }
6053            if inputs.contains(I::Backdrop) {
6054                backdrops.push((id, key));
6055            }
6056            if matches!(layer.role, R::Effect | R::Transition) {
6057                subtrees.push((id, key));
6058            }
6059        }
6060        if !backdrops.is_empty() {
6061            // What changed: the views of the items, and the parents of the
6062            // views that left (`Remove`, `Delete`), which stand in for them.
6063            let mut everywhere = false;
6064            let mut changed: Vec<Key> = Vec::new();
6065            let mut seen = rustc_hash::FxHashSet::default();
6066            for item in &self.mount {
6067                match shown_by(item) {
6068                    Shown::Nothing => {}
6069                    Shown::Everywhere => {
6070                        everywhere = true;
6071                        break;
6072                    }
6073                    Shown::View(id) => {
6074                        if seen.insert(id)
6075                            && let Ok(key) = self.key(id)
6076                        {
6077                            changed.push(key);
6078                        }
6079                    }
6080                }
6081            }
6082            for &id in &unlinked_from {
6083                if seen.insert(id)
6084                    && let Ok(key) = self.key(id)
6085                {
6086                    changed.push(key);
6087                }
6088            }
6089            for &(id, key) in &backdrops {
6090                if everywhere || self.draws_before(&changed, key) {
6091                    marked.push(id);
6092                }
6093            }
6094        }
6095        if !subtrees.is_empty() {
6096            let mut seen = rustc_hash::FxHashSet::default();
6097            // A view that left (`Remove`, `Delete`) has no parent to walk
6098            // up from any more: its old parent stands in for it.
6099            let views = self.mount.iter().filter_map(MountItem::view);
6100            for view in views.chain(unlinked_from) {
6101                if !seen.insert(view) {
6102                    continue;
6103                }
6104                let Ok(mut key) = self.key(view) else {
6105                    continue;
6106                };
6107                loop {
6108                    if let Some(&(id, _)) = subtrees.iter().find(|(_, k)| *k == key)
6109                        && !marked.contains(&id)
6110                    {
6111                        marked.push(id);
6112                    }
6113                    let parent = self.nodes[key as usize].parent;
6114                    if parent == NO_KEY {
6115                        break;
6116                    }
6117                    key = parent;
6118                }
6119            }
6120        }
6121        for id in marked {
6122            self.mount.push(MountItem::ShaderInput { id });
6123        }
6124    }
6125
6126    /// Whether one of `views` draws before `reader` (under it): an ancestor
6127    /// of it (its own box is behind it), or a view that comes before it in
6128    /// the order the views draw in, siblings by [`Node::stack_rank`] then in
6129    /// order. The reader, what it holds and what draws over it do not: they
6130    /// are not in its backdrop. A view whose way up does not meet the
6131    /// reader's (another root, an overlay's) is taken to draw before it.
6132    fn draws_before(&self, views: &[Key], reader: Key) -> bool {
6133        if views.is_empty() {
6134            return false;
6135        }
6136        // The reader's way up, the reader first: where each ancestor is on it.
6137        let mut up: Vec<Key> = Vec::new();
6138        let mut key = reader;
6139        while key != NO_KEY {
6140            up.push(key);
6141            key = self.nodes[key as usize].parent;
6142        }
6143        let at: rustc_hash::FxHashMap<Key, usize> =
6144            up.iter().enumerate().map(|(i, &k)| (k, i)).collect();
6145        views.iter().any(|&view| {
6146            let mut below = NO_KEY;
6147            let mut key = view;
6148            while key != NO_KEY {
6149                if let Some(&i) = at.get(&key) {
6150                    if i == 0 {
6151                        // The reader, or a view in it.
6152                        return false;
6153                    }
6154                    if below == NO_KEY {
6155                        // An ancestor of the reader.
6156                        return true;
6157                    }
6158                    // `key` holds both: the side of the view and the
6159                    // reader's.
6160                    return self.stacks_before(key, below, up[i - 1]);
6161                }
6162                below = key;
6163                key = self.nodes[key as usize].parent;
6164            }
6165            true
6166        })
6167    }
6168
6169    /// Whether `parent`'s child `a` draws before (under) its child `b`.
6170    fn stacks_before(&self, parent: Key, a: Key, b: Key) -> bool {
6171        let children = &self.nodes[parent as usize].children;
6172        let rank = |k: Key| {
6173            let index = children.iter().position(|&c| c == k).unwrap_or(usize::MAX);
6174            (self.nodes[k as usize].stack_rank(), index)
6175        };
6176        rank(a) < rank(b)
6177    }
6178
6179    /// A shader's `source`, program, `uniforms` or `paused`, or an effect's
6180    /// or transition's props: the layer is made again, and sent when it
6181    /// changed; a transition whose `value` changed starts.
6182    fn set_shader_prop(&mut self, key: Key, prop: Prop) {
6183        let id = self.nodes[key as usize].id;
6184        let Some(state) = self.nodes[key as usize].shader.as_mut() else {
6185            log::warn!(target: "js", "shader props are a `<Shader>`'s; node {id} is not one");
6186            return;
6187        };
6188        match prop {
6189            Prop::ShaderSource(source) => {
6190                if state.source == source {
6191                    return;
6192                }
6193                state.source = source.clone();
6194                state.shader = None;
6195                if let Some(source) = source {
6196                    let compiled = self.compile(&source);
6197                    let state = self.nodes[key as usize]
6198                        .shader
6199                        .as_mut()
6200                        .expect("shader node");
6201                    match compiled {
6202                        Ok(shader) => state.shader = Some(shader),
6203                        Err(error) => log::warn!(target: "js", "the shader of node {id}: {error}"),
6204                    }
6205                }
6206            }
6207            Prop::Shader(shader) => {
6208                state.source = None;
6209                state.shader = shader;
6210            }
6211            Prop::Uniforms(uniforms) => state.uniforms = uniforms,
6212            Prop::ShaderPaused(paused) => state.paused = paused,
6213            Prop::ShaderProgress(progress) => state.progress = progress,
6214            Prop::MaxSampleOffset(overflow) => state.overflow = overflow.max(Points::ZERO),
6215            Prop::TransitionValue(value) => state.value = value,
6216            Prop::TransitionDuration(duration) => state.duration = duration,
6217            Prop::TransitionFallback(fallback) => state.fallback = fallback,
6218            _ => return,
6219        }
6220        let state = self.nodes[key as usize]
6221            .shader
6222            .as_mut()
6223            .expect("shader node");
6224        use crate::shader::ShaderRole as R;
6225        let transition = matches!(state.role, R::Transition | R::ScreenTransition);
6226        // A transition without a shader of its own runs its fallback.
6227        let program = state.shader.clone().or_else(|| {
6228            (transition && state.fallback == crate::TransitionFallback::Fade)
6229                .then(crate::shader::crossfade)
6230                .flatten()
6231        });
6232        let layer = program.map(|shader| {
6233            let mut warnings = Vec::new();
6234            let (progress, animated) = match state.progress {
6235                crate::shader::ShaderProgress::Number(n) => (n, None),
6236                crate::shader::ShaderProgress::Animated(node) => (Percentage(0.0), Some(node)),
6237            };
6238            let layer = crate::shader::ShaderLayer::new(shader, &state.uniforms.0, &mut warnings)
6239                .with_paused(state.paused)
6240                .with_role(state.role)
6241                .with_overflow(state.overflow)
6242                .with_progress(progress, animated);
6243            for warning in warnings {
6244                log::warn!(target: "js", "the shader of node {id}: {warning}");
6245            }
6246            Arc::new(layer)
6247        });
6248        if transition && state.value != state.shown {
6249            let before = std::mem::replace(&mut state.shown, state.value.clone());
6250            let ms = state.duration.unwrap_or(DEFAULT_TRANSITION_MS).max(0.0);
6251            if before.is_some() && layer.is_some() && ms > 0.0 {
6252                self.transition_starts.push(MountItem::ShaderTransition {
6253                    id,
6254                    duration: std::time::Duration::from_micros(
6255                        (f64::from(ms) * 1000.0).round() as u64
6256                    ),
6257                });
6258            }
6259        }
6260        let state = self.nodes[key as usize]
6261            .shader
6262            .as_mut()
6263            .expect("shader node");
6264        if layer.as_ref().is_some_and(|l| {
6265            !l.shader.inputs().is_empty() || matches!(l.role, R::Screen | R::ScreenTransition)
6266        }) {
6267            self.pictured.insert(id);
6268        } else {
6269            self.pictured.remove(&id);
6270        }
6271        if layer == state.layer {
6272            return;
6273        }
6274        let nodes_of = |l: &Option<Arc<crate::shader::ShaderLayer>>| {
6275            l.as_ref().map_or(&[][..], |l| &l.nodes[..]).to_vec()
6276        };
6277        let slots_changed = nodes_of(&layer) != nodes_of(&state.layer);
6278        state.layer = layer;
6279        self.mark(
6280            key,
6281            dirty::SHADER | if slots_changed { dirty::ANIMATION } else { 0 },
6282        );
6283    }
6284
6285    fn set_prop(&mut self, id: NodeId, prop: Prop) -> Result<(), ApplyError> {
6286        let key = self.key(id)?;
6287        // Rust components: `component` makes a view a host, its props
6288        // arrive decoded (`RustProp`; platform components keep JSON).
6289        let prop = match prop {
6290            Prop::Component(name) if self.nodes[key as usize].kind == Kind::View => {
6291                self.create_instance(id, name);
6292                return Ok(());
6293            }
6294            // A GPU view names a renderer a UI set registered.
6295            Prop::Component(name) if self.nodes[key as usize].kind == Kind::GpuView => {
6296                let source = self.components.gpu_renderer(&name);
6297                if source.is_none() {
6298                    log::warn!(target: "js", "no GPU renderer is registered as `{name}`; the view draws nothing");
6299                }
6300                self.set_gpu_source(key, id, source);
6301                return Ok(());
6302            }
6303            Prop::GpuRenderer(source) => {
6304                if self.nodes[key as usize].kind == Kind::GpuView {
6305                    self.set_gpu_source(key, id, source);
6306                } else {
6307                    log::warn!("a GPU renderer on node {id}, which is no GPU view");
6308                }
6309                return Ok(());
6310            }
6311            Prop::ComponentSlot(name) => {
6312                self.set_slot_name(id, name);
6313                self.lay_out_through(key);
6314                return Ok(());
6315            }
6316            Prop::ComponentRender(slot) => {
6317                self.set_render_holder(id, slot);
6318                self.lay_out_through(key);
6319                return Ok(());
6320            }
6321            Prop::RustProp(name, value) => {
6322                if !self.set_component_prop(id, name, value) {
6323                    log::warn!(target: "js", "a Rust component's prop on node {id}, which hosts none");
6324                }
6325                return Ok(());
6326            }
6327            Prop::Follow(target) => {
6328                self.set_follow_target(key, target);
6329                return Ok(());
6330            }
6331            Prop::PassPosition(pass) => {
6332                self.set_pass_position(key, pass);
6333                return Ok(());
6334            }
6335            Prop::FollowTransition(transition) => {
6336                self.set_follow_transition(key, transition);
6337                return Ok(());
6338            }
6339            Prop::Accessibility(AccessibilityProp::ActiveDescendant(target)) => {
6340                self.set_relation(key, relations::Relation::ActiveDescendant, target);
6341                return Ok(());
6342            }
6343            Prop::Accessibility(AccessibilityProp::Controls(target)) => {
6344                self.set_relation(key, relations::Relation::Controls, target);
6345                return Ok(());
6346            }
6347            Prop::Accessibility(AccessibilityProp::DescribedBy(target)) => {
6348                self.set_relation(key, relations::Relation::DescribedBy, target);
6349                return Ok(());
6350            }
6351            Prop::ScrollEdgeElement(target) => {
6352                self.set_scroll_edge(key, target);
6353                return Ok(());
6354            }
6355            // A described view's own description waits for the element
6356            // describing it to go.
6357            Prop::Accessibility(AccessibilityProp::Description(description))
6358                if !self.relators.is_empty() && self.set_own_description(key, &description) =>
6359            {
6360                return Ok(());
6361            }
6362            prop => prop,
6363        };
6364        let prop = self.check_prop(key, prop);
6365        if let Prop::ShaderSource(_)
6366        | Prop::Shader(_)
6367        | Prop::Uniforms(_)
6368        | Prop::ShaderPaused(_)
6369        | Prop::ShaderProgress(_)
6370        | Prop::MaxSampleOffset(_)
6371        | Prop::TransitionValue(_)
6372        | Prop::TransitionDuration(_)
6373        | Prop::TransitionFallback(_) = prop
6374        {
6375            self.set_shader_prop(key, prop);
6376            return Ok(());
6377        }
6378        if let Prop::TransitionShader(spec) = prop {
6379            self.set_nav_shader(key, spec);
6380            return Ok(());
6381        }
6382        if let Prop::Screen(ScreenProp::StatusBar(setting)) = prop {
6383            self.set_status_bar(key, setting);
6384            return Ok(());
6385        }
6386        if let Prop::Screen(ScreenProp::Orientations(bits)) = prop {
6387            self.set_page_orientations(key, bits);
6388            return Ok(());
6389        }
6390        if let Prop::ListViewport(mode) = prop {
6391            self.set_list_viewport(key, mode);
6392            return Ok(());
6393        }
6394        // How a list in its parent's viewport scrolls is the scroll view's
6395        // around it.
6396        if matches!(
6397            prop,
6398            Prop::Scroll(_)
6399                | Prop::KeyboardDismissMode(_)
6400                | Prop::Scrollbar(_)
6401                | Prop::Refreshing(_)
6402                | Prop::ScrollValue(_)
6403                | Prop::PullValue(_)
6404                | Prop::Native(NativeProp::Scrollable(_))
6405        ) && let Some(list) = self.nodes[key as usize].list.as_mut().filter(|l| l.parent)
6406        {
6407            list.ignored |= match prop {
6408                Prop::Scroll(ScrollProp::RefreshIndicator(None)) => 0,
6409                Prop::Scroll(ScrollProp::RefreshIndicator(Some(_))) | Prop::PullValue(Some(_)) => {
6410                    list::ignored::REFRESH
6411                }
6412                Prop::Scroll(_)
6413                | Prop::KeyboardDismissMode(
6414                    KeyboardDismissMode::OnDrag | KeyboardDismissMode::Interactive,
6415                )
6416                | Prop::Native(NativeProp::Scrollable(false)) => list::ignored::BEHAVIOR,
6417                Prop::Scrollbar(
6418                    crate::ScrollbarSetting::Hidden
6419                    | crate::ScrollbarSetting::Themed(_)
6420                    | crate::ScrollbarSetting::ThemeValue(_),
6421                ) => list::ignored::SCROLLBAR,
6422                Prop::Refreshing(true) => list::ignored::REFRESH,
6423                Prop::ScrollValue(Some(_)) => list::ignored::SCROLL_VALUE,
6424                _ => 0,
6425            };
6426            self.warn_ignored(key);
6427            return Ok(());
6428        }
6429        let node = &mut self.nodes[key as usize];
6430        let mut flags = 0;
6431        let mut key_ancestry = false;
6432        let mut rebuild_span = false;
6433        let mut copy_text_changed = false;
6434        let mut slop_moved = false;
6435        match prop {
6436            Prop::Source(source) => {
6437                if let Some(image) = node.image.as_mut() {
6438                    // A `data:` URI is decoded here, once, not by every
6439                    // platform at every load.
6440                    let source = source.map(ImageSource::inline);
6441                    let size = source.as_ref().and_then(ImageSource::natural_size);
6442                    image.source = source;
6443                    flags |= dirty::IMAGE;
6444                    let layout = node.layout.expect("image layout");
6445                    if let Some(LeafContext::Image(natural)) =
6446                        self.layout.get_node_context_mut(layout)
6447                        && *natural != size
6448                    {
6449                        *natural = size;
6450                        self.layout.mark_dirty(layout);
6451                        self.needs_layout = true;
6452                    }
6453                }
6454            }
6455            Prop::Image(option) => {
6456                if let Some(image) = node.image.as_mut() {
6457                    match option {
6458                        ImageProp::Placeholder(source) => {
6459                            image.options.placeholder = source.map(ImageSource::inline)
6460                        }
6461                        ImageProp::BlurRadius(r) => image.options.blur_radius = r.max(Points::ZERO),
6462                        ImageProp::FadeDuration(ms) => image.options.fade_ms = ms,
6463                        ImageProp::SvgCurrentColor(on) => image.svg_current_color = on,
6464                    }
6465                    flags |= dirty::IMAGE;
6466                }
6467            }
6468            Prop::Horizontal(horizontal) => {
6469                if let Some(scroll) = node.scroll.as_mut()
6470                    && scroll.horizontal != horizontal
6471                {
6472                    scroll.horizontal = horizontal;
6473                    flags |= dirty::SCROLL;
6474                    let rtl = node.rtl;
6475                    if let Some(list) = node.list.as_mut() {
6476                        list.set_mirrored(horizontal && rtl);
6477                        list.set_horizontal(horizontal);
6478                    }
6479                    let children = node.children.clone();
6480                    self.sync_layout_style(key);
6481                    for child in children {
6482                        self.sync_layout_style(child);
6483                    }
6484                    if self.nodes[key as usize]
6485                        .list
6486                        .as_ref()
6487                        .is_some_and(|l| l.parent)
6488                    {
6489                        self.sync_spacer(key, true);
6490                        self.outer_moved = true;
6491                        // Its children are read along the new axis.
6492                        flags |= dirty::VIEW_PROPS;
6493                    }
6494                }
6495            }
6496            Prop::Scrollbar(setting) => {
6497                if let Some(scroll) = node.scroll.as_mut() {
6498                    scroll.scrollbar = setting;
6499                    flags |= dirty::SCROLL;
6500                    self.scrollbars_pending.push(key);
6501                } else if let Some(input) = node.input.as_mut() {
6502                    input.scrollbar = setting;
6503                    flags |= dirty::INPUT;
6504                    self.scrollbars_pending.push(key);
6505                }
6506            }
6507            Prop::Scroll(prop) => {
6508                if let Some(scroll) = node.scroll.as_mut() {
6509                    let b = &mut scroll.behavior;
6510                    match prop {
6511                        ScrollProp::Paging(on) => b.paging = on,
6512                        ScrollProp::SnapInterval(v) => b.snap_interval = v.max(Points::ZERO),
6513                        ScrollProp::SnapOffsets(v) => b.snap_offsets = v,
6514                        ScrollProp::SnapAlignment(a) => b.snap_alignment = a,
6515                        ScrollProp::Deceleration(r) => b.deceleration = r,
6516                        ScrollProp::Bounces(on) => b.bounces = on,
6517                        ScrollProp::ScrollsToTop(on) => b.scrolls_to_top = on,
6518                        ScrollProp::SmoothWheel(on) => b.smooth_wheel = on,
6519                        ScrollProp::WheelLineHeight(h) => b.wheel_line_height = h.max(Points::ZERO),
6520                        ScrollProp::ContentInset(i) => b.content_inset = i,
6521                        ScrollProp::ScrollbarInset(i) => {
6522                            // Negative insets count as none.
6523                            b.scrollbar_inset = i.map(|v| Points(v.0.max(0.0)));
6524                            // A built-in bar is laid out within the insets.
6525                            if scroll.bar.is_some() {
6526                                self.needs_layout = true;
6527                            }
6528                        }
6529                        ScrollProp::KeyboardTaps(t) => b.keyboard_taps = t,
6530                        ScrollProp::DisableIntervalMomentum(on) => b.one_step = on,
6531                        ScrollProp::MinZoom(v) => b.min_zoom = v.max(0.01),
6532                        ScrollProp::MaxZoom(v) => b.max_zoom = v.max(0.01),
6533                        ScrollProp::BouncesZoom(on) => b.bounces_zoom = on,
6534                        ScrollProp::Pinch(on) => b.pinch = on,
6535                        ScrollProp::CenterContent(on) => b.center_content = on,
6536                        ScrollProp::RefreshIndicator(h) => {
6537                            // No height, no indicator: every release would refresh.
6538                            b.refresh_indicator = h.filter(|h| h.0 > 0.0);
6539                        }
6540                        ScrollProp::Zoom(scale) => {
6541                            // After the limits (sent with this commit's
6542                            // behavior) are applied.
6543                            let id = node.id;
6544                            self.commands.push((
6545                                id,
6546                                Command::ZoomTo {
6547                                    scale,
6548                                    center: None,
6549                                    animated: false,
6550                                },
6551                            ));
6552                        }
6553                        ScrollProp::EventThrottle(ms) => scroll.event_throttle_ms = ms.max(0.0),
6554                        ScrollProp::ContentOffset(offset) => {
6555                            // Where it starts: scrolled there after layout.
6556                            let id = node.id;
6557                            self.commands.push((
6558                                id,
6559                                Command::ScrollTo {
6560                                    x: offset.x,
6561                                    y: offset.y,
6562                                    animated: false,
6563                                },
6564                            ));
6565                        }
6566                    }
6567                    flags |= dirty::SCROLL_BEHAVIOR;
6568                }
6569            }
6570            Prop::Refreshing(refreshing) => {
6571                if let Some(scroll) = node.scroll.as_mut() {
6572                    scroll.refreshing = refreshing;
6573                    flags |= dirty::REFRESHING;
6574                }
6575            }
6576            Prop::ScrollValue(value) => {
6577                if let Some(value) = value {
6578                    self.reach.drive(value);
6579                }
6580                if let Some(scroll) = node.scroll.as_mut() {
6581                    scroll.scroll_value = value;
6582                    flags |= dirty::SCROLL;
6583                }
6584            }
6585            Prop::PullValue(value) => {
6586                if let Some(value) = value {
6587                    self.reach.drive(value);
6588                }
6589                if let Some(scroll) = node.scroll.as_mut() {
6590                    scroll.pull_value = value;
6591                    flags |= dirty::SCROLL;
6592                }
6593            }
6594            Prop::Count(count) => {
6595                if let Some(list) = node.list.as_mut()
6596                    && list.count != count
6597                {
6598                    list.unrequest(&take_queued_binds(&mut self.list_binds, node.id));
6599                    list.set_count(count);
6600                }
6601            }
6602            Prop::EstimatedItemSize(size) => {
6603                if let Some(list) = node.list.as_mut() {
6604                    list.set_estimated(size.0);
6605                }
6606            }
6607            Prop::Slot(slot) => {
6608                node.slot = Some(slot);
6609                let parent = node.parent;
6610                if let Some(list) = self
6611                    .nodes
6612                    .get_mut(parent as usize)
6613                    .and_then(|p| p.list.as_mut())
6614                {
6615                    list.add_slot_cell(slot, key);
6616                }
6617            }
6618            Prop::Splice(at, removed, inserted) => {
6619                let loads_at_start = node.events.contains(EventKind::LoadMoreAtStart);
6620                if let Some(list) = node.list.as_mut() {
6621                    list.loads_at_start = loads_at_start;
6622                    list.unrequest(&take_queued_binds(&mut self.list_binds, node.id));
6623                    list.splice(at, removed, inserted);
6624                }
6625            }
6626            Prop::ListDiff(diff) => {
6627                let loads_at_start = node.events.contains(EventKind::LoadMoreAtStart);
6628                if let Some(list) = node.list.as_mut() {
6629                    list.loads_at_start = loads_at_start;
6630                    list.unrequest(&take_queued_binds(&mut self.list_binds, node.id));
6631                    list.reorder(&diff);
6632                }
6633            }
6634            Prop::Columns(columns) => {
6635                if let Some(list) = node.list.as_mut()
6636                    && list.set_columns(columns)
6637                {
6638                    // Its cells are laid out again at the new width, even
6639                    // when nothing else in the turn lays anything out.
6640                    self.needs_layout = true;
6641                }
6642            }
6643            Prop::Inverted(inverted) => {
6644                if let Some(list) = node.list.as_mut() {
6645                    list.set_inverted(inverted);
6646                    if list.parent {
6647                        self.warn_ignored(key);
6648                    }
6649                }
6650            }
6651            Prop::FollowEnd(threshold, animated) => {
6652                if let Some(list) = node.list.as_mut() {
6653                    list.set_follow_end(threshold.map(|t| t.0), animated);
6654                    if list.parent {
6655                        self.warn_ignored(key);
6656                    }
6657                }
6658            }
6659            Prop::ListAlignment(alignment) => {
6660                if let Some(list) = node.list.as_mut() {
6661                    list.set_alignment(alignment);
6662                    if list.parent {
6663                        self.warn_ignored(key);
6664                    }
6665                }
6666            }
6667            Prop::StickyIndices(indices) => {
6668                if let Some(list) = node.list.as_mut() {
6669                    list.set_sticky(indices);
6670                    if list.parent {
6671                        self.warn_ignored(key);
6672                    }
6673                }
6674            }
6675            Prop::StickyOffset(offset) => {
6676                if let Some(list) = node.list.as_mut() {
6677                    list.set_sticky_node(None);
6678                    list.set_sticky_offset(offset.0);
6679                    if list.parent {
6680                        self.warn_ignored(key);
6681                    }
6682                }
6683            }
6684            Prop::StickyOffsetNode(node_id) => {
6685                if let Some(list) = node.list.as_mut() {
6686                    list.set_sticky_offset(0.0);
6687                    list.set_sticky_node(node_id);
6688                }
6689            }
6690            Prop::ListContent(content) => {
6691                if let Some(list) = node.list.as_mut()
6692                    && list.set_content(content)
6693                {
6694                    self.needs_layout = true;
6695                }
6696            }
6697            Prop::Viewability(config) => {
6698                if let Some(list) = node.list.as_mut()
6699                    && list.viewability != config
6700                {
6701                    list.viewability = config;
6702                    list.dirty = true;
6703                }
6704            }
6705            Prop::LoadMoreThreshold(threshold) => {
6706                if let Some(list) = node.list.as_mut() {
6707                    list.end_threshold = threshold.max(0.0);
6708                }
6709            }
6710            Prop::LoadMoreAtStartThreshold(threshold) => {
6711                if let Some(list) = node.list.as_mut() {
6712                    list.start_threshold = threshold.max(0.0);
6713                }
6714            }
6715            Prop::CellIndex(index) => {
6716                let parent = node.parent;
6717                if let Some(list) = self
6718                    .nodes
6719                    .get_mut(parent as usize)
6720                    .and_then(|p| p.list.as_mut())
6721                {
6722                    list.rendered(key, index);
6723                }
6724            }
6725            Prop::PanValues(x, y) => {
6726                // A gesture drives them: no bound on where they take a view.
6727                for value in [x, y].into_iter().flatten() {
6728                    self.reach.drive(value);
6729                }
6730                (node.gestures.pan_x, node.gestures.pan_y) = (x, y);
6731                flags |= dirty::PAN;
6732            }
6733            Prop::PanEnabled(enabled) => {
6734                if node.pan_enabled != enabled {
6735                    node.pan_enabled = enabled;
6736                    flags |= dirty::PAN | dirty::EVENTS;
6737                }
6738            }
6739            Prop::PanScrollHandoff(value) => {
6740                let props = node.props.get_or_insert_default();
6741                if props.pan_scroll_handoff != value {
6742                    props.pan_scroll_handoff = value;
6743                    flags |= dirty::VIEW_PROPS;
6744                }
6745            }
6746            Prop::PinchValue(value) => {
6747                if let Some(value) = value {
6748                    self.reach.drive(value);
6749                }
6750                node.gestures.pinch = value;
6751                flags |= dirty::PAN;
6752            }
6753            Prop::RotationValue(value) => {
6754                if let Some(value) = value {
6755                    self.reach.drive(value);
6756                }
6757                node.gestures.rotation = value;
6758                flags |= dirty::PAN;
6759            }
6760            Prop::AllowFontScaling(allow) => {
6761                if node.paragraph.allow_font_scaling != allow {
6762                    node.paragraph.allow_font_scaling = allow;
6763                    self.font_settings_changed(key);
6764                }
6765            }
6766            Prop::SelectionColor(color) if node.input.is_none() => {
6767                if node.paragraph.selection_color != color {
6768                    node.paragraph.selection_color = color;
6769                    if node.kind == Kind::Text {
6770                        self.mark_text_block(key);
6771                    } else {
6772                        // A view's: the texts and inputs inside take it
6773                        // (`inherited_text_props`).
6774                        self.mark_inheriting_text(key);
6775                    }
6776                }
6777            }
6778            Prop::AdjustsFontSizeToFit(_) | Prop::MinimumFontScale(_) => {
6779                let before = (node.paragraph.fit, node.paragraph.min_font_scale);
6780                match prop {
6781                    Prop::AdjustsFontSizeToFit(on) => node.paragraph.fit = on,
6782                    Prop::MinimumFontScale(min) => node.paragraph.min_font_scale = min,
6783                    _ => {}
6784                }
6785                if (node.paragraph.fit, node.paragraph.min_font_scale) != before {
6786                    self.queue_text(key);
6787                    if let Some(layout) = self.nodes[key as usize].layout
6788                        && let Some(LeafContext::Text(cx)) =
6789                            self.layout.get_node_context_mut(layout)
6790                    {
6791                        cx.laid_out = None;
6792                    }
6793                }
6794            }
6795            Prop::MaxFontSizeMultiplier(max) => {
6796                if node.paragraph.max_font_multiplier != max {
6797                    node.paragraph.max_font_multiplier = max;
6798                    self.font_settings_changed(key);
6799                }
6800            }
6801            Prop::PointerEvents(value) => {
6802                let props = node.props.get_or_insert_default();
6803                if props.pointer_events != value {
6804                    props.pointer_events = value;
6805                    flags |= dirty::VIEW_PROPS;
6806                }
6807            }
6808            Prop::HitSlop(value) => {
6809                let props = node.props.get_or_insert_default();
6810                if props.hit_slop != value {
6811                    props.hit_slop = value;
6812                    flags |= dirty::VIEW_PROPS;
6813                    slop_moved = true;
6814                }
6815            }
6816            Prop::Href(value) => {
6817                let value = value.filter(|href| !href.is_empty());
6818                let props = node.props.get_or_insert_default();
6819                if props.href != value {
6820                    props.href = value;
6821                    flags |= dirty::VIEW_PROPS;
6822                    // A span's is recorded in its block's text (`link_hrefs`).
6823                    if node.kind == Kind::Text && node.inline {
6824                        rebuild_span = true;
6825                    }
6826                }
6827            }
6828            Prop::PanActivation(value) => {
6829                let props = node.props.get_or_insert_default();
6830                if props.pan_activation != value {
6831                    props.pan_activation = value;
6832                    flags |= dirty::VIEW_PROPS;
6833                }
6834            }
6835            Prop::InsetPadding(insets) | Prop::InsetMargin(insets) => {
6836                let slot = usize::from(matches!(prop, Prop::InsetMargin(_)));
6837                let mut all = node.insets.as_deref().copied().unwrap_or_default();
6838                if all[slot] != insets {
6839                    all[slot] = insets;
6840                    node.insets = (all != <[EdgeInsets; 2]>::default()).then(|| Box::new(all));
6841                    self.restyle(key);
6842                }
6843                return Ok(());
6844            }
6845            Prop::Class(names) => {
6846                self.set_classes(key, Some(names), None);
6847                return Ok(());
6848            }
6849            Prop::ClassList(list) => {
6850                self.set_classes(key, None, Some(list));
6851                return Ok(());
6852            }
6853            Prop::TailwindTheme(json) => {
6854                self.set_tailwind_theme(&json);
6855                return Ok(());
6856            }
6857            Prop::UiTheme(json) => {
6858                self.set_ui_theme(&json);
6859                return Ok(());
6860            }
6861            Prop::SnapToWindowMargin(margin) => {
6862                self.set_snap_to_window_margin(margin);
6863                return Ok(());
6864            }
6865            Prop::LayoutDirection(rtl) => {
6866                // The surface's direction (the root's): the user's language, as
6867                // JS or the policy sets it.
6868                if key == self.root && node.direction != Some(rtl) {
6869                    node.direction = Some(rtl);
6870                    self.mount.push(MountItem::LayoutDirection { rtl });
6871                    self.update_direction(key);
6872                    self.root_direction_changed(rtl);
6873                }
6874                return Ok(());
6875            }
6876            Prop::Appearance(appearance) => {
6877                // The app's appearance (the root's): `nsh.json`,
6878                // `setColorScheme`.
6879                if key == self.root {
6880                    self.set_appearance(appearance);
6881                }
6882                return Ok(());
6883            }
6884            Prop::Keymap(keymap) => {
6885                // The surface's shortcuts (the root's): `nsh/keymap`.
6886                if key == self.root {
6887                    let keymap = self.keymap_with_focus(keymap);
6888                    self.mount.push(MountItem::Keymap(keymap));
6889                }
6890                return Ok(());
6891            }
6892            Prop::LongPressDelay(value) => {
6893                let props = node.props.get_or_insert_default();
6894                if props.long_press_delay != value {
6895                    props.long_press_delay = value;
6896                    flags |= dirty::VIEW_PROPS;
6897                }
6898            }
6899            Prop::Ripple(value) => {
6900                let props = node.props.get_or_insert_default();
6901                if props.ripple != value {
6902                    props.ripple = value;
6903                    flags |= dirty::VIEW_PROPS;
6904                }
6905            }
6906            Prop::Elevation(value) => {
6907                let value = value.max(Points::ZERO);
6908                if node.elevation != value {
6909                    node.elevation = value;
6910                    flags |= dirty::VIEW;
6911                }
6912            }
6913            Prop::BackdropMaterial(value) => {
6914                if node.backdrop_material != value {
6915                    node.backdrop_material = value;
6916                    flags |= dirty::VIEW;
6917                }
6918            }
6919            Prop::MacOsBackdrop(value) => {
6920                if node.macos_backdrop != value {
6921                    node.macos_backdrop = value;
6922                    flags |= dirty::VIEW;
6923                }
6924            }
6925            Prop::WindowsBackdrop(value) => {
6926                if node.windows_backdrop != value {
6927                    node.windows_backdrop = value;
6928                    flags |= dirty::VIEW;
6929                }
6930            }
6931            Prop::ActiveStyle(patch) => {
6932                self.set_part_style(key, classes::Part::Active, patch);
6933                return Ok(());
6934            }
6935            Prop::HoverStyle(patch) => {
6936                self.set_part_style(key, classes::Part::Hover, patch);
6937                return Ok(());
6938            }
6939            Prop::FocusStyle(patch) => {
6940                self.set_part_style(key, classes::Part::Focus, patch);
6941                return Ok(());
6942            }
6943            Prop::DisabledStyle(patch) => {
6944                self.set_part_style(key, classes::Part::Disabled, patch);
6945                return Ok(());
6946            }
6947            Prop::SelectedStyle(patch) => {
6948                self.set_part_style(key, classes::Part::Selected, patch);
6949                return Ok(());
6950            }
6951            Prop::CheckedStyle(patch) => {
6952                self.set_part_style(key, classes::Part::Checked, patch);
6953                return Ok(());
6954            }
6955            Prop::IndeterminateStyle(patch) => {
6956                self.set_part_style(key, classes::Part::Indeterminate, patch);
6957                return Ok(());
6958            }
6959            Prop::PressedStyle(patch) => {
6960                self.set_part_style(key, classes::Part::Pressed, patch);
6961                return Ok(());
6962            }
6963            Prop::ExpandedStyle(patch) => {
6964                self.set_part_style(key, classes::Part::Expanded, patch);
6965                return Ok(());
6966            }
6967            Prop::FocusWithinStyle(patch) => {
6968                self.set_part_style(key, classes::Part::FocusWithin, patch);
6969                return Ok(());
6970            }
6971            Prop::FocusVisibleStyle(patch) => {
6972                self.set_part_style(key, classes::Part::FocusVisible, patch);
6973                return Ok(());
6974            }
6975            Prop::ProjectedStates(states) => {
6976                self.set_projected_states(key, states);
6977                return Ok(());
6978            }
6979            Prop::ProjectedData(data) => {
6980                self.set_projected_data(key, data);
6981                return Ok(());
6982            }
6983            Prop::ProjectedActive(group) => {
6984                self.set_projected_active(key, group);
6985                return Ok(());
6986            }
6987            Prop::HeaderStyle(patch) => {
6988                self.set_part_style(key, classes::Part::Header, patch);
6989                return Ok(());
6990            }
6991            Prop::HeaderClass(names) => {
6992                self.set_part_class(key, classes::Part::Header, &names);
6993                return Ok(());
6994            }
6995            Prop::HeaderClassList(list) => {
6996                self.set_part_class_list(key, classes::Part::Header, list);
6997                return Ok(());
6998            }
6999            Prop::ListContentClass(names) => {
7000                self.set_part_class(key, classes::Part::Content, &names);
7001                return Ok(());
7002            }
7003            Prop::TestId(value) => {
7004                let props = node.props.get_or_insert_default();
7005                if props.test_id != value {
7006                    props.test_id = value;
7007                    flags |= dirty::VIEW_PROPS;
7008                    // A span's id is recorded in its block's text.
7009                    if node.kind == Kind::Text && node.inline {
7010                        rebuild_span = true;
7011                    }
7012                }
7013            }
7014            Prop::ClearsKeyboard(value) => {
7015                if node.clears_keyboard != value {
7016                    // The `env()` terms in its subtree may come to
7017                    // something else: `sync_env` compares them all at the
7018                    // end of the commit and restyles the ones that did.
7019                    node.clears_keyboard = value;
7020                }
7021            }
7022            Prop::CopyText(value) => {
7023                if node.copy_text != value {
7024                    node.copy_text = value;
7025                    // Its block's text holds it; a render's content's is
7026                    // its placeholder's (`Core::attachment_copy_text`).
7027                    copy_text_changed = true;
7028                }
7029            }
7030            Prop::WebElement(value) => {
7031                let props = node.props.get_or_insert_default();
7032                if props.web_element != value {
7033                    props.web_element = value;
7034                    flags |= dirty::VIEW_PROPS;
7035                }
7036            }
7037            Prop::WindowDrag(value) => {
7038                let props = node.props.get_or_insert_default();
7039                if props.window_drag != value {
7040                    props.window_drag = value;
7041                    flags |= dirty::VIEW_PROPS;
7042                }
7043            }
7044            Prop::WindowControl(value) => {
7045                let props = node.props.get_or_insert_default();
7046                if props.window_control != value {
7047                    props.window_control = value;
7048                    flags |= dirty::VIEW_PROPS;
7049                }
7050            }
7051            Prop::WindowResize(value) => {
7052                let props = node.props.get_or_insert_default();
7053                if props.window_resize != value {
7054                    props.window_resize = value;
7055                    flags |= dirty::VIEW_PROPS;
7056                }
7057            }
7058            Prop::Focusable(value) => {
7059                let props = node.props.get_or_insert_default();
7060                if props.focusable != value {
7061                    props.focusable = value;
7062                    flags |= dirty::VIEW_PROPS;
7063                }
7064            }
7065            Prop::KeyCapture(value) => {
7066                let props = node.props.get_or_insert_default();
7067                if props.key_capture != value {
7068                    props.key_capture = value;
7069                    flags |= dirty::VIEW_PROPS;
7070                    key_ancestry = true;
7071                }
7072            }
7073            Prop::SelectableView(value) => {
7074                let props = node.props.get_or_insert_default();
7075                if props.selectable_view != value {
7076                    props.selectable_view = value;
7077                    flags |= dirty::VIEW_PROPS;
7078                }
7079            }
7080            Prop::SelectionMenu(items) => {
7081                let items: std::sync::Arc<[crate::desktop::MenuItem]> =
7082                    crate::desktop::MenuItem::selection_menu(&items).into();
7083                let props = node.props.get_or_insert_default();
7084                if props.selection_menu != items {
7085                    props.selection_menu = items;
7086                    flags |= dirty::VIEW_PROPS;
7087                }
7088            }
7089            Prop::ContinuesText(value) => {
7090                let props = node.props.get_or_insert_default();
7091                if props.continues_text != value {
7092                    props.continues_text = value;
7093                    flags |= dirty::VIEW_PROPS;
7094                }
7095            }
7096            Prop::Accessibility(prop) => {
7097                // A label changing on mounted props goes alone: it is
7098                // the one that follows app state (a count, a value).
7099                let label_only =
7100                    node.props.is_some() && matches!(prop, AccessibilityProp::Label(_));
7101                let props = node.props.get_or_insert_default();
7102                let a = &mut props.accessibility;
7103                let before = a.clone();
7104                match prop {
7105                    AccessibilityProp::Accessible(v) => a.accessible = v,
7106                    AccessibilityProp::Label(v) => a.label = v,
7107                    AccessibilityProp::Hint(v) => a.hint = v,
7108                    AccessibilityProp::Description(v) => a.description = v,
7109                    AccessibilityProp::Role(v) => a.role = v,
7110                    AccessibilityProp::State(v) => a.state = v,
7111                    AccessibilityProp::Value(v) => a.value = v,
7112                    AccessibilityProp::Hidden(v) => a.hidden = v,
7113                    AccessibilityProp::Important(accessible, hidden) => {
7114                        a.accessible = accessible;
7115                        a.hidden = hidden;
7116                    }
7117                    AccessibilityProp::LiveRegion(v) => a.live_region = v,
7118                    AccessibilityProp::Actions(v) => a.actions = v,
7119                    AccessibilityProp::Level(v) => a.level = v,
7120                    AccessibilityProp::Orientation(v) => a.orientation = v,
7121                    // Set as relations, above.
7122                    AccessibilityProp::ActiveDescendant(_)
7123                    | AccessibilityProp::Controls(_)
7124                    | AccessibilityProp::DescribedBy(_) => {}
7125                }
7126                let states = classes::accessibility_states(&a.state);
7127                let states_changed = states != classes::accessibility_states(&before.state);
7128                if *a != before {
7129                    flags |= if label_only {
7130                        dirty::LABEL
7131                    } else {
7132                        dirty::VIEW_PROPS
7133                    };
7134                }
7135                if states_changed {
7136                    if flags != 0 {
7137                        self.mark(key, flags);
7138                    }
7139                    self.set_accessibility_states(key, states);
7140                    return Ok(());
7141                }
7142            }
7143            Prop::KeyboardDismissMode(mode) => {
7144                if let Some(scroll) = node.scroll.as_mut() {
7145                    scroll.keyboard_dismiss = mode;
7146                    flags |= dirty::SCROLL;
7147                }
7148            }
7149            // `animation` on a dialog: the value pages and dialogs share.
7150            Prop::Screen(ScreenProp::Animation(a)) if node.kind == Kind::Modal => {
7151                if let Some(root) = node.root.as_mut() {
7152                    root.modal.animation = match a {
7153                        ScreenAnimation::Default => ModalAnimation::Slide,
7154                        ScreenAnimation::Fade => ModalAnimation::Fade,
7155                        ScreenAnimation::None => ModalAnimation::None,
7156                    };
7157                    flags |= dirty::MODAL;
7158                }
7159            }
7160            Prop::Screen(prop) => {
7161                if let Some(root) = node.root.as_mut() {
7162                    let c = &mut root.screen;
7163                    match prop {
7164                        ScreenProp::Title(v) => c.title = v,
7165                        ScreenProp::HeaderVisible(v) => c.header_visible = v,
7166                        ScreenProp::HeaderLargeTitle(v) => c.large_title = v,
7167                        ScreenProp::HeaderTransparent(v) => c.header_transparent = v,
7168                        ScreenProp::HeaderShadowVisible(v) => c.header_shadow_visible = v,
7169                        ScreenProp::HeaderTitleAlign(v) => c.title_align = v,
7170                        ScreenProp::HeaderBackgroundOnScroll(v) => {
7171                            c.header_background_on_scroll = v
7172                        }
7173                        ScreenProp::HidesBottomBarWhenPushed(v) => {
7174                            c.hides_bottom_bar_when_pushed = v
7175                        }
7176                        ScreenProp::HeaderBackTitle(v) => c.back_title = v,
7177                        ScreenProp::HeaderBackVisible(v) => c.back_visible = v,
7178                        ScreenProp::HeaderRightSystemItem(v) => c.right_system_item = v,
7179                        ScreenProp::HeaderRightSymbol(v) => c.right_symbol = v,
7180                        ScreenProp::HeaderLeftSystemItem(v) => c.left_system_item = v,
7181                        ScreenProp::HeaderLeftSymbol(v) => c.left_symbol = v,
7182                        ScreenProp::HeaderRightItems(v) => c.right_items = v,
7183                        ScreenProp::HeaderLeftItems(v) => c.left_items = v,
7184                        ScreenProp::PopOnSwipe(v) => c.gesture_enabled = v,
7185                        ScreenProp::PopOnBack(v) => c.prevent_back = !v,
7186                        ScreenProp::Animation(v) => c.animation = v,
7187                        // Taken by `set_prop`.
7188                        ScreenProp::StatusBar(_) | ScreenProp::Orientations(_) => {}
7189                    }
7190                    // Header changes move the content.
7191                    root.laid_out = None;
7192                    self.needs_layout = true;
7193                    flags |= dirty::SCREEN;
7194                }
7195            }
7196            Prop::NativeId(name) => {
7197                if node.kind == Kind::InputAccessory {
7198                    let attached = node.parent != NO_KEY;
7199                    if attached {
7200                        self.accessory_attached(key, false);
7201                    }
7202                    if let Some(root) = self.nodes[key as usize].root.as_mut() {
7203                        root.native_id = name;
7204                    }
7205                    if attached {
7206                        self.accessory_attached(key, true);
7207                    }
7208                    return Ok(());
7209                }
7210                // Other views: the embedding app finds them by it
7211                // (`watchScroll`).
7212                let value: Option<Arc<str>> = name.as_deref().map(Into::into);
7213                let props = node.props.get_or_insert_default();
7214                if props.native_id != value {
7215                    props.native_id = value;
7216                    flags |= dirty::VIEW_PROPS;
7217                }
7218            }
7219            Prop::Modal(prop) => {
7220                if let Some(root) = node.root.as_mut() {
7221                    let c = &mut root.modal;
7222                    match prop {
7223                        ModalProp::Animation(v) => c.animation = v,
7224                        ModalProp::Presentation(v) => c.presentation = v,
7225                        ModalProp::StatusBarTranslucent(v) => c.status_bar_translucent = v,
7226                        ModalProp::Orientations(v) => c.orientations = v,
7227                        ModalProp::CloseOnEscape(v) => c.close_on_escape = v,
7228                        ModalProp::CloseOnBackdropPress(v) => c.close_on_backdrop_press = v,
7229                        ModalProp::CloseOnSwipe(v) => c.close_on_swipe = v,
7230                        ModalProp::Detents(v) => c.detents = v,
7231                        ModalProp::Detent(v) => c.detent = v,
7232                        ModalProp::DefaultDetent(v) => c.default_detent = v,
7233                        ModalProp::Grabber(v) => c.grabber = v,
7234                        ModalProp::LargestUndimmedDetent(v) => c.largest_undimmed_detent = v,
7235                    }
7236                    flags |= dirty::MODAL;
7237                }
7238            }
7239            Prop::Overlay(prop) => {
7240                use crate::OverlayProp;
7241                // A hint makes an overlay a tooltip's, which counts among no
7242                // siblings (`is_element_child`): theirs move.
7243                let parent = node.parent;
7244                if matches!(prop, OverlayProp::Hint(_))
7245                    && parent != NO_KEY
7246                    && self.nodes[parent as usize]
7247                        .positional
7248                        .has(Positional::CHILDREN)
7249                {
7250                    self.queue_positions(parent);
7251                }
7252                self.set_overlay_config(key, |c| match prop {
7253                    OverlayProp::Anchor(v) => c.anchor = v,
7254                    OverlayProp::Placement(v) => c.placement = v,
7255                    OverlayProp::Align(v) => c.align = v,
7256                    OverlayProp::Offset(v) => c.offset = v,
7257                    OverlayProp::Margin(v) => c.margin = v,
7258                    OverlayProp::Hint(v) => c.hint = v,
7259                    OverlayProp::Open(v) => c.open = v,
7260                    OverlayProp::Cover(v) => c.cover = v,
7261                });
7262                if matches!(prop, OverlayProp::Margin(_))
7263                    && let Some(state) = self.overlay_mut(key)
7264                    && !state.margin_set
7265                {
7266                    state.margin_set = true;
7267                    state.placed = None;
7268                    self.needs_layout = true;
7269                }
7270                return Ok(());
7271            }
7272            Prop::Tooltip(content) => {
7273                self.set_tooltip(key, content);
7274                return Ok(());
7275            }
7276            Prop::HeaderSlot(slot) => {
7277                if let Some(root) = node.root.as_mut()
7278                    && root.slot != slot
7279                {
7280                    root.slot = slot;
7281                    let parent = node.parent;
7282                    if parent != NO_KEY {
7283                        self.mark(parent, dirty::SCREEN);
7284                    }
7285                }
7286            }
7287            // `scrollable` of scroll views and lists.
7288            Prop::Native(NativeProp::Scrollable(on)) if node.scroll.is_some() => {
7289                if let Some(scroll) = node.scroll.as_mut() {
7290                    scroll.behavior.enabled = on;
7291                    flags |= dirty::SCROLL_BEHAVIOR;
7292                }
7293            }
7294            Prop::Component(name) => {
7295                let created = node.created;
7296                if let Some(component) = node.component.as_mut() {
7297                    match &component.name {
7298                        // Named after its native view was made (a Rust
7299                        // component whose root is `native()` takes its
7300                        // host's place, which is made first): the platform
7301                        // is told now, and gets every prop again after it.
7302                        None if created => {
7303                            component.name = Some(name.clone());
7304                            component.changed =
7305                                component.props.iter().map(|(k, _)| k.clone()).collect();
7306                            self.mount.push(MountItem::Component { id, name });
7307                            flags |= dirty::COMPONENT;
7308                            if !component.slots.is_empty() {
7309                                component.slots_changed.set(true);
7310                                flags |= dirty::ANIMATION;
7311                            }
7312                        }
7313                        None => component.name = Some(name),
7314                        Some(old) if *old != name => log::warn!(
7315                            target: "js",
7316                            "a native component cannot change from `{old}` to `{name}`; render a new element"
7317                        ),
7318                        Some(_) => {}
7319                    }
7320                }
7321            }
7322            Prop::ComponentPropBinding(name, value) => {
7323                if let Some(component) = node.component.as_mut() {
7324                    let slot = match component.slots.iter().position(|k| *k == name) {
7325                        Some(s) => Some(s as u16),
7326                        None if value.is_none() => None,
7327                        None => {
7328                            component.slots.push(name.clone());
7329                            component.slots_changed.set(true);
7330                            Some((component.slots.len() - 1) as u16)
7331                        }
7332                    };
7333                    if let Some(slot) = slot {
7334                        let at = component.bound.iter().position(|(s, _)| *s == slot);
7335                        match (at, value) {
7336                            (Some(i), Some(n)) => component.bound[i].1 = n,
7337                            (None, Some(n)) => component.bound.push((slot, n)),
7338                            (Some(i), None) => {
7339                                component.bound.remove(i);
7340                                // Its static value (or its removal) is sent again.
7341                                if !component.changed.contains(&name) {
7342                                    component.changed.push(name);
7343                                }
7344                                flags |= dirty::COMPONENT;
7345                            }
7346                            (None, None) => {}
7347                        }
7348                        flags |= dirty::ANIMATION;
7349                    }
7350                }
7351            }
7352            Prop::ComponentProp(name, value) => {
7353                if let Some(component) = node.component.as_mut() {
7354                    let at = component.props.iter().position(|(k, _)| *k == name);
7355                    match (at, value) {
7356                        (Some(i), Some(v)) => component.props[i].1 = v,
7357                        (None, Some(v)) => component.props.push((name.clone(), v)),
7358                        (Some(i), None) => {
7359                            component.props.swap_remove(i);
7360                        }
7361                        (None, None) => {}
7362                    }
7363                    if !component.changed.contains(&name) {
7364                        component.changed.push(name);
7365                    }
7366                    flags |= dirty::COMPONENT;
7367                }
7368            }
7369            Prop::Native(prop) => {
7370                if let NativeProp::Disabled(d) = prop {
7371                    // `disabled:` classes, on any element.
7372                    self.set_disabled(key, d);
7373                }
7374                let node = &mut self.nodes[key as usize];
7375                // The platforms make a web view with its website data store
7376                // and the URL schemes it serves, from its first props.
7377                if node.created
7378                    && let Some(NativeProps::WebView(p)) = node.control.as_deref()
7379                {
7380                    let changed = match &prop {
7381                        NativeProp::Incognito(on) => Some(("`incognito` is", *on != p.incognito)),
7382                        NativeProp::Zoomable(on) => Some(("`zoomable` is", *on != p.zoomable)),
7383                        // A re-render builds new handlers: only a change
7384                        // of the schemes served is worth a warning.
7385                        NativeProp::UrlSchemes(schemes) => Some((
7386                            "URL schemes are",
7387                            !schemes
7388                                .iter()
7389                                .map(|s| s.scheme())
7390                                .eq(p.url_schemes.iter().map(|s| s.scheme())),
7391                        )),
7392                        _ => None,
7393                    };
7394                    if let Some((what, changed)) = changed {
7395                        if changed {
7396                            log::warn!(
7397                                target: "js",
7398                                "a web view's {what} read when it is made; render a new element to change it"
7399                            );
7400                        }
7401                        return Ok(());
7402                    }
7403                }
7404                if let Some(control) = node.control.as_mut() {
7405                    apply_native(control, prop);
7406                    flags |= dirty::NATIVE;
7407                }
7408            }
7409            Prop::Value(value) => {
7410                if let Some(input) = node.input.as_mut() {
7411                    input.value_set = true;
7412                    if input.value != value {
7413                        input.value = value;
7414                        flags |= dirty::INPUT_VALUE;
7415                        self.measure_input(key);
7416                    }
7417                }
7418            }
7419            Prop::DefaultValue(value) => {
7420                if let Some(input) = node.input.as_mut()
7421                    && !input.value_set
7422                {
7423                    input.value_set = true;
7424                    input.value = value;
7425                    flags |= dirty::INPUT_VALUE;
7426                    self.measure_input(key);
7427                }
7428            }
7429            prop => {
7430                let Some(input) = node.input.as_mut() else {
7431                    return Ok(());
7432                };
7433                let c = &mut input.config;
7434                let remeasure = match prop {
7435                    Prop::Placeholder(text) => {
7436                        c.placeholder = text;
7437                        true
7438                    }
7439                    Prop::Multiline(multiline) => {
7440                        c.multiline = multiline;
7441                        // Only a multiline input shows a built-in bar.
7442                        self.scrollbars_pending.push(key);
7443                        true
7444                    }
7445                    Prop::PlaceholderColor(color) => {
7446                        c.placeholder_color = color;
7447                        false
7448                    }
7449                    Prop::Secure(secure) => {
7450                        c.secure = secure;
7451                        false
7452                    }
7453                    Prop::KeyboardType(keyboard) => {
7454                        c.keyboard = keyboard;
7455                        false
7456                    }
7457                    Prop::KeyboardAppearance(appearance) => {
7458                        c.keyboard_appearance = appearance;
7459                        false
7460                    }
7461                    Prop::ReturnKeyType(key) => {
7462                        c.return_key = key;
7463                        false
7464                    }
7465                    Prop::AutoCapitalize(mode) => {
7466                        c.auto_capitalize = mode;
7467                        false
7468                    }
7469                    Prop::AutoCorrect(on) => {
7470                        c.auto_correct = on;
7471                        false
7472                    }
7473                    Prop::MaxLength(len) => {
7474                        c.max_length = len;
7475                        false
7476                    }
7477                    Prop::Readonly(on) => {
7478                        c.editable = !on;
7479                        false
7480                    }
7481                    Prop::SubmitBehavior(behavior) => {
7482                        c.submit_behavior = behavior;
7483                        false
7484                    }
7485                    Prop::PasteBehavior(behavior) => {
7486                        c.paste_behavior = behavior;
7487                        false
7488                    }
7489                    Prop::PasteMaxSize(max) => {
7490                        c.paste_max_size = max;
7491                        false
7492                    }
7493                    Prop::AutoFocus(on) => {
7494                        c.auto_focus = on;
7495                        false
7496                    }
7497                    Prop::SelectTextOnFocus(on) => {
7498                        c.select_text_on_focus = on;
7499                        false
7500                    }
7501                    Prop::Caret(on) => {
7502                        c.caret_hidden = !on;
7503                        false
7504                    }
7505                    Prop::InputAccessoryViewId(name) => {
7506                        c.accessory_id = name;
7507                        false
7508                    }
7509                    Prop::SelectionColor(color) => {
7510                        c.selection_color = color;
7511                        false
7512                    }
7513                    Prop::CaretColor(color) => {
7514                        c.caret_color = color;
7515                        false
7516                    }
7517                    Prop::AutoFill(fill) => {
7518                        c.auto_fill = fill;
7519                        false
7520                    }
7521                    Prop::Selection(start, end) => {
7522                        // Applied after the batch's value.
7523                        let id = node.id;
7524                        self.commands
7525                            .push((id, Command::SetSelection { start, end }));
7526                        return Ok(());
7527                    }
7528                    _ => return Ok(()),
7529                };
7530                flags |= dirty::INPUT;
7531                if remeasure {
7532                    self.measure_input(key);
7533                }
7534            }
7535        }
7536        if flags != 0 {
7537            self.mark(key, flags);
7538        }
7539        if slop_moved {
7540            self.slop_moved.push(key);
7541        }
7542        if rebuild_span {
7543            self.mark_text_block(key);
7544        }
7545        if copy_text_changed {
7546            if self.nodes[key as usize].inline {
7547                self.mark_text_block(key);
7548            } else if let Some(place) = self.placed_in_text(key) {
7549                self.mark_text_block(place);
7550            }
7551        }
7552        if key_ancestry {
7553            self.key_ancestry_dirty = true;
7554        }
7555        Ok(())
7556    }
7557
7558    /// Puts loose run `child_id` in text block or span `parent` without a
7559    /// node when it is the only child there; false when it cannot.
7560    fn fold_run(
7561        &mut self,
7562        parent: Key,
7563        parent_id: NodeId,
7564        child_id: NodeId,
7565        before: Option<NodeId>,
7566    ) -> bool {
7567        let node = &self.nodes[parent as usize];
7568        if before.is_some()
7569            || node.kind != Kind::Text
7570            || !node.children.is_empty()
7571            || self.folded.contains_key(&parent)
7572            || self.components.slot_hosts.contains_key(&parent_id)
7573        {
7574            return false;
7575        }
7576        let Some(run) = self.runs.get_mut(&child_id) else {
7577            return false;
7578        };
7579        // Moved from another block (no Remove first).
7580        let from = std::mem::replace(&mut run.block, parent);
7581        if from != NO_KEY {
7582            self.folded.remove(&from);
7583            self.mark_text_block(from);
7584        }
7585        self.folded.insert(parent, child_id);
7586        self.mark_text_block(parent);
7587        true
7588    }
7589
7590    /// Takes run `id` out of its block, keeping it without a node.
7591    fn unfold_run(&mut self, id: NodeId) {
7592        let Some(run) = self.runs.get_mut(&id) else {
7593            return;
7594        };
7595        let block = std::mem::replace(&mut run.block, NO_KEY);
7596        if block != NO_KEY {
7597            self.folded.remove(&block);
7598            self.mark_text_block(block);
7599        }
7600    }
7601
7602    /// Gives run `id` its node, in its block if it is in one (for any use
7603    /// other than holding text as a block's only child). Remove it from
7604    /// `runs` during allocation so the quota counts it only once, and
7605    /// restore it on failure so its block keeps its text.
7606    pub(super) fn materialize_run(&mut self, id: NodeId) -> Result<(), ApplyError> {
7607        let Some(run) = self.runs.remove(&id) else {
7608            return Ok(());
7609        };
7610        let key = match self.alloc(id, Kind::RawText) {
7611            Ok(key) => key,
7612            Err(e) => {
7613                self.runs.insert(id, run);
7614                return Err(e);
7615            }
7616        };
7617        self.nodes[key as usize].text = run.text;
7618        if run.block != NO_KEY {
7619            self.folded.remove(&run.block);
7620            let parent = self.nodes[run.block as usize].id;
7621            let _ = self.insert(parent, id, None);
7622        }
7623        Ok(())
7624    }
7625
7626    /// The text of the run text block or span `key` holds without a node.
7627    fn folded_text(&self, key: Key) -> Option<&str> {
7628        if self.folded.is_empty() {
7629            return None;
7630        }
7631        let id = self.folded.get(&key)?;
7632        self.runs.get(id).map(|r| r.text.as_str())
7633    }
7634
7635    fn insert(
7636        &mut self,
7637        parent_id: NodeId,
7638        child_id: NodeId,
7639        before: Option<NodeId>,
7640    ) -> Result<(), ApplyError> {
7641        let parent = self.key(parent_id)?;
7642        if !self.runs.is_empty() || !self.folded.is_empty() {
7643            if self.fold_run(parent, parent_id, child_id, before) {
7644                return Ok(());
7645            }
7646            self.materialize_run(child_id)?;
7647            if let Some(b) = before {
7648                self.materialize_run(b)?;
7649            }
7650            if let Some(&run) = self.folded.get(&parent) {
7651                self.materialize_run(run)?;
7652            }
7653        }
7654        let child = self.key(child_id)?;
7655        let from = self.nodes[child as usize].parent;
7656        if from != NO_KEY {
7657            self.input_bar_moves(child);
7658            self.note_move(from, parent);
7659        }
7660        let mut before = before.map(|b| self.key(b)).transpose()?;
7661        // Appended below the built-in bar, which stays on top.
7662        if before.is_none()
7663            && let Some((bar, _)) = self.nodes[parent as usize]
7664                .scroll
7665                .as_ref()
7666                .and_then(|s| s.bar.as_ref())
7667            && let Ok(bar) = self.key(*bar)
7668            && bar != child
7669        {
7670            before = Some(bar);
7671        }
7672        let Some(depth) = self
7673            .depth_outside(child, parent)
7674            .filter(|_| child != self.root)
7675        else {
7676            return Err(ApplyError::Cycle(child_id));
7677        };
7678        let max = MAX_TREE_DEPTH as u32;
7679        if depth + self.nodes[child as usize].height > max {
7680            // What left the child since may have made it shallower.
7681            if depth + self.count_heights(child) > max {
7682                return Err(ApplyError::TooDeep(MAX_TREE_DEPTH));
7683            }
7684        }
7685        if self.nodes[parent as usize]
7686            .shader
7687            .as_ref()
7688            .is_some_and(|s| {
7689                matches!(
7690                    s.role,
7691                    crate::shader::ShaderRole::Screen | crate::shader::ShaderRole::ScreenTransition
7692                )
7693            })
7694        {
7695            // It takes no space, so a child lays out in nothing: the
7696            // surface is what it draws through.
7697            log::warn!(
7698                target: "js",
7699                "node {child_id} in screen effect {parent_id}: a screen effect or transition has no children"
7700            );
7701        }
7702        if let Some(b) = before
7703            && (b == child || self.nodes[b as usize].parent != parent)
7704        {
7705            return Err(ApplyError::BadAnchor(self.nodes[b as usize].id));
7706        }
7707
7708        // Detach from the current position. A native view that stays visible
7709        // is moved by the insert below, so only emit a remove when the new
7710        // parent has no native view.
7711        let parent_created = self.nodes[parent as usize].created;
7712        if self.nodes[child as usize].parent != NO_KEY {
7713            self.unlink(child, !parent_created);
7714        }
7715
7716        let p = &self.nodes[parent as usize];
7717        // Inside a block or a span (not inside an attachment: its children
7718        // are its own layout's).
7719        let inline = p.kind == Kind::Text && !self.nodes[child as usize].fixed_view;
7720        let pos = match before {
7721            Some(b) => {
7722                let (pos, looked) = position_from_ends(&p.children, &b).expect("anchor is a child");
7723                self.placing(looked);
7724                pos
7725            }
7726            None => p.children.len(),
7727        };
7728        self.set_inline(child, inline);
7729        if !inline {
7730            // An attachment hidden with its span leaves the text: shown
7731            // where it goes (in a text, its block decides again).
7732            self.set_hidden_in_text(child, false);
7733        }
7734        self.nodes[child as usize].parent = parent;
7735        if self.nodes[child as usize].kind == Kind::Overlay {
7736            // Its logical parent changed: find its keyboard override again.
7737            self.key_ancestry_dirty = true;
7738        }
7739        self.nodes[parent as usize].children.insert(pos, child);
7740        self.dirty_overlays();
7741        self.raise_heights(child);
7742        self.key_content_changed(parent);
7743        self.rank_noted(child);
7744        self.tree_order_changed |= self.track_tree_order;
7745        self.tab_places_stale = true;
7746        if self.nodes[child as usize].states & crate::tailwind::state::FOCUS_WITHIN != 0 {
7747            // The focus moved with it: the views around it now.
7748            self.focus_moved = true;
7749        }
7750        self.ch_changed(child);
7751        self.status_bars_moved |= !self.status_bar_nodes.is_empty();
7752        self.outer_moved |= !self.parent_lists.is_empty() && self.may_hold_page_list(child);
7753        self.sticky_changed |= !self.sticky_nodes.is_empty();
7754        self.update_direction(child);
7755        if self.nodes[parent as usize].child_perspective.is_some() {
7756            self.mark(child, dirty::VIEW | dirty::ANIMATION);
7757        }
7758        let node = &self.nodes[parent as usize];
7759        let color = node.text_style.color.or(node.inherited_color);
7760        if self.nodes[child as usize].inherited_color != color {
7761            self.inherit_color_from(child, color);
7762        }
7763        self.groups_changed(child, parent);
7764        let child_node = &self.nodes[child as usize];
7765        if child_node
7766            .classes
7767            .as_ref()
7768            .is_some_and(|c| c.deps() & crate::tailwind::deps::POSITION != 0)
7769            // A view passing its position on reads it for its children.
7770            || (child_node.positional.has(Positional::PASS)
7771                && child_node.positional.has(Positional::CHILDREN))
7772        {
7773            self.reads_positions(parent);
7774        }
7775        if self.nodes[parent as usize]
7776            .positional
7777            .has(Positional::CHILDREN)
7778        {
7779            self.queue_positions(parent);
7780        }
7781        self.spacing_changed(parent, child);
7782        if self.pointer_none_classes > 0 {
7783            self.pointer_events_moved(parent);
7784        }
7785
7786        if inline {
7787            if self.nodes[child as usize].placeholder {
7788                self.ask_row(child);
7789            }
7790            self.mark_text_block(parent);
7791            return Ok(());
7792        }
7793        // A cell joining a list: register its slot and derive its style
7794        // from the list orientation.
7795        if self.nodes[parent as usize].list.is_some() {
7796            if let Some(slot) = self.nodes[child as usize].slot {
7797                self.nodes[parent as usize]
7798                    .list
7799                    .as_mut()
7800                    .expect("list")
7801                    .add_slot_cell(slot, child);
7802            }
7803            self.sync_layout_style(child);
7804        }
7805        let child_kind = self.nodes[child as usize].kind;
7806        if child_kind == Kind::InputAccessory {
7807            self.accessory_attached(child, true);
7808        }
7809        if child_kind == Kind::HeaderItem {
7810            self.mark(parent, dirty::SCREEN);
7811        }
7812        if let Some(child_layout) = self.nodes[child as usize].layout {
7813            // List cells, screens, modals and header items stay independent
7814            // layout roots.
7815            if self.nodes[parent as usize].list.is_none()
7816                && !self.nodes[child as usize].is_layout_root()
7817            {
7818                let index = self.layout_index_at(parent, pos);
7819                let parent_layout = self.nodes[parent as usize]
7820                    .layout
7821                    .expect("block parent has layout");
7822                self.layout
7823                    .insert_child_at_index(parent_layout, index as usize, child_layout);
7824            }
7825            self.needs_layout = true;
7826            // A dialog opening in content a scroll view has not made yet
7827            // makes the views around it: it shows over everything.
7828            let parent_created = parent_created
7829                || (child_kind == Kind::Modal
7830                    && self.nodes[parent as usize].culled
7831                    && self.uncull(parent));
7832            // An overlay's native view goes to its root view
7833            // (`sync_overlays`).
7834            if parent_created
7835                && !self.nodes[child as usize].is_overlay()
7836                && !{
7837                    let scope = self.cull_scope(parent);
7838                    self.hold_back(scope, child)
7839                }
7840            {
7841                self.ensure_created(child);
7842                let before = match self.nodes[parent as usize].list.as_ref() {
7843                    // Below the sticky cells of a list in its parent's
7844                    // viewport, which stay on top.
7845                    Some(list) if list.parent && !list.sent_sticky.is_empty() => {
7846                        self.below_sticky(parent, child)
7847                    }
7848                    _ => self.native_before_at(parent, child, pos),
7849                };
7850                // By the nodes' own ids (the ops may name an alias).
7851                self.mount.push(MountItem::Insert {
7852                    parent: self.nodes[parent as usize].id,
7853                    child: self.nodes[child as usize].id,
7854                    before,
7855                });
7856            }
7857        }
7858        Ok(())
7859    }
7860
7861    /// Detaches `key` from its parent (Remove op).
7862    fn detach(&mut self, key: Key) {
7863        self.input_bar_moves(key);
7864        self.unlink(key, true);
7865    }
7866
7867    /// A multiline input with a built-in bar beside it leaves its place:
7868    /// the bar goes, and is made again beside it where it goes.
7869    fn input_bar_moves(&mut self, key: Key) {
7870        let node = &self.nodes[key as usize];
7871        if node.input.as_ref().is_some_and(|i| i.bar.is_some()) {
7872            self.release_scrollbar(key);
7873            self.scrollbars_pending.push(key);
7874        }
7875    }
7876
7877    /// Unlinks `key` from its parent's children, layout and (optionally)
7878    /// native hierarchy.
7879    fn unlink(&mut self, key: Key, emit_remove: bool) {
7880        if self.nodes[key as usize].kind == Kind::Modal && self.nodes[key as usize].created {
7881            self.restoring_modal_focus = true;
7882        }
7883        let parent = self.nodes[key as usize].parent;
7884        let siblings = &mut self.nodes[parent as usize].children;
7885        let pos = siblings
7886            .iter()
7887            .position(|&c| c == key)
7888            .expect("child of parent");
7889        siblings.remove(pos);
7890        self.key_content_changed(parent);
7891        self.tree_order_changed |= self.track_tree_order;
7892        self.tab_places_stale = true;
7893        if let Some(list) = self.nodes[parent as usize].list.as_mut() {
7894            list.remove_cell(key);
7895        }
7896        if self.nodes[parent as usize]
7897            .positional
7898            .has(Positional::CHILDREN)
7899        {
7900            self.queue_positions(parent);
7901        }
7902        self.nodes[key as usize].parent = NO_KEY;
7903        self.dirty_overlays();
7904        if self.nodes[key as usize].states & crate::tailwind::state::FOCUS_WITHIN != 0 {
7905            // The focus left the views around it with it.
7906            self.focus_moved = true;
7907        }
7908        if self.nodes[parent as usize].child_perspective.is_some() {
7909            // Without the perspective wherever it goes next.
7910            self.mark(key, dirty::VIEW | dirty::ANIMATION);
7911        }
7912        self.spacing_changed(parent, NO_KEY);
7913        if self.pointer_none_classes > 0 && self.pointer_region(parent).is_some() {
7914            // It no longer inherits the region's `none`.
7915            self.pointer_pending.push(key);
7916            self.pointer_events_moved(parent);
7917        }
7918        self.groups_changed(key, parent);
7919        self.status_bars_moved |= !self.status_bar_nodes.is_empty();
7920        self.outer_moved |= !self.parent_lists.is_empty() && self.may_hold_page_list(key);
7921        self.sticky_changed |= !self.sticky_nodes.is_empty();
7922        if !self.pictured.is_empty() {
7923            self.unlinked_from.push(self.nodes[parent as usize].id);
7924        }
7925        let node = &self.nodes[key as usize];
7926        let (inline, layout, created, id) = (node.inline, node.layout, node.created, node.id);
7927        // Replaced by its row, of another size: the scroll views keep what
7928        // they show in place (`resize_anchor.rs`).
7929        self.resize_settling |= node.row_asked;
7930        if inline {
7931            self.mark_text_block(parent);
7932            return;
7933        }
7934        let kind = self.nodes[key as usize].kind;
7935        if kind == Kind::InputAccessory {
7936            self.accessory_attached(key, false);
7937        }
7938        if kind == Kind::HeaderItem {
7939            self.mark(parent, dirty::SCREEN);
7940        }
7941        if let Some(layout) = layout {
7942            if self.nodes[parent as usize].list.is_none()
7943                && !self.nodes[key as usize].is_layout_root()
7944            {
7945                let parent_layout = self.nodes[parent as usize]
7946                    .layout
7947                    .expect("block parent has layout");
7948                self.layout.remove_child(parent_layout, layout);
7949            }
7950            self.needs_layout = true;
7951            if emit_remove
7952                && created
7953                && self.nodes[parent as usize].created
7954                && !self.nodes[key as usize].is_overlay()
7955            {
7956                self.mount.push(MountItem::Remove { id });
7957                self.note_restructured(parent);
7958            }
7959        }
7960    }
7961
7962    /// A page's or dialog's `statusBar`: changed in place while the node
7963    /// is in the tree (so it keeps its place among the others); its entry
7964    /// is added or removed by [`Core::sync_status_bars`].
7965    fn set_status_bar(&mut self, key: Key, setting: Option<crate::StatusBarSetting>) {
7966        let Some(root) = self.nodes[key as usize].root.as_mut() else {
7967            return;
7968        };
7969        root.status_bar = setting;
7970        let entry = root.status_bar_entry;
7971        match (setting, entry) {
7972            (Some(s), Some(e)) => self.components.status_bars.set(e, s),
7973            (Some(_), None) => {
7974                if !self.status_bar_nodes.contains(&key) {
7975                    self.status_bar_nodes.push(key);
7976                }
7977                self.status_bars_moved = true;
7978            }
7979            (None, entry) => {
7980                if let Some(e) = entry {
7981                    self.components.status_bars.remove(e);
7982                    if let Some(root) = self.nodes[key as usize].root.as_mut() {
7983                        root.status_bar_entry = None;
7984                    }
7985                }
7986                self.status_bar_nodes.retain(|&k| k != key);
7987            }
7988        }
7989    }
7990
7991    /// The `statusBar` of each screen and modal in the tree has an entry,
7992    /// added in the order they got their setting; the others have none
7993    /// (once per commit, after the tree changed).
7994    fn sync_status_bars(&mut self) {
7995        if !std::mem::take(&mut self.status_bars_moved) {
7996            return;
7997        }
7998        for i in 0..self.status_bar_nodes.len() {
7999            let key = self.status_bar_nodes[i];
8000            let in_tree = self.is_ancestor(self.root, key);
8001            let Some(root) = self.nodes[key as usize].root.as_mut() else {
8002                continue;
8003            };
8004            match (in_tree, root.status_bar_entry, root.status_bar) {
8005                (true, None, Some(setting)) => {
8006                    root.status_bar_entry = Some(self.components.status_bars.add(setting));
8007                }
8008                (false, Some(entry), _) => {
8009                    root.status_bar_entry = None;
8010                    self.components.status_bars.remove(entry);
8011                }
8012                _ => {}
8013            }
8014        }
8015    }
8016
8017    fn release(&mut self, id: NodeId) -> Result<(), ApplyError> {
8018        if let Some(run) = self.runs.remove(&id) {
8019            if run.block != NO_KEY {
8020                self.folded.remove(&run.block);
8021                self.mark_text_block(run.block);
8022            }
8023            return Ok(());
8024        }
8025        let key = self.key(id)?;
8026        // Its run is orphaned like its children.
8027        if let Some(run) = self.folded.remove(&key)
8028            && let Some(run) = self.runs.get_mut(&run)
8029        {
8030            run.block = NO_KEY;
8031        }
8032        self.cancel_web_evaluations(id);
8033        self.webview_released(id);
8034        if key == self.root {
8035            return Ok(());
8036        }
8037        // What the core made for its `tooltip` goes first, out of it.
8038        if !self.overlay_state.tooltips.is_empty() {
8039            self.tooltip_released(id);
8040        }
8041        // So does its built-in bar.
8042        if self.nodes[key as usize].bar().is_some() {
8043            self.release_scrollbar(key);
8044        }
8045        if self.nodes[key as usize].parent != NO_KEY {
8046            // Deleting the view also detaches it natively.
8047            self.unlink(key, false);
8048        }
8049        // Out of the view it was virtualized against, before its key is
8050        // free for another node.
8051        if self.nodes[key as usize]
8052            .list
8053            .as_ref()
8054            .is_some_and(|l| l.parent)
8055        {
8056            self.forget_outer(key);
8057            self.parent_lists.retain(|&k| k != key);
8058        }
8059        if self.nodes[key as usize].is_overlay() {
8060            self.dirty_overlays();
8061        }
8062        self.dirty_overlay_listeners();
8063        let node = self.nodes.remove(key as usize);
8064        self.ch_readers -= usize::from(node.reads_ch);
8065        self.slots.remove(id as usize);
8066        if node.class_props.as_ref().and_then(|c| c.pointer_events)
8067            == Some(crate::props::PointerEvents::None)
8068        {
8069            self.pointer_none_classes -= 1;
8070        }
8071        if node.kind == Kind::List {
8072            self.lists.retain(|&k| k != key);
8073        }
8074        if node.sticky.is_some() {
8075            self.sticky_nodes.retain(|&k| k != key);
8076            self.sticky_changed = true;
8077        }
8078        if node.follow.is_some() {
8079            self.release_follower(key);
8080        }
8081        if !self.relators.is_empty() {
8082            self.release_relator(key);
8083        }
8084        if let Some(scroll) = node.scroll.as_ref() {
8085            if !scroll.dependents.is_empty() {
8086                self.outer_released(&scroll.dependents);
8087            }
8088            if scroll.asked.is_some() {
8089                self.outer_asked.retain(|&k| k != key);
8090            }
8091            self.sticky_views.retain(|&k| k != key);
8092            self.sticky_scrollers.retain(|&k| k != key);
8093        }
8094        if let Some((spacer, _)) = node.list.as_ref().and_then(|l| l.spacer) {
8095            self.layout.remove(spacer);
8096        }
8097        if node.kind == Kind::Text {
8098            self.attachment_blocks.retain(|&k| k != key);
8099        }
8100        if node.is_layout_root() {
8101            self.roots.retain(|&k| k != key);
8102        }
8103        if let Some(state) = node.root.as_ref().and_then(|r| r.overlay.as_ref()) {
8104            self.overlay_released(key, state.wrapper, state.host.is_some());
8105        }
8106        if let Some(root) = node.root.as_ref()
8107            && root.status_bar.is_some()
8108        {
8109            if let Some(entry) = root.status_bar_entry {
8110                self.components.status_bars.remove(entry);
8111            }
8112            self.status_bar_nodes.retain(|&k| k != key);
8113        }
8114        self.orientation_pages.retain(|&(k, _)| k != key);
8115        // Children are released by their own ops (the whole subtree became
8116        // unreachable in JS); orphan them so they never point at a dead key.
8117        for &c in &node.children {
8118            if let Some(child) = self.nodes.get_mut(c as usize) {
8119                child.parent = NO_KEY;
8120            }
8121        }
8122        if node.states & crate::tailwind::state::FOCUS_WITHIN != 0 {
8123            // The focus went with it, or is inside a child no longer in
8124            // it.
8125            self.focus_moved = true;
8126        }
8127        if let Some(layout) = node.layout {
8128            self.layout.remove(layout);
8129        }
8130        if node.created {
8131            self.mount.push(MountItem::Delete { id });
8132        }
8133        Ok(())
8134    }
8135
8136    /// A page's `supportedOrientations` (0: none): changed in place, so it
8137    /// keeps its place among the others.
8138    fn set_page_orientations(&mut self, key: Key, bits: u8) {
8139        match self.orientation_pages.iter_mut().find(|(k, _)| *k == key) {
8140            Some(page) if bits != 0 => page.1 = bits,
8141            Some(_) => self.orientation_pages.retain(|&(k, _)| k != key),
8142            None if bits != 0 => self.orientation_pages.push((key, bits)),
8143            None => {}
8144        }
8145    }
8146
8147    /// Sends the orientations of the page that decides them when they
8148    /// changed (once per commit): the last to get its setting of those in
8149    /// the tree and displayed, so a page kept in a tab that is not shown
8150    /// (`display: none`) does not decide while another tab is. Pages with a
8151    /// setting are few, and the walk is up their ancestors only.
8152    fn sync_orientations(&mut self) {
8153        if self.orientation_pages.is_empty() && self.orientations_shown == 0 {
8154            return;
8155        }
8156        let bits = self
8157            .orientation_pages
8158            .iter()
8159            .rev()
8160            .find(|&&(key, _)| self.displayed_in_tree(key))
8161            .map_or(0, |&(_, bits)| bits);
8162        if bits != self.orientations_shown {
8163            self.orientations_shown = bits;
8164            self.commands
8165                .push((crate::ROOT_ID, Command::Orientations(bits)));
8166        }
8167    }
8168
8169    /// Whether `key` is in the tree with no `display: none` on it or on any
8170    /// view above it, across layout roots (a page under a hidden tab).
8171    fn displayed_in_tree(&self, mut key: Key) -> bool {
8172        while key != NO_KEY {
8173            if key == self.root {
8174                return true;
8175            }
8176            let node = &self.nodes[key as usize];
8177            if node.layout.is_some_and(|l| self.layout.displays_none(l)) {
8178                return false;
8179            }
8180            key = node.parent;
8181        }
8182        false
8183    }
8184
8185    /// How many views are above `key` and `key` itself (1 for a view with
8186    /// no parent), or `None` when `ancestor` is one of them.
8187    fn depth_outside(&self, ancestor: Key, mut key: Key) -> Option<u32> {
8188        let mut depth = 0;
8189        while key != NO_KEY {
8190            if key == ancestor {
8191                return None;
8192            }
8193            depth += 1;
8194            key = self.nodes[key as usize].parent;
8195        }
8196        Some(depth)
8197    }
8198
8199    /// Counts how many levels of views are under each view of `key`'s
8200    /// subtree, keeps each count as that view's [`Node::height`] and returns
8201    /// `key`'s. Every view of it, not only `key`: [`Self::raise_heights`] stops at the first
8202    /// view already as high as what came under it, so a view left higher
8203    /// than it is would keep the views above it from hearing of what grows
8204    /// under it later.
8205    fn count_heights(&mut self, key: Key) -> u32 {
8206        // Each view after its parent: from the end, its children are
8207        // counted before it.
8208        let mut order = vec![key];
8209        let mut next = 0;
8210        while let Some(&at) = order.get(next) {
8211            next += 1;
8212            order.extend_from_slice(&self.nodes[at as usize].children);
8213        }
8214        for &at in order.iter().rev() {
8215            let height = self.nodes[at as usize]
8216                .children
8217                .iter()
8218                .map(|&c| self.nodes[c as usize].height + 1)
8219                .max()
8220                .unwrap_or(0);
8221            self.nodes[at as usize].height = height;
8222        }
8223        self.nodes[key as usize].height
8224    }
8225
8226    /// The app's keymap as mounted: with how the focus came
8227    /// (`Keymap::pointer_focus`) when a binding asks for
8228    /// it, kept to mount again as the focus moves (`sync_pointer_keymap`).
8229    fn keymap_with_focus(
8230        &mut self,
8231        keymap: Arc<crate::keymap::Keymap>,
8232    ) -> Arc<crate::keymap::Keymap> {
8233        if !keymap.takes_over_pointer_focus() {
8234            self.pointer_keymap = None;
8235            return keymap;
8236        }
8237        let pointer = self.focus.is_some() && self.focus_by_pointer;
8238        let mounted = Arc::new((*keymap).clone().with_pointer_focus(pointer));
8239        self.pointer_keymap = Some((keymap, pointer));
8240        mounted
8241    }
8242
8243    /// The focus a pointer gave came or went: the keymap whose bindings
8244    /// ask for it is mounted again, so the platform matches the next keys
8245    /// with it. One item per move, only for an app that asks.
8246    fn sync_pointer_keymap(&mut self) {
8247        let pointer = self.focus.is_some() && self.focus_by_pointer;
8248        let Some((keymap, sent)) = &self.pointer_keymap else {
8249            return;
8250        };
8251        if *sent == pointer {
8252            return;
8253        }
8254        let keymap = keymap.clone();
8255        let mounted = self.keymap_with_focus(keymap);
8256        self.mount.push(MountItem::Keymap(mounted));
8257    }
8258
8259    /// `key` came under its parent: the views above it are as high as it
8260    /// makes them. Stops at the first that was already: a view is always at
8261    /// least one higher than each of its children.
8262    fn raise_heights(&mut self, key: Key) {
8263        let mut height = self.nodes[key as usize].height + 1;
8264        let mut at = self.nodes[key as usize].parent;
8265        while at != NO_KEY {
8266            let node = &mut self.nodes[at as usize];
8267            if node.height >= height {
8268                break;
8269            }
8270            node.height = height;
8271            height += 1;
8272            at = node.parent;
8273        }
8274    }
8275
8276    /// A popup that gives the keyboard focus back to `to` opens
8277    /// ([`crate::element::ElementRef::focus_back_origin`]): on macOS and
8278    /// iOS, opened by a pointer, the focus it opened with is where the focus goes back to
8279    /// (the pointer's press left it there, off the trigger); elsewhere the
8280    /// trigger takes it back as the pointer's (`pointer_focus_back`);
8281    /// opened by the keyboard, the trigger takes it back, as before.
8282    pub(super) fn note_focus_origin(&mut self, to: NodeId) {
8283        let mut origins = std::mem::take(&mut self.focus_origins);
8284        // Triggers that are gone leave no note behind (a popup closed by a
8285        // press outside gives nothing back, so its note stays until then).
8286        origins.retain(|&(id, _)| id != to && self.key(id).is_ok());
8287        if self.modality == Some(crate::platform::InputModality::Pointer) {
8288            origins.push((to, self.focus));
8289        }
8290        self.focus_origins = origins;
8291    }
8292
8293    /// Whether a press leaves the keyboard focus where it is (macOS and
8294    /// iOS, as AppKit and UIKit do), so a popup a pointer opened gives it
8295    /// back where it was. Elsewhere a press focuses the trigger, as native
8296    /// buttons there do, and closing gives the trigger the focus.
8297    fn press_leaves_focus(&self) -> bool {
8298        matches!(
8299            self.components.environment.os,
8300            crate::platform::Os::MacOs | crate::platform::Os::Ios
8301        )
8302    }
8303
8304    /// The keyboard focus back from the popup `from` (its node, when it is
8305    /// still there) to `before`, the focus a pointer opened it with: there
8306    /// when that view is still in the tree and outside the popup, else off
8307    /// the popup, so its keys go to the app's shortcuts as they did before
8308    /// it opened.
8309    fn focus_back_to_origin(&mut self, before: Option<(Key, NodeId)>, from: Option<Key>) {
8310        let outside = |this: &Self, key: Key| from.is_none_or(|from| !this.is_ancestor(from, key));
8311        let alive = |this: &Self, (key, id): (Key, NodeId)| {
8312            this.key(id).is_ok_and(|k| k == key) && this.is_ancestor(this.root, key)
8313        };
8314        if let Some((_, id)) = before.filter(|&b| alive(self, b) && outside(self, b.0)) {
8315            self.commands.push((id, Command::Focus));
8316        } else if let Some((_, id)) = self.focus.filter(|&(key, _)| !outside(self, key)) {
8317            self.commands.push((id, Command::Blur));
8318        }
8319    }
8320
8321    /// A dialog opening gives the keyboard focus to its first control, as
8322    /// the web's `<dialog>` and the desktops' dialogs do, unless the focus
8323    /// is already inside it or goes there in this commit (`autoFocus`, the
8324    /// app's `focus()`). Desktops and the web only: a phone would raise
8325    /// its keyboard for a field.
8326    fn focus_opened_modals(&mut self) {
8327        let opened = std::mem::take(&mut self.modals_opened);
8328        if !self.has_window() {
8329            return;
8330        }
8331        for (modal, id) in opened {
8332            // Opened and removed again in the same commit.
8333            let Some(node) = self.nodes.get(modal as usize).filter(|n| n.id == id) else {
8334                continue;
8335            };
8336            if node.kind != Kind::Modal
8337                || !node.created
8338                || node.parent == NO_KEY
8339                || !self.displayed_in_tree(modal)
8340                // A window of the app's own is no dialog.
8341                || self.window_ids.values().any(|(root, _)| *root == node.id)
8342            {
8343                continue;
8344            }
8345            if self
8346                .focus
8347                .is_some_and(|(key, _)| self.is_ancestor(modal, key))
8348            {
8349                continue;
8350            }
8351            let inside = |this: &Self, id: NodeId| {
8352                this.key(id).is_ok_and(|key| this.is_ancestor(modal, key))
8353            };
8354            let asked = self
8355                .commands
8356                .iter()
8357                .any(|(to, c)| matches!(c, Command::Focus) && inside(self, *to))
8358                || self.mount.iter().any(|m| {
8359                    matches!(
8360                        m,
8361                        MountItem::Command {
8362                            id: to,
8363                            command: Command::Focus,
8364                        } if inside(self, *to)
8365                    )
8366                });
8367            if asked {
8368                continue;
8369            }
8370            // A field that focuses itself (`autoFocus`) is `Err`.
8371            if let Ok(Some(id)) = self.first_control(modal) {
8372                self.commands.push((id, Command::Focus));
8373                self.modal_focus_given = Some(id);
8374            }
8375        }
8376    }
8377
8378    /// The first view under `key` (depth first) the keyboard focus can go
8379    /// to: an enabled input, or an enabled view that takes presses or is
8380    /// `focusable`. Not in a hidden subtree, an overlay or another modal.
8381    /// `Err` when an input under it focuses itself (`autoFocus`).
8382    fn first_control(&self, key: Key) -> Result<Option<NodeId>, ()> {
8383        let mut found = None;
8384        let mut stack: Vec<Key> = self.nodes[key as usize]
8385            .children
8386            .iter()
8387            .rev()
8388            .copied()
8389            .collect();
8390        while let Some(k) = stack.pop() {
8391            let node = &self.nodes[k as usize];
8392            if matches!(node.kind, Kind::Overlay | Kind::Modal)
8393                || node.layout.is_some_and(|l| self.layout.displays_none(l))
8394            {
8395                continue;
8396            }
8397            let disabled = node.states & crate::tailwind::state::DISABLED != 0;
8398            let focusable = node.props.as_ref().and_then(|p| p.focusable);
8399            if let Some(input) = node.input.as_ref() {
8400                if input.config.auto_focus {
8401                    return Err(());
8402                }
8403                if found.is_none() && !disabled && focusable != Some(false) {
8404                    found = Some(node.id);
8405                }
8406            } else if found.is_none()
8407                && !disabled
8408                && (focusable == Some(true)
8409                    || (focusable.is_none() && node.mounted_events().contains(EventKind::Press)))
8410            {
8411                found = Some(node.id);
8412            }
8413            stack.extend(node.children.iter().rev().copied());
8414        }
8415        Ok(found)
8416    }
8417
8418    /// The stop after `key` in the Tab order (`forward`) or before it, as
8419    /// the keyboard focus would move from it: of the dialog `key` is in, or
8420    /// else its window's root view, depth first in the app's tree (an
8421    /// overlay where the app put it), wrapping around at the ends. The
8422    /// stops are those of [`Self::first_control`]; not under `skip` (the
8423    /// popup closing), another modal, an overlay not shown or a hidden
8424    /// subtree. `None` when no other view is a stop.
8425    fn tab_neighbor(&self, key: Key, forward: bool, skip: Option<Key>) -> Option<NodeId> {
8426        let mut scope = key;
8427        while self.nodes[scope as usize].parent != NO_KEY
8428            && self.nodes[scope as usize].kind != Kind::Modal
8429        {
8430            scope = self.nodes[scope as usize].parent;
8431        }
8432        let mut stops = Vec::new();
8433        let mut at = None;
8434        let mut stack = vec![scope];
8435        while let Some(k) = stack.pop() {
8436            let node = &self.nodes[k as usize];
8437            let hidden = (k != scope && node.kind == Kind::Modal)
8438                || Some(k) == skip
8439                || (node.kind == Kind::Overlay && self.overlay(k).is_none_or(|s| s.host.is_none()))
8440                || node.layout.is_some_and(|l| self.layout.displays_none(l));
8441            if hidden {
8442                continue;
8443            }
8444            let disabled = node.states & crate::tailwind::state::DISABLED != 0;
8445            let focusable = node.props.as_ref().and_then(|p| p.focusable);
8446            let stop = !disabled
8447                && match node.input {
8448                    Some(_) => focusable != Some(false),
8449                    None => {
8450                        focusable == Some(true)
8451                            || (focusable.is_none()
8452                                && node.mounted_events().contains(EventKind::Press))
8453                    }
8454                };
8455            if k == key {
8456                at = Some(stops.len());
8457                stops.push(node.id);
8458            } else if stop {
8459                stops.push(node.id);
8460            }
8461            stack.extend(node.children.iter().rev().copied());
8462        }
8463        let at = at?;
8464        let n = stops.len();
8465        if n < 2 {
8466            return None;
8467        }
8468        let next = if forward {
8469            (at + 1) % n
8470        } else {
8471            (at + n - 1) % n
8472        };
8473        Some(stops[next])
8474    }
8475
8476    fn is_ancestor(&self, ancestor: Key, mut key: Key) -> bool {
8477        while key != NO_KEY {
8478            if key == ancestor {
8479                return true;
8480            }
8481            key = self.nodes[key as usize].parent;
8482        }
8483        false
8484    }
8485
8486    /// The native sibling `child` goes below: native views are stacked by
8487    /// `zIndex`, then in tree order.
8488    fn native_before(&self, parent: Key, child: Key) -> Option<NodeId> {
8489        let pos = self.nodes[parent as usize]
8490            .children
8491            .iter()
8492            .inspect(|_| self.placing(1))
8493            .position(|&c| c == child)?;
8494        self.native_before_at(parent, child, pos)
8495    }
8496
8497    /// [`Self::native_before`] for `child` at `pos` among its siblings.
8498    /// When none of them was ever stacked apart, the next made sibling.
8499    ///
8500    /// A view in its parent never goes below a sibling the platform places
8501    /// elsewhere (a screen, a modal, a header item, an input accessory):
8502    /// that sibling is not among the parent's native subviews, so the
8503    /// platform would add the view on top of the others instead.
8504    fn native_before_at(&self, parent: Key, child: Key, pos: usize) -> Option<NodeId> {
8505        let children = &self.nodes[parent as usize].children;
8506        let z = self.nodes[child as usize].stack_rank();
8507        let in_parent = !self.nodes[child as usize].kind.is_root();
8508        let anchors = |n: &Node| {
8509            n.created && n.layout.is_some() && !n.is_overlay() && !(in_parent && n.kind.is_root())
8510        };
8511        if !self.nodes[parent as usize].ranked_children && z == (0, false) {
8512            let next = children[pos + 1..].iter().find_map(|&c| {
8513                self.placing(1);
8514                let n = &self.nodes[c as usize];
8515                anchors(n).then_some(n.id)
8516            });
8517            return match next {
8518                Some(id) => Some(id),
8519                None if !self.overlays.is_empty() => self.first_overlay_in(parent),
8520                None => None,
8521            };
8522        }
8523        self.placing(children.len());
8524        let mut best: Option<((i32, bool), usize, NodeId)> = None;
8525        for (i, &c) in children.iter().enumerate() {
8526            let n = &self.nodes[c as usize];
8527            if c == child || !anchors(n) {
8528                continue;
8529            }
8530            let rank = n.stack_rank();
8531            if (rank, i) > (z, pos) && best.is_none_or(|b| (rank, i) < (b.0, b.1)) {
8532                best = Some((rank, i, n.id));
8533            }
8534        }
8535        // Below the overlays shown in it, when it is a root view.
8536        match best {
8537            Some(b) => Some(b.2),
8538            None if !self.overlays.is_empty() => self.first_overlay_in(parent),
8539            None => None,
8540        }
8541    }
8542
8543    /// Notes on `key`'s parent that `key` is stacked apart from the
8544    /// others, when it is ([`Node::ranked_children`]).
8545    fn rank_noted(&mut self, key: Key) {
8546        let node = &self.nodes[key as usize];
8547        let parent = node.parent;
8548        if parent != NO_KEY && node.stack_rank() != (0, false) {
8549            self.nodes[parent as usize].ranked_children = true;
8550        }
8551    }
8552
8553    /// `key`'s `zIndex` changed: moves its native view among its siblings.
8554    fn restack(&mut self, key: Key) {
8555        self.rank_noted(key);
8556        let node = &self.nodes[key as usize];
8557        let (parent, id) = (node.parent, node.id);
8558        if parent == NO_KEY
8559            || !node.created
8560            || node.layout.is_none()
8561            || node.inline
8562            || node.is_overlay()
8563        {
8564            return;
8565        }
8566        let p = &self.nodes[parent as usize];
8567        if !p.created || p.list.is_some() {
8568            return;
8569        }
8570        let before = self.native_before(parent, key);
8571        self.mount.push(MountItem::Insert {
8572            parent: p.id,
8573            child: id,
8574            before,
8575        });
8576    }
8577
8578    /// `allowFontScaling` / `maxFontSizeMultiplier` changed on `key`.
8579    fn font_settings_changed(&mut self, key: Key) {
8580        match self.nodes[key as usize].kind {
8581            Kind::Text => self.mark_text_block(key),
8582            Kind::Input => {
8583                self.measure_input(key);
8584                self.mark(key, dirty::INPUT);
8585            }
8586            _ => {}
8587        }
8588    }
8589
8590    /// Where the child at `pos` among `parent`'s children goes among the
8591    /// children of `parent`'s layout node: before the layout node of the
8592    /// next sibling that has one (the layout node's children are those
8593    /// siblings', in order), or after them all. Looks at the siblings next
8594    /// to it and at the layout children near `pos`, not at every sibling
8595    /// before it: views inserted before the one after a list's rows, or
8596    /// before the first of a chat's messages, look at a few of them each.
8597    fn layout_index_at(&self, parent: Key, pos: usize) -> u32 {
8598        let node = &self.nodes[parent as usize];
8599        let layout = node.layout.expect("block parent has layout");
8600        let next = node.children[pos + 1..]
8601            .iter()
8602            .inspect(|_| self.placing(1))
8603            .find_map(|&c| {
8604                let c = &self.nodes[c as usize];
8605                c.layout.filter(|_| !c.is_layout_root())
8606            });
8607        let index = match next {
8608            // As many layout children are before it as siblings with one
8609            // are: at most `pos`, fewer by those without one.
8610            Some(next) => match position_near(self.layout.children(layout), &next, pos) {
8611                Some((index, looked)) => {
8612                    self.placing(looked);
8613                    index
8614                }
8615                None => {
8616                    debug_assert!(false, "a sibling's layout node is its parent's child");
8617                    self.render_index(parent, pos) as usize
8618                }
8619            },
8620            None => self.layout.children_len(layout),
8621        };
8622        debug_assert!(
8623            pos + 1 != node.children.len() || index as u32 == self.rendering_before(parent, pos),
8624            "the layout node's children are its rendering children"
8625        );
8626        index as u32
8627    }
8628
8629    /// The rendering siblings before `pos` among `parent`'s children,
8630    /// counted: what [`Self::layout_index_at`] finds without counting them.
8631    /// Looks at each of them ([`Components::placing_work`]).
8632    fn render_index(&self, parent: Key, pos: usize) -> u32 {
8633        self.placing(pos);
8634        self.rendering_before(parent, pos)
8635    }
8636
8637    /// [`Self::render_index`] uncounted, for the check of debug builds.
8638    fn rendering_before(&self, parent: Key, pos: usize) -> u32 {
8639        self.nodes[parent as usize].children[..pos]
8640            .iter()
8641            .map(|&c| &self.nodes[c as usize])
8642            .filter(|c| c.layout.is_some() && !c.is_layout_root())
8643            .count() as u32
8644    }
8645
8646    /// Moves `key` (and its subtree) into or out of an inline context.
8647    fn set_inline(&mut self, key: Key, inline: bool) {
8648        let node = &mut self.nodes[key as usize];
8649        if node.inline == inline {
8650            return;
8651        }
8652        node.inline = inline;
8653        if node.kind == Kind::Text {
8654            if inline {
8655                // Block -> span: spans have no layout node or native view; the
8656                // span keeps the style for when it is a block again.
8657                if let Some(l) = node.layout.take() {
8658                    if node.base_layout.is_none() {
8659                        node.base_layout = Some(Box::new(self.layout.style(l).clone()));
8660                    }
8661                    self.layout.remove(l);
8662                }
8663                if node.created {
8664                    node.created = false;
8665                    self.mount.push(MountItem::Delete { id: node.id });
8666                }
8667            } else {
8668                // A fixed text keeps its style: the layout node takes it with
8669                // the position it is fixed at ([`Self::sync_layout_style`]).
8670                let style = if node.fixed_view {
8671                    node.base_layout.as_deref().cloned()
8672                } else {
8673                    node.base_layout.take().map(|b| *b)
8674                }
8675                .unwrap_or_default();
8676                let cx = LeafContext::Text(Box::new(TextContext::new(Arc::default())));
8677                let layout = self.layout.new_leaf_with_context(style, cx);
8678                self.layout.set_tag(layout, key);
8679                node.layout = Some(layout);
8680                self.mark(key, dirty::TEXT_BUILD);
8681            }
8682        }
8683        // Other elements inside text are not supported; they are ignored. A
8684        // watched span changing its inline context can change the block that
8685        // listens for its hint.
8686        self.dirty_overlay_listeners();
8687    }
8688
8689    /// Creates the native views of `key`'s subtree if needed, wiring up the
8690    /// children in order.
8691    fn ensure_created(&mut self, key: Key) {
8692        let has_attachments = self.attachment_blocks.contains(&key);
8693        let node = &mut self.nodes[key as usize];
8694        if node.created || node.layout.is_none() {
8695            return;
8696        }
8697        node.created = true;
8698        self.pace.made += 1;
8699        // The frame it was given while culled, its view's first.
8700        let culled_frame = std::mem::take(&mut node.culled)
8701            .then_some(node.frame)
8702            .filter(|f| !f.origin.x.0.is_nan());
8703        self.tree_order_changed |= self.track_tree_order;
8704        self.tab_places_stale = true;
8705        if node.kind == Kind::Modal {
8706            self.modals_opened.push((key, node.id));
8707        }
8708        if node.kind == Kind::Text {
8709            self.measure_for_real(key);
8710        }
8711        // A follower made after layout (it waited, culled or paced) took the
8712        // frame layout gave it, and no walk of `emit_frames_in` told
8713        // `laid_follower` of it, so `place_follower` has nothing to place:
8714        // lay it out again, which does.
8715        if culled_frame.is_some()
8716            && self.nodes[key as usize].follow.is_some()
8717            && let Some(layout) = self.nodes[key as usize].layout
8718        {
8719            self.layout.mark_dirty(layout);
8720            self.needs_layout = true;
8721        }
8722        let node = &mut self.nodes[key as usize];
8723        if let Some(scroll) = node.scroll.as_mut() {
8724            scroll.content = None;
8725            // Sticky ranges computed while culled have not reached a
8726            // native view yet. Send them once this view is made.
8727            if !scroll.view_sticky.is_empty() {
8728                self.sticky_views.push(key);
8729            }
8730            // The new native view counts the core's scrolls from zero.
8731            scroll.issued = 0;
8732            scroll.target = None;
8733            scroll.pending.clear();
8734        }
8735        // A list in its parent's viewport is a plain view clipping its
8736        // cells.
8737        let parent_list = node.list.as_ref().is_some_and(|l| l.parent);
8738        let id = node.id;
8739        let kind = node.kind;
8740        let mut flags = self.mount_state(key);
8741        let node = &mut self.nodes[key as usize];
8742        if kind == Kind::Text && has_attachments {
8743            // Its attachments' views go inside the new view.
8744            node.attached.clear();
8745            flags |= dirty::TEXT_BUILD;
8746        }
8747        self.mount.push(MountItem::Create {
8748            id,
8749            kind: if parent_list {
8750                ViewKind::View
8751            } else {
8752                kind.view_kind()
8753            },
8754        });
8755        if let Some(component) = self.nodes[key as usize].component.as_mut() {
8756            // Unnamed, it is named later in this commit (`set_prop`), or
8757            // never: the flush of its props says which.
8758            if let Some(name) = &component.name {
8759                self.mount.push(MountItem::Component {
8760                    id,
8761                    name: name.clone(),
8762                });
8763            }
8764            // A GPU view's renderer, before its props (set later, it is
8765            // sent then).
8766            if let Some(source) = &component.source {
8767                self.mount.push(MountItem::GpuView {
8768                    id,
8769                    source: Some(source.clone()),
8770                });
8771            }
8772        }
8773        if let Some(item) = self.creation_tracking(key) {
8774            self.mount.push(item);
8775        }
8776        if let Some(frame) = culled_frame {
8777            self.nodes[key as usize].frame = frame;
8778            self.mount.push(MountItem::Frame { id, frame });
8779            // And its content size, before any scroll it is made for: the
8780            // platform clamps a scroll to the content it knows.
8781            let content = self.nodes[key as usize]
8782                .scroll
8783                .as_mut()
8784                .and_then(|s| s.culled_content.take());
8785            if let Some(size) = content {
8786                self.set_scroll_content(key, size);
8787            }
8788            if kind == Kind::Canvas
8789                && self.nodes[key as usize]
8790                    .drawing
8791                    .as_ref()
8792                    .is_some_and(|d| d.fit().is_some())
8793            {
8794                self.fitted_pending.push(key);
8795            }
8796            // Beside its frame, an input takes its content box from the
8797            // layout and a scroll view its extent; made after it was laid
8798            // out, nothing lays it out again to send them.
8799            if matches!(kind, Kind::Input | Kind::Scroll) {
8800                self.emit_frames(key);
8801            }
8802        }
8803        let projected = self.nodes[key as usize].projected;
8804        if self.mount_projected && projected != 0 {
8805            self.mount.push(MountItem::ProjectStates {
8806                id,
8807                states: projected,
8808            });
8809        }
8810        self.mark(key, flags);
8811        self.dirty_overlays();
8812        if !kind.is_container() {
8813            return;
8814        }
8815        // Bottom to top: by `zIndex`, then in order.
8816        let mut children = std::mem::take(&mut self.nodes[key as usize].children);
8817        let original = children.clone();
8818        if children
8819            .iter()
8820            .any(|&c| self.nodes[c as usize].stack_rank() != (0, false))
8821        {
8822            children.sort_by_key(|&c| self.nodes[c as usize].stack_rank());
8823        }
8824        // Children far down a scroll view's content wait (`cull.rs`).
8825        let scope = self.cull_scope(key);
8826        for &child in &children {
8827            let c = &self.nodes[child as usize];
8828            if c.layout.is_some() && !c.is_overlay() && !self.hold_back(scope, child) {
8829                self.ensure_created(child);
8830                let child_id = self.nodes[child as usize].id;
8831                self.mount.push(MountItem::Insert {
8832                    parent: id,
8833                    child: child_id,
8834                    before: None,
8835                });
8836            }
8837        }
8838        self.nodes[key as usize].children = original;
8839    }
8840
8841    /// Resets what `key`'s native view was last sent and returns what a new
8842    /// view needs: a new view has the default style and no listeners.
8843    fn mount_state(&mut self, key: Key) -> u32 {
8844        let node = &mut self.nodes[key as usize];
8845        let kind = node.kind;
8846        node.frame = Bounds::UNSET;
8847        node.emitted = None;
8848        if let Some(layout) = node.layout {
8849            self.layout.mark_stale(layout);
8850        }
8851        let node = &mut self.nodes[key as usize];
8852        // A list in its parent's viewport is a plain view clipping its
8853        // cells (`Node::mounted_view_style`), with no scroll view's config.
8854        let parent_list = node.list.as_ref().is_some_and(|l| l.parent);
8855        let mut flags = 0;
8856        if !node.view_style.is_default()
8857            || node.elevation != Points::ZERO
8858            || node.backdrop_material != crate::BackdropMaterial::default()
8859            || node.macos_backdrop.is_some()
8860            || node.windows_backdrop.is_some()
8861            || parent_list
8862            || node.spare
8863            || node.hidden_in_text
8864        {
8865            flags |= dirty::VIEW;
8866        }
8867        if !node.events.is_empty() {
8868            flags |= dirty::EVENTS;
8869        }
8870        if kind == Kind::Text {
8871            flags |= dirty::TEXT_MOUNT;
8872        }
8873        if node.image.as_ref().is_some_and(|i| i.source.is_some()) {
8874            flags |= dirty::IMAGE;
8875        }
8876        if let Some(scroll) = &node.scroll
8877            && !parent_list
8878        {
8879            flags |= dirty::SCROLL;
8880            if scroll.behavior != ScrollBehavior::default() {
8881                flags |= dirty::SCROLL_BEHAVIOR;
8882            }
8883            if scroll.refreshing {
8884                flags |= dirty::REFRESHING;
8885            }
8886        }
8887        if !node.animated.is_empty()
8888            || node.drawing.as_ref().is_some_and(|d| !d.slots.is_empty())
8889            || node.component.as_ref().is_some_and(|c| !c.slots.is_empty())
8890            || node
8891                .shader
8892                .as_ref()
8893                .and_then(|s| s.layer.as_ref())
8894                .is_some_and(|l| !l.nodes.is_empty())
8895        {
8896            flags |= dirty::ANIMATION;
8897        }
8898        if node.drawing.is_some() {
8899            flags |= dirty::CANVAS;
8900        }
8901        if node.shader.as_ref().is_some_and(|s| s.layer.is_some()) {
8902            flags |= dirty::SHADER;
8903        }
8904        if !node.gestures.is_empty() {
8905            flags |= dirty::PAN;
8906        }
8907        // What its classes and styles say of `pointer-events` was worked out
8908        // before the view was there to hear it.
8909        if node.props.is_some()
8910            || node.class_pointer != crate::props::PointerEvents::Auto
8911            || node.spare
8912            || node.hidden_in_text
8913            || node.list.as_ref().is_some_and(|l| l.parent)
8914        {
8915            flags |= dirty::VIEW_PROPS;
8916        }
8917        match kind {
8918            Kind::Screen => flags |= dirty::SCREEN,
8919            Kind::Modal => flags |= dirty::MODAL,
8920            _ => {}
8921        }
8922        if node.control.is_some() {
8923            flags |= dirty::NATIVE;
8924        }
8925        if let Some(list) = node.list.as_mut() {
8926            list.dirty = true;
8927        }
8928        if let Some(input) = node.input.as_mut() {
8929            input.content = None;
8930            flags |= dirty::INPUT;
8931            if !input.value.is_empty() {
8932                flags |= dirty::INPUT_VALUE;
8933            }
8934        }
8935        if let Some(component) = node.component.as_mut() {
8936            // The new component gets every property, and its slots' names.
8937            component.changed = component.props.iter().map(|(k, _)| k.clone()).collect();
8938            component.slots_changed.set(!component.slots.is_empty());
8939            flags |= dirty::COMPONENT;
8940        }
8941        flags
8942    }
8943
8944    #[inline]
8945    /// Sets GPU view `key`'s renderer: sent with its `Create`, or now when
8946    /// it is made already, with every prop again (a new renderer starts
8947    /// from none).
8948    fn set_gpu_source(&mut self, key: Key, id: NodeId, source: Option<crate::gpu::GpuSource>) {
8949        let node = &mut self.nodes[key as usize];
8950        let created = node.created;
8951        let Some(component) = node.component.as_mut() else {
8952            return;
8953        };
8954        if component.source == source {
8955            return;
8956        }
8957        component.source = source.clone();
8958        if !created {
8959            return;
8960        }
8961        self.mount.push(MountItem::GpuView { id, source });
8962        component.changed = component.props.iter().map(|(k, _)| k.clone()).collect();
8963        let mut flags = dirty::COMPONENT;
8964        if !component.slots.is_empty() {
8965            component.slots_changed.set(true);
8966            flags |= dirty::ANIMATION;
8967        }
8968        self.mark(key, flags);
8969    }
8970
8971    fn mark(&mut self, key: Key, flags: u32) {
8972        let node = &mut self.nodes[key as usize];
8973        node.dirty |= flags;
8974        // A culled view given a transform or an animated value may show
8975        // away from its frame now, and so may what a view with one holds
8976        // (`cull.rs`).
8977        if flags & (dirty::VIEW | dirty::ANIMATION) != 0
8978            && (node.culled
8979                || !self.culling.is_empty()
8980                    && (!node.animated.is_empty() || !node.view_style.transform.ops().is_empty()))
8981        {
8982            self.cull_dirty = true;
8983        }
8984        if !node.queued {
8985            node.queued = true;
8986            self.queue.push(key);
8987        }
8988    }
8989
8990    /// Marks the text block containing `key` (or `key` itself) for rebuild.
8991    fn mark_text_block(&mut self, mut key: Key) {
8992        loop {
8993            let node = &self.nodes[key as usize];
8994            if !node.inline {
8995                if node.kind == Kind::Text {
8996                    self.mark(key, dirty::TEXT_BUILD);
8997                }
8998                return;
8999            }
9000            if node.parent == NO_KEY {
9001                // A detached span: rebuilt when it is inserted into a block.
9002                return;
9003            }
9004            key = node.parent;
9005        }
9006    }
9007
9008    fn flush_dirty(&mut self) {
9009        loop {
9010            // The children that moved since, each parent's once.
9011            self.flush_positions();
9012            self.flush_dirty_once();
9013            // Text blocks create the views of new attachments while
9014            // flushing, which queues them; texts inside attachments built
9015            // after their block resize them, which builds the block again.
9016            self.check_attachments();
9017            if self.queue.is_empty() {
9018                break;
9019            }
9020        }
9021    }
9022
9023    fn flush_dirty_once(&mut self) {
9024        let mut queue = std::mem::take(&mut self.queue);
9025        for &key in &queue {
9026            let Some(node) = self.nodes.get_mut(key as usize) else {
9027                continue;
9028            };
9029            let mut flags = std::mem::take(&mut node.dirty);
9030            node.queued = false;
9031            if flags & dirty::TEXT_BUILD != 0 && node.layout.is_some() {
9032                if self.rebuild_text(key) {
9033                    flags |= dirty::TEXT_MOUNT;
9034                }
9035                // Whether it shows characters (`terminal_layout::Role`).
9036                self.sync_grid_role(key);
9037            }
9038            let node = &self.nodes[key as usize];
9039            if !node.created {
9040                continue;
9041            }
9042            let id = node.id;
9043            if flags & dirty::VIEW != 0 {
9044                let style = self.mounted_view_style(key);
9045                self.mount.push(MountItem::ViewStyle { id, style });
9046            }
9047            if flags & dirty::EVENTS != 0 {
9048                self.mount.push(MountItem::Events {
9049                    id,
9050                    events: node.mounted_events(),
9051                });
9052            }
9053            if flags & dirty::IMAGE != 0
9054                && let Some(image) = &node.image
9055            {
9056                // The style's `objectFit`; an image covers its box by
9057                // default.
9058                let resize_mode = node.object_fit.unwrap_or_default();
9059                // Bundled assets with variants: the one for the screen.
9060                let ratio = self.components.environment.pixel_ratio;
9061                self.mount.push(MountItem::Image {
9062                    id,
9063                    source: image.source.as_ref().map(|s| s.resolved(ratio)),
9064                    resize_mode,
9065                    options: crate::mount::ImageOptions {
9066                        placeholder: image
9067                            .options
9068                            .placeholder
9069                            .as_ref()
9070                            .map(|s| s.resolved(ratio)),
9071                        blur_radius: image.options.blur_radius,
9072                        fade_ms: image.options.fade_ms,
9073                        position: node.view_style.object_position,
9074                        current_color: image.svg_current_color.then(|| self.resolved_paint(key).1),
9075                    },
9076                });
9077            }
9078            if let Some(scroll) = &node.scroll
9079                && node.list.as_ref().is_none_or(|l| !l.parent)
9080            {
9081                if flags & dirty::SCROLL != 0 {
9082                    self.mount.push(MountItem::ScrollConfig {
9083                        id,
9084                        horizontal: scroll.horizontal,
9085                        // A built-in bar takes the indicator's place.
9086                        scrollbar_visible: scroll.scrollbar != crate::ScrollbarSetting::Hidden
9087                            && scroll.bar.is_none(),
9088                        replaced: scroll.bar.is_some(),
9089                        scroll_value: scroll.scroll_value,
9090                        pull_value: scroll.pull_value,
9091                        keyboard_dismiss: scroll.keyboard_dismiss,
9092                        mirrored: node.kind == Kind::List && scroll.horizontal && node.rtl,
9093                    });
9094                }
9095                if flags & dirty::SCROLL_BEHAVIOR != 0 {
9096                    self.mount.push(MountItem::ScrollBehavior {
9097                        id,
9098                        behavior: Box::new(scroll.behavior.clone()),
9099                    });
9100                }
9101                if flags & dirty::REFRESHING != 0 {
9102                    self.mount.push(MountItem::Refreshing {
9103                        id,
9104                        refreshing: scroll.refreshing,
9105                    });
9106                }
9107            }
9108            if flags & dirty::ANIMATION != 0 {
9109                let mut bindings = node.animated.clone();
9110                // A sticky view's animated inset is its scroll view's
9111                // (`sticky.rs`); other views' insets do not animate.
9112                if bindings
9113                    .iter()
9114                    .any(|(p, _)| matches!(p, AnimationProp::StickyTop | AnimationProp::StickyLeft))
9115                {
9116                    if node.sticky.is_none() && !self.inset_warned {
9117                        self.inset_warned = true;
9118                        log::warn!(
9119                            target: "js",
9120                            "an animated `top` / `left` only moves a `position: sticky` view's sticking point; it is ignored on view {id}"
9121                        );
9122                    }
9123                    bindings.retain(|(p, _)| {
9124                        !matches!(p, AnimationProp::StickyTop | AnimationProp::StickyLeft)
9125                    });
9126                }
9127                // Its transform's steps come after its parent's perspective.
9128                let steps = self.perspective_steps(key);
9129                if steps > 0 {
9130                    for (prop, _) in &mut bindings {
9131                        if let AnimationProp::Transform(i) = prop {
9132                            *i += steps;
9133                        }
9134                    }
9135                }
9136                if let Some(d) = &node.drawing {
9137                    bindings.extend(
9138                        d.slots
9139                            .iter()
9140                            .enumerate()
9141                            .map(|(i, &n)| (AnimationProp::CanvasArg(i as u16), n)),
9142                    );
9143                }
9144                if let Some(layer) = node.shader.as_ref().and_then(|s| s.layer.as_ref()) {
9145                    bindings.extend(
9146                        layer
9147                            .nodes
9148                            .iter()
9149                            .enumerate()
9150                            .map(|(i, &n)| (AnimationProp::CanvasArg(i as u16), n)),
9151                    );
9152                }
9153                if let Some(component) = &node.component {
9154                    bindings.extend(
9155                        component
9156                            .bound
9157                            .iter()
9158                            .map(|&(s, n)| (AnimationProp::ComponentSlot(s), n)),
9159                    );
9160                }
9161                if let Some(component) = &node.component
9162                    && component.slots_changed.replace(false)
9163                {
9164                    self.mount.push(MountItem::ComponentPropSlots {
9165                        id,
9166                        names: component.slots.clone(),
9167                    });
9168                }
9169                self.mount
9170                    .push(MountItem::AnimationBindings { id, bindings });
9171            }
9172            if flags & dirty::CANVAS != 0
9173                && let Some(drawing) = &node.drawing
9174            {
9175                if drawing.fit().is_some() {
9176                    // Its size comes with this round's layout.
9177                    self.fitted_pending.push(key);
9178                } else {
9179                    let drawing = self.mounted_drawing(key, drawing);
9180                    self.mount.push(MountItem::Canvas { id, drawing });
9181                }
9182            }
9183            if flags & dirty::SHADER != 0
9184                && let Some(shader) = &node.shader
9185            {
9186                self.mount.push(MountItem::Shader {
9187                    id,
9188                    layer: shader.layer.clone(),
9189                });
9190            }
9191            if flags & dirty::PAN != 0 {
9192                let mut values = node.gestures;
9193                if !node.pan_enabled {
9194                    values.pan_x = None;
9195                    values.pan_y = None;
9196                }
9197                self.mount.push(MountItem::Gestures { id, values });
9198            }
9199            if flags & dirty::VIEW_PROPS != 0 {
9200                self.mount.push(MountItem::ViewProps {
9201                    id,
9202                    props: node.mounted_props(),
9203                });
9204            } else if flags & dirty::LABEL != 0 {
9205                let label = node
9206                    .props
9207                    .as_ref()
9208                    .and_then(|p| p.accessibility.label.clone());
9209                self.mount.push(MountItem::AccessibilityLabel { id, label });
9210            }
9211            if flags & dirty::SCREEN != 0
9212                && let Some(config) = self.screen_config(key)
9213            {
9214                self.mount.push(MountItem::ScreenConfig {
9215                    id,
9216                    config: Box::new(config),
9217                });
9218            }
9219            if flags & dirty::COMPONENT != 0
9220                && self.nodes[key as usize].kind == Kind::Native
9221                && let Some(component) = self.nodes[key as usize].component.as_ref()
9222                && component.name.is_none()
9223            {
9224                log::warn!(target: "js", "a <native> element without `component`");
9225            }
9226            if flags & dirty::COMPONENT != 0
9227                && let Some(component) = self.nodes[key as usize].component.as_mut()
9228                && !component.changed.is_empty()
9229            {
9230                let changed = std::mem::take(&mut component.changed);
9231                let props: Vec<_> = changed
9232                    .into_iter()
9233                    // A bound prop's value waits until it is unbound.
9234                    .filter(|name| !component.is_bound(name))
9235                    .map(|name| {
9236                        let value = component
9237                            .props
9238                            .iter()
9239                            .find(|(k, _)| *k == name)
9240                            .map(|(_, v)| v.clone());
9241                        (name, value)
9242                    })
9243                    .collect();
9244                if !props.is_empty() {
9245                    self.mount.push(MountItem::ComponentProps { id, props });
9246                }
9247            }
9248            if flags & dirty::NATIVE != 0 && !self.web_unchecked.is_empty() {
9249                self.settle_web_urls(key);
9250            }
9251            let node = &self.nodes[key as usize];
9252            if flags & dirty::NATIVE != 0
9253                && let Some(control) = &node.control
9254            {
9255                self.mount.push(MountItem::NativeProps {
9256                    id,
9257                    props: (**control).clone(),
9258                });
9259            }
9260            if flags & dirty::MODAL != 0
9261                && let Some(root) = &node.root
9262            {
9263                let mut config = root.modal.clone();
9264                config.window = self.window_of(key);
9265                // A platform presents a dialog when it is inserted, over the
9266                // window its config names: a dialog inserted in this batch
9267                // (one that mounts in a window of the app's own already
9268                // open) gets its config ahead of its insertion.
9269                let item = MountItem::ModalConfig { id, config };
9270                match self
9271                    .mount
9272                    .iter()
9273                    .position(|m| matches!(m, MountItem::Insert { child, .. } if *child == id))
9274                {
9275                    Some(at) => self.mount.insert(at, item),
9276                    None => self.mount.push(item),
9277                }
9278            }
9279            if flags & dirty::NAV_SHADER != 0
9280                && let Some(root) = &node.root
9281            {
9282                let shader = root.nav_shader.clone();
9283                self.mount.push(MountItem::NavShader { id, shader });
9284            }
9285            if let Some(input) = &node.input {
9286                if flags & dirty::INPUT != 0 {
9287                    let mut config = input.config.clone();
9288                    config.accessory = config
9289                        .accessory_id
9290                        .as_deref()
9291                        .and_then(|name| self.accessories.get(name).copied());
9292                    // An explicit prop (Rust), then the style key, then
9293                    // the classes (`placeholder:text-*`, `caret-*`,
9294                    // `selection:bg-*`).
9295                    config.placeholder_color = config
9296                        .placeholder_color
9297                        .or(node.text_style.placeholder_color);
9298                    config.selection_color =
9299                        config.selection_color.or(node.text_style.selection_color);
9300                    let class = node.class_props.as_deref();
9301                    if let Some(c) = class {
9302                        config.placeholder_color = config.placeholder_color.or(c.placeholder_color);
9303                    }
9304                    config.selection_color =
9305                        config.selection_color.or(self.inherited_text_props(key).2);
9306                    config.caret_color = config
9307                        .caret_color
9308                        .or(node.text_style.caret_color)
9309                        .or(class.and_then(|c| c.caret_color));
9310                    config.style = scaled(
9311                        self.inherited_text_style(key).inherit(&node.text_style),
9312                        node.paragraph.font_multiplier(self.font_scale),
9313                    );
9314                    config.align = directed_align(
9315                        node.text_style.text_align.unwrap_or_default(),
9316                        node.rtl && !node.text_style.text_align_physical,
9317                    );
9318                    config.rtl = node.text_style.writing_direction.unwrap_or(node.rtl);
9319                    // A built-in bar takes the indicator's place.
9320                    config.scrollbar_visible =
9321                        input.scrollbar != crate::ScrollbarSetting::Hidden && input.bar.is_none();
9322                    config.report_scroll = input.bar.is_some() || input.watched;
9323                    self.mount.push(MountItem::Input {
9324                        id,
9325                        config: Box::new(config),
9326                    });
9327                }
9328                if flags & dirty::INPUT_VALUE != 0 {
9329                    self.mount.push(MountItem::InputValue {
9330                        id,
9331                        text: input.value.clone(),
9332                        count: input.count,
9333                    });
9334                }
9335            }
9336            if flags & dirty::TEXT_MOUNT != 0 {
9337                self.queue_text(key);
9338            }
9339        }
9340        queue.clear();
9341        // Keep the allocation (unless flushing queued more).
9342        if self.queue.is_empty() {
9343            self.queue = queue;
9344        }
9345    }
9346
9347    /// `onContentSizeChange` of input `key` if the size of its value (at the
9348    /// content box's width when multiline) changed. An empty input reports
9349    /// an empty line, as React Native does, though it is measured (sized)
9350    /// with its placeholder.
9351    fn report_content_size(&mut self, key: Key, width: f32) {
9352        let node = &self.nodes[key as usize];
9353        let (Some(input), Some(layout)) = (node.input.as_ref(), node.layout) else {
9354            return;
9355        };
9356        let max = input.config.multiline.then_some(width);
9357        let (placeholder, empty_line) = (input.placeholder_measured, input.empty_line);
9358        let Some(LeafContext::Text(cx)) = self.layout.get_node_context_mut(layout) else {
9359            return;
9360        };
9361        let size = if !placeholder {
9362            measure_text(&self.text_engine, &mut self.measure_cache, cx, max)
9363        } else if let Some((hash, size)) = empty_line
9364            && hash == cx.layout_hash
9365        {
9366            size
9367        } else {
9368            // Measured once per placeholder and style.
9369            let hash = cx.layout_hash;
9370            let mut empty = TextContext::new(Arc::new(self.input_text(key, "")));
9371            let size = measure_text(&self.text_engine, &mut self.measure_cache, &mut empty, max);
9372            let input = self.nodes[key as usize]
9373                .input
9374                .as_mut()
9375                .expect("input state");
9376            input.empty_line = Some((hash, size));
9377            size
9378        };
9379        let node = &mut self.nodes[key as usize];
9380        let input = node.input.as_mut().expect("input state");
9381        if input.content_size == Some(size) {
9382            return;
9383        }
9384        input.content_size = Some(size);
9385        let id = node.id;
9386        self.events.push(crate::element::JsEvent::Event(
9387            id,
9388            EventKind::ContentSizeChange,
9389            EventPayload::Map(vec![
9390                ("width", PayloadValue::Number(size.width.0 as f64)),
9391                ("height", PayloadValue::Number(size.height.0 as f64)),
9392            ]),
9393        ));
9394    }
9395
9396    fn text_cx(&mut self, layout: LayoutId) -> &mut TextContext<M::Prepared> {
9397        match self.layout.get_node_context_mut(layout) {
9398            Some(LeafContext::Text(cx)) => cx,
9399            _ => unreachable!("text block without text context"),
9400        }
9401    }
9402
9403    /// The text style `key` inherits from the views around it, as CSS
9404    /// does: `color` / `text-white` on a container styles the text in it
9405    /// (React Native views ignore text styles).
9406    /// The style text inherits at the root: React Native's defaults with
9407    /// the app's font.
9408    fn base_text_style(&self) -> ResolvedTextStyle {
9409        ResolvedTextStyle {
9410            font_family: self.default_font,
9411            ..ResolvedTextStyle::default()
9412        }
9413    }
9414
9415    /// A native component's `accentColor` style, passed to it as its
9416    /// `accentColor` prop (`#RRGGBBAA`; removed when unset): the system
9417    /// control shows its state in it, over the color its props give.
9418    fn sync_accent(&mut self, key: Key) {
9419        let node = &mut self.nodes[key as usize];
9420        let accent = node.view_style.accent_color;
9421        let Some(component) = node.component.as_mut() else {
9422            return;
9423        };
9424        let value = accent.map(|Color(c)| crate::JsonValue::from(format!("#{c:08X}")));
9425        let at = component
9426            .props
9427            .iter()
9428            .position(|(k, _)| &**k == ACCENT_PROP);
9429        if at.map(|i| &component.props[i].1) == value.as_ref() {
9430            return;
9431        }
9432        let name: Arc<str> = Arc::from(ACCENT_PROP);
9433        match (at, value) {
9434            (Some(i), Some(v)) => component.props[i].1 = v,
9435            (None, Some(v)) => component.props.push((name.clone(), v)),
9436            (Some(i), None) => {
9437                component.props.swap_remove(i);
9438            }
9439            (None, None) => return,
9440        }
9441        if !component.changed.contains(&name) {
9442            component.changed.push(name);
9443        }
9444        self.mark(key, dirty::COMPONENT);
9445    }
9446
9447    /// Texts and spans around `key` (it is inside an attachment) pass on
9448    /// their color only, as `currentColor` reaches the attachment's view:
9449    /// the attachment takes the color of the text it sits in, while its
9450    /// font and line height stay its own, which size the box its line
9451    /// makes room for.
9452    fn inherited_text_style(&self, key: Key) -> ResolvedTextStyle {
9453        let mut chain: Vec<Key> = Vec::new();
9454        let mut k = self.nodes[key as usize].parent;
9455        while k != NO_KEY {
9456            let node = &self.nodes[k as usize];
9457            let passes = if node.kind == Kind::Text {
9458                node.text_style.color.is_some()
9459            } else {
9460                node.text_style != TextStyle::default()
9461            };
9462            if passes {
9463                chain.push(k);
9464            }
9465            k = node.parent;
9466        }
9467        chain
9468            .iter()
9469            .rev()
9470            .fold(self.base_text_style(), |style, &k| {
9471                let node = &self.nodes[k as usize];
9472                if node.kind == Kind::Text {
9473                    ResolvedTextStyle {
9474                        color: node.text_style.color.unwrap_or(style.color),
9475                        ..style
9476                    }
9477                } else {
9478                    style.inherit(&node.text_style)
9479                }
9480            })
9481    }
9482
9483    /// What the classes of `key`, else of the nearest view around it that
9484    /// says, set for its lines' wrapping, its selection and the
9485    /// selection's highlight: `whitespace-*` and `select-*` inherit, as
9486    /// CSS's `white-space` and `user-select: auto` do, and `selection:bg-*`
9487    /// reaches the texts inside (Tailwind's `& *::selection`), as a view's
9488    /// own color does (Rust's `Element::selection_color`, over its
9489    /// classes'). One walk up.
9490    fn inherited_text_props(&self, key: Key) -> (Option<bool>, Option<bool>, Option<Color>) {
9491        let (no_wrap, selectable, highlight, _) = self.inherited_text_wrap(key);
9492        (no_wrap, selectable, highlight)
9493    }
9494
9495    /// [`Core::inherited_text_props`] and whether its lines wrap
9496    /// `text-pretty`, which inherits with `white-space` (the same classes
9497    /// set both).
9498    fn inherited_text_wrap(&self, key: Key) -> (Option<bool>, Option<bool>, Option<Color>, bool) {
9499        let (mut no_wrap, mut selectable, mut highlight) = (None, None, None);
9500        let mut pretty = None;
9501        let mut k = key;
9502        while k != NO_KEY && (no_wrap.is_none() || selectable.is_none() || highlight.is_none()) {
9503            let node = &self.nodes[k as usize];
9504            if !matches!(node.kind, Kind::Text | Kind::Input) {
9505                highlight = highlight.or(node.paragraph.selection_color);
9506            }
9507            if let Some(c) = node.class_props.as_deref() {
9508                if no_wrap.is_none() && c.no_wrap.is_some() {
9509                    pretty = Some(c.pretty);
9510                }
9511                no_wrap = no_wrap.or(c.no_wrap);
9512                selectable = selectable.or(c.selectable);
9513                highlight = highlight.or(c.selection_color);
9514            }
9515            k = node.parent;
9516        }
9517        (no_wrap, selectable, highlight, pretty.unwrap_or(false))
9518    }
9519
9520    /// The nearest `textAlign` set on a view around `key`.
9521    fn inherited_text_align(&self, key: Key) -> Option<(TextAlign, bool)> {
9522        let mut k = self.nodes[key as usize].parent;
9523        while k != NO_KEY {
9524            let node = &self.nodes[k as usize];
9525            if let Some(a) = node.text_style.text_align {
9526                return Some((a, node.text_style.text_align_physical));
9527            }
9528            k = node.parent;
9529        }
9530        None
9531    }
9532
9533    /// `textIndent` in effect for `key`: the nearest node that sets it,
9534    /// with an `em` value resolved against that node's font size (an
9535    /// inherited length does not grow with a child's font, as in CSS).
9536    fn inherited_text_indent(&self, key: Key) -> Option<Points> {
9537        let mut k = key;
9538        while k != NO_KEY {
9539            let style = &self.nodes[k as usize].text_style;
9540            // A node sets one of the two (`textIndent` clears the other).
9541            if let Some(em) = style.text_indent_em {
9542                return Some(Points(self.font_size_at(k) * em));
9543            }
9544            if let Some(points) = style.text_indent {
9545                return Some(points);
9546            }
9547            k = self.nodes[k as usize].parent;
9548        }
9549        None
9550    }
9551
9552    /// The font size `key` resolves to: its own (`fontSize`, an `em` or a
9553    /// percentage of the inherited one), else the one it inherits.
9554    fn font_size_at(&self, key: Key) -> f32 {
9555        let mut em = 1.0f32;
9556        let mut k = key;
9557        loop {
9558            let style = &self.nodes[k as usize].text_style;
9559            if let Some(scale) = style.font_size_em {
9560                em *= scale;
9561            } else if let Some(size) = style.font_size {
9562                return size.0 * em;
9563            }
9564            let parent = self.nodes[k as usize].parent;
9565            if parent == NO_KEY {
9566                return self.base_text_style().font_size.0 * em;
9567            }
9568            k = parent;
9569        }
9570    }
9571
9572    /// Text blocks and inputs inside `key` inherit its new text style.
9573    fn mark_inheriting_text(&mut self, key: Key) {
9574        self.ch_changed(key);
9575        let mut stack: Vec<Key> = self.nodes[key as usize].children.clone();
9576        while let Some(k) = stack.pop() {
9577            match self.nodes[k as usize].kind {
9578                // The texts inside its attachments inherit too.
9579                Kind::Text => {
9580                    if !self.nodes[k as usize].inline {
9581                        self.mark_text_block(k);
9582                    }
9583                    stack.extend_from_slice(&self.nodes[k as usize].children);
9584                }
9585                Kind::Input => {
9586                    self.measure_input(k);
9587                    self.mark(k, dirty::INPUT);
9588                }
9589                Kind::RawText => {}
9590                _ => stack.extend_from_slice(&self.nodes[k as usize].children),
9591            }
9592        }
9593    }
9594
9595    /// Rebuilds the attributed text of a block. Returns true if it changed.
9596    ///
9597    /// Only layout-relevant changes invalidate measurement and layout; a
9598    /// color change keeps both and just needs a new final layout.
9599    fn rebuild_text(&mut self, key: Key) -> bool {
9600        // Far down a scroll view's content, with no view yet: estimated
9601        // until it comes near (`cull.rs`).
9602        let deferred = !self.nodes[key as usize].created && self.cull_scope(key).is_some();
9603        let node = &self.nodes[key as usize];
9604        // Its own style's and classes' (`numberOfLines`, `textOverflow`).
9605        let class = node.class_props.as_deref();
9606        let explicit_ellipsize = class.and_then(|c| c.ellipsize);
9607        let ellipsize = explicit_ellipsize.unwrap_or_default();
9608        let inherited = self.inherited_text_style(key);
9609        let (no_wrap, selectable, highlight, pretty) = self.inherited_text_wrap(key);
9610        // As in CSS, a nowrap line that clips and sets an ellipsis is cut
9611        // at its box, as `truncate` does; `textOverflow` defaults to `clip`.
9612        let clamps_nowrap = no_wrap == Some(true)
9613            && node.view_style.overflow_hidden
9614            && explicit_ellipsize.is_some_and(|mode| mode != crate::EllipsizeMode::Clip);
9615        let max_lines = match class.and_then(|c| c.number_of_lines) {
9616            Some(lines) if lines > 0 => lines,
9617            _ if clamps_nowrap => 1,
9618            _ => 0,
9619        };
9620        let (align, physical) = node
9621            .text_style
9622            .text_align
9623            .map(|align| (align, node.text_style.text_align_physical))
9624            .or_else(|| self.inherited_text_align(key))
9625            .unwrap_or_default();
9626        let base = inherited.inherit(&node.text_style);
9627        let mut text = AttributedText {
9628            paragraph_strut: Some(base),
9629            align: directed_align(align, node.rtl && !physical),
9630            writing_direction: node.text_style.writing_direction,
9631            rtl: node.rtl,
9632            max_lines,
9633            ellipsize,
9634            // A line clamp already keeps lines from wrapping past it, and
9635            // must ellipsize at the box (`truncate`).
9636            no_wrap: max_lines == 0 && no_wrap.unwrap_or(false),
9637            shadow: node.text_style.shadow(),
9638            selectable,
9639            selection_color: node
9640                .paragraph
9641                .selection_color
9642                .or(node.text_style.selection_color)
9643                .or(highlight),
9644            ..AttributedText::default()
9645        };
9646        let multiplier = node.paragraph.font_multiplier(self.font_scale);
9647        let options = crate::TextOptions::default().indent(
9648            self.inherited_text_indent(key)
9649                .map(|indent| indent * multiplier),
9650        );
9651        let inserted = self.update_attachments(key);
9652        let baselines = self.attachment_baselines(key);
9653        let mut parts = TextAttachments {
9654            alignments: crate::AttachmentAlignments::default(),
9655            spacers: Vec::new(),
9656            baselines: &baselines,
9657            next_baseline: 0,
9658        };
9659        self.collect_text(key, base, &mut text, &mut parts, false);
9660        let TextAttachments {
9661            alignments,
9662            spacers,
9663            ..
9664        } = parts;
9665        self.hide_attachments(key, false);
9666        if multiplier != 1.0 {
9667            if let Some(strut) = &mut text.paragraph_strut {
9668                *strut = scaled(*strut, multiplier);
9669            }
9670            for span in &mut text.spans {
9671                span.style = scaled(span.style, multiplier);
9672            }
9673        }
9674        let layout = self.nodes[key as usize]
9675            .layout
9676            .expect("text block has layout");
9677        let colors_at_draw = self.text_engine.draws_colors_from_text();
9678        let cx = self.text_cx(layout);
9679        cx.deferred = deferred;
9680        cx.spacers = spacers;
9681        let pretty_changed = cx.pretty.is_some() != pretty;
9682        if pretty_changed {
9683            cx.pretty = pretty.then(|| Box::new((f32::NAN, Points::ZERO)));
9684            cx.laid_out = None;
9685        }
9686        if *cx.text == text && cx.alignments == alignments && cx.options == options {
9687            if inserted {
9688                // New attachment views: placed with the next final layout.
9689                cx.laid_out = None;
9690            }
9691            return inserted || pretty_changed;
9692        }
9693        if !cx.text.metadata_eq(&text)
9694            && !inserted
9695            && cx.alignments == alignments
9696            && cx.options == options
9697            && cx.text.rendering_eq(&text)
9698        {
9699            cx.text = Arc::new(text);
9700            cx.metadata_changed = true;
9701            return true;
9702        }
9703        // Only colors or hidden runs changed, and the platform draws them
9704        // from the text: its typesetting, measurements and final layout all
9705        // stand; the new text is mounted with the layout drawn (a fitted
9706        // text has a layout of its own text, made again).
9707        if !inserted
9708            && cx.alignments == alignments
9709            && cx.options == options
9710            && colors_at_draw
9711            && cx
9712                .laid_out
9713                .as_ref()
9714                .is_none_or(|l| Arc::ptr_eq(&l.text, &cx.text))
9715            && cx.text.same_but_colors(&text)
9716        {
9717            let text = Arc::new(text);
9718            if let Some(laid) = &mut cx.laid_out {
9719                laid.text = text.clone();
9720            }
9721            cx.text = text;
9722            cx.metadata_changed = true;
9723            return true;
9724        }
9725        cx.metadata_changed = false;
9726        let same_layout =
9727            cx.text.layout_eq(&text) && cx.alignments == alignments && cx.options == options;
9728        cx.alignments = alignments;
9729        cx.options = options;
9730        cx.text = Arc::new(text);
9731        // Platform typesetting state embeds colors too (unless it draws
9732        // them from the text, above): rebuild it.
9733        cx.prepared = None;
9734        cx.min_content = None;
9735        cx.laid_out = None;
9736        if let Some(p) = &mut cx.pretty {
9737            p.0 = f32::NAN;
9738        }
9739        if !same_layout {
9740            cx.layout_hash = text_layout_hash(&cx.alignments, &cx.text, &cx.options);
9741            cx.cache = None;
9742            cx.baseline = None;
9743            cx.same_lines = None;
9744            cx.no_ahead = false;
9745            // A text that measures as before leaves every layout standing:
9746            // only the text is mounted again. Attachments are placed by its
9747            // final layout, laid out again with the rest.
9748            let attachments =
9749                !cx.alignments.is_empty() || !self.nodes[key as usize].attached.is_empty();
9750            let measure = leaf_measure(&self.text_engine, &mut self.measure_cache);
9751            // A text sized by its style never resizes its box: no need to
9752            // typeset it to know.
9753            if attachments
9754                || !(self.layout.sized_by_style(layout)
9755                    || self.layout.measures_as_before(layout, measure))
9756            {
9757                self.layout.mark_dirty(layout);
9758                self.needs_layout = true;
9759            }
9760        }
9761        true
9762    }
9763
9764    /// The text of `key`'s children into `out`, what it learns of their
9765    /// attachments into `parts`; `in_press`: inside a span taking presses.
9766    fn collect_text(
9767        &self,
9768        key: Key,
9769        style: ResolvedTextStyle,
9770        out: &mut AttributedText,
9771        parts: &mut TextAttachments<'_>,
9772        in_press: bool,
9773    ) {
9774        if let Some(text) = self.folded_text(key) {
9775            out.push(text, style);
9776        }
9777        for &c in &self.nodes[key as usize].children {
9778            let child = &self.nodes[c as usize];
9779            if child.is_overlay() {
9780                continue;
9781            }
9782            match child.kind {
9783                Kind::RawText => out.push(&child.text, style),
9784                Kind::Text => {
9785                    let start = out.len_utf16();
9786                    let mut inner = style.inherit(&child.text_style);
9787                    if let Some(mut b) = span_background(&child.view_style, child.id) {
9788                        (b.top, b.bottom) = span_vertical_padding(child);
9789                        inner.background = Some(b);
9790                    }
9791                    // `visibility: "hidden"` on a span hides its characters,
9792                    // and those of the spans inside it, where they stand.
9793                    if inner.hidden || child.view_style.hidden {
9794                        inner = inner.hide();
9795                    }
9796                    let press = pressable(child.events);
9797                    let hinted = child.overlay_watched & overlay::watch::HINT != 0;
9798                    // Read from the classes, not `tracked`, which may be
9799                    // updated after this merge in the same commit.
9800                    let tracked = child.classes.as_ref().map_or(0, |c| c.tracked_states());
9801                    let hovers = tracked & crate::tailwind::state::HOVERED != 0;
9802                    // Horizontal padding takes room in the line, as a CSS
9803                    // inline box's does: an empty attachment at each end in
9804                    // the span's style, so its background spans it too.
9805                    let (first, last) = span_padding(child, out.rtl);
9806                    let pad = |out: &mut AttributedText, spacers: &mut Vec<u32>, w: f32| {
9807                        if w > 0.0 {
9808                            spacers.push(out.len_utf16());
9809                            out.push_attachment(crate::geometry::size_pt(w, 0.0), inner);
9810                        }
9811                    };
9812                    pad(out, &mut parts.spacers, first);
9813                    self.collect_text(c, inner, out, parts, in_press || press);
9814                    pad(out, &mut parts.spacers, last);
9815                    // A link with a hint (its URL) hears the pointer come
9816                    // over its characters and leave them. A span that takes
9817                    // no presses (a `RichEditor`'s link mark: the editor's
9818                    // touches place the caret and open it) is one only for
9819                    // its hint: no press, no stop of Tab. Inside a span that
9820                    // takes presses it is none, so that span, the innermost
9821                    // link there, keeps the press of those characters.
9822                    // Hidden characters take no presses, as CSS's hidden
9823                    // elements take no pointer events. A span with
9824                    // `hover:` / `active:` styles hears the pointer and
9825                    // its presses the same way: it has no view to report
9826                    // its states, `Self::span_state` takes them from these.
9827                    if !inner.hidden && (press || ((hinted || hovers) && !in_press)) {
9828                        let mut events = child.events;
9829                        if hinted || hovers {
9830                            events.set(EventKind::MouseEnter, true);
9831                            events.set(EventKind::MouseLeave, true);
9832                        }
9833                        if press && tracked & crate::tailwind::state::PRESSED != 0 {
9834                            events.set(EventKind::PressDown, true);
9835                            events.set(EventKind::PressUp, true);
9836                        }
9837                        // Where it goes (`TextView`'s links), for platforms
9838                        // that make it a hyperlink (the web's `<a href>`).
9839                        if let Some(href) = child.props.as_ref().and_then(|p| p.href.clone()) {
9840                            out.link_hrefs
9841                                .push(crate::text::LinkHref::new(out.links.len() as u32, href));
9842                        }
9843                        out.links.push(crate::text::TextLink {
9844                            start,
9845                            end: out.len_utf16(),
9846                            node: child.id,
9847                            events,
9848                            focus_stop: press
9849                                && child.props.as_ref().is_none_or(|p| p.focus_stop(true)),
9850                        });
9851                    }
9852                    if let Some(test_id) = child.props.as_ref().and_then(|p| p.test_id.clone()) {
9853                        out.test_ids.push(crate::text::SpanTestId {
9854                            start,
9855                            end: out.len_utf16(),
9856                            test_id,
9857                        });
9858                    }
9859                }
9860                // Placed in its root view, not in the text.
9861                Kind::Overlay => {}
9862                // An attachment, laid out by `update_attachments`.
9863                _ => {
9864                    if let Some(l) = child.layout {
9865                        let size = self.rounded_layout(l).size;
9866                        // The baselines are in the attachments' order: the
9867                        // next one is this attachment's, or a later one's.
9868                        if let Some(&(_, baseline)) = parts
9869                            .baselines
9870                            .get(parts.next_baseline)
9871                            .filter(|b| b.0 == c)
9872                        {
9873                            parts.next_baseline += 1;
9874                            parts
9875                                .alignments
9876                                .set_baseline(out.len_utf16(), Some(baseline));
9877                        }
9878                        if let Some(copy) = self.attachment_copy_text(c) {
9879                            out.copy_texts.push(crate::text::AttachmentCopyText::new(
9880                                out.len_utf16(),
9881                                copy.clone(),
9882                            ));
9883                        }
9884                        parts.alignments.push(
9885                            out,
9886                            crate::geometry::size_pt(size.width, size.height),
9887                            self.attachment_align(c),
9888                            style,
9889                        );
9890                    }
9891                }
9892            }
9893        }
9894    }
9895
9896    /// Where attachment `key` sits in its line (`verticalAlign`). A
9897    /// placeholder of a render (`renderCustom`, ...) that sets none takes
9898    /// what its content sets: the placeholder and JS's holder around the
9899    /// content are not the app's views, so the app styles only the content
9900    /// (`<View style={{ verticalAlign: "middle" }}>` in `renderCustom`).
9901    fn attachment_align(&self, key: Key) -> crate::style::VerticalAlign {
9902        use crate::style::VerticalAlign;
9903        let node = &self.nodes[key as usize];
9904        if node.vertical_align != VerticalAlign::Baseline
9905            || !self.components.renders.is_place(node.id)
9906        {
9907            return node.vertical_align;
9908        }
9909        self.render_content(key)
9910            .map_or(VerticalAlign::Baseline, |content| {
9911                self.nodes[content as usize].vertical_align
9912            })
9913    }
9914
9915    /// What a copy gives in place of attachment `key` (`copyText`): its
9916    /// own, or for a placeholder of a render (`renderCustom`, ...) that
9917    /// sets none its content's, as [`Self::attachment_align`] reads the
9918    /// content's alignment. An empty one copies as nothing, as unset.
9919    fn attachment_copy_text(&self, key: Key) -> Option<&Arc<str>> {
9920        let node = &self.nodes[key as usize];
9921        let copy = match &node.copy_text {
9922            Some(copy) => Some(copy),
9923            None if self.components.renders.is_place(node.id) => self
9924                .render_content(key)
9925                .and_then(|content| self.nodes[content as usize].copy_text.as_ref()),
9926            None => None,
9927        };
9928        copy.filter(|c| !c.is_empty())
9929    }
9930
9931    /// The content of render placeholder `key`: the placeholder's only
9932    /// child is the holder; the holder's, the content.
9933    fn render_content(&self, key: Key) -> Option<Key> {
9934        let mut key = key;
9935        for _ in 0..2 {
9936            let mut children = self.nodes[key as usize]
9937                .children
9938                .iter()
9939                .filter(|&&c| !self.nodes[c as usize].is_overlay());
9940            match (children.next(), children.next()) {
9941                (Some(&only), None) => key = only,
9942                _ => return None,
9943            }
9944        }
9945        Some(key)
9946    }
9947
9948    /// The attachments of text block `key` that stand on the baseline by
9949    /// a baseline of their own, with how far below their top it is: the
9950    /// first line's of the first text in each, laid out by
9951    /// [`Core::update_attachments`], as CSS stands an `inline-block` or
9952    /// `inline-flex` box on the baseline of its first line box. One with
9953    /// no text in it (an image, a box), or whose engine knows no
9954    /// baselines, stands on its bottom edge, as a replaced box.
9955    fn attachment_baselines(&mut self, key: Key) -> Vec<(Key, Points)> {
9956        let mut keys = Vec::new();
9957        self.attachments_of(key, &mut keys);
9958        keys.retain(|&a| self.attachment_align(a) == crate::style::VerticalAlign::Baseline);
9959        keys.into_iter()
9960            .filter_map(|a| Some((a, self.first_text_baseline(a, true)?)))
9961            .collect()
9962    }
9963
9964    /// How far below `key`'s top the baseline of the first line of text
9965    /// in it is (`root`: `key` is the box asked about, else its place in
9966    /// its parent counts too); none without a text.
9967    fn first_text_baseline(&mut self, key: Key, root: bool) -> Option<Points> {
9968        let node = &self.nodes[key as usize];
9969        if node.is_overlay() {
9970            return None;
9971        }
9972        let layout = node.layout?;
9973        // Only what takes part in the box's flow has its baseline: not a
9974        // `display: none` subtree, which has no box (CSS Display), nor an
9975        // absolutely positioned one, out of the flow.
9976        if !root
9977            && (self.layout.displays_none(layout)
9978                || self.layout.style(layout).position == Position::Absolute)
9979        {
9980            return None;
9981        }
9982        let text = node.kind == Kind::Text;
9983        let l = *self.layout.unrounded_layout(layout);
9984        let top = if root { 0.0 } else { l.location.y };
9985        if text {
9986            let width =
9987                l.size.width - l.padding.left - l.padding.right - l.border.left - l.border.right;
9988            let engine = &self.text_engine;
9989            let Some(LeafContext::Text(cx)) = self.layout.get_node_context_mut(layout) else {
9990                return None;
9991            };
9992            let baseline = text_baseline(engine, cx, width.max(0.0))?;
9993            return Some(Points(top + l.border.top + l.padding.top) + baseline);
9994        }
9995        let children = self.nodes[key as usize].children.clone();
9996        children
9997            .into_iter()
9998            .find_map(|c| self.first_text_baseline(c, false))
9999            .map(|inner| Points(top) + inner)
10000    }
10001
10002    /// The render placeholder in a text that view `key` is the content of
10003    /// (see [`Core::attachment_align`]), if it is one.
10004    fn placed_in_text(&self, key: Key) -> Option<Key> {
10005        let holder = self.nodes[key as usize].parent;
10006        if holder == NO_KEY || !self.is_render_holder(self.nodes[holder as usize].id) {
10007            return None;
10008        }
10009        let place = self.nodes[holder as usize].parent;
10010        (place != NO_KEY && self.nodes[place as usize].inline).then_some(place)
10011    }
10012
10013    /// The attachments of text block `key` (views and images inside it,
10014    /// also inside its spans), in text order.
10015    fn attachments_of(&self, key: Key, out: &mut Vec<Key>) {
10016        for &c in &self.nodes[key as usize].children {
10017            let child = &self.nodes[c as usize];
10018            if child.is_overlay() {
10019                continue;
10020            }
10021            match child.kind {
10022                Kind::RawText | Kind::Overlay => {}
10023                Kind::Text => self.attachments_of(c, out),
10024                _ if child.layout.is_some() => out.push(c),
10025                _ => {}
10026            }
10027        }
10028    }
10029
10030    /// The text block an attachment is in, if it is one.
10031    fn attachment_block(&self, key: Key) -> Option<Key> {
10032        let node = &self.nodes[key as usize];
10033        if !node.inline || node.layout.is_none() || node.kind == Kind::Text {
10034            return None;
10035        }
10036        let mut k = node.parent;
10037        while k != NO_KEY {
10038            let n = &self.nodes[k as usize];
10039            if !n.inline {
10040                return (n.kind == Kind::Text).then_some(k);
10041            }
10042            k = n.parent;
10043        }
10044        None
10045    }
10046
10047    /// Lays out the attachments of text block `key` (each a layout root
10048    /// at its own content size) and keeps their native views inside the
10049    /// block's. Returns true if views were inserted (they need placing).
10050    fn update_attachments(&mut self, key: Key) -> bool {
10051        let mut keys = Vec::new();
10052        self.attachments_of(key, &mut keys);
10053        let block = &self.nodes[key as usize];
10054        if keys.is_empty() && block.attached.is_empty() {
10055            return false;
10056        }
10057        let (block_id, created) = (block.id, block.created);
10058        let old = std::mem::take(&mut self.nodes[key as usize].attached);
10059        let mut inserted = false;
10060        for &a in &keys {
10061            let id = self.nodes[a as usize].id;
10062            let new = !old.contains(&id);
10063            if created && new {
10064                self.ensure_created(a);
10065                self.mount.push(MountItem::Insert {
10066                    parent: block_id,
10067                    child: id,
10068                    before: None,
10069                });
10070                inserted = true;
10071            }
10072            let layout = self.nodes[a as usize].layout.expect("attachment layout");
10073            let dirty = self.layout.dirty(layout);
10074            if dirty {
10075                self.layout_root(
10076                    layout,
10077                    taffy::Size {
10078                        width: AvailableSpace::MaxContent,
10079                        height: AvailableSpace::MaxContent,
10080                    },
10081                );
10082            }
10083            if created && (dirty || new) {
10084                // Its own frame follows the text; its subtree's now.
10085                let children = std::mem::take(&mut self.nodes[a as usize].children);
10086                for &child in &children {
10087                    self.emit_frames(child);
10088                }
10089                self.nodes[a as usize].children = children;
10090            }
10091        }
10092        // Views that left the block and were not moved natively elsewhere.
10093        for id in old {
10094            let Ok(k) = self.key(id) else { continue };
10095            let n = &self.nodes[k as usize];
10096            let moved = n.parent != NO_KEY && !n.inline && self.nodes[n.parent as usize].created;
10097            if n.created && !moved && self.attachment_block(k).is_none() {
10098                self.mount.push(MountItem::Remove { id });
10099            }
10100        }
10101        let ids: Vec<NodeId> = keys.iter().map(|&a| self.nodes[a as usize].id).collect();
10102        let has = !ids.is_empty();
10103        self.nodes[key as usize].attached = if created { ids } else { Vec::new() };
10104        match (has, self.attachment_blocks.contains(&key)) {
10105            (true, false) => self.attachment_blocks.push(key),
10106            (false, true) => self.attachment_blocks.retain(|&k| k != key),
10107            _ => {}
10108        }
10109        inserted
10110    }
10111
10112    /// Text blocks whose attachments' content changed are built again.
10113    fn check_attachments(&mut self) {
10114        let mut i = 0;
10115        while i < self.attachment_blocks.len() {
10116            let key = self.attachment_blocks[i];
10117            i += 1;
10118            let Some(node) = self.nodes.get(key as usize) else {
10119                continue;
10120            };
10121            let dirty = node.attached.iter().any(|&id| {
10122                self.key(id).is_ok_and(|k| {
10123                    self.nodes[k as usize]
10124                        .layout
10125                        .is_some_and(|l| self.layout.dirty(l))
10126                })
10127            });
10128            if dirty {
10129                self.mark(key, dirty::TEXT_BUILD);
10130            }
10131        }
10132    }
10133
10134    /// Where the layout of the node around `layout` is in its layout root
10135    /// (the sum of the unrounded locations above it), as Taffy's rounding
10136    /// carries it down: added from the root down, in Taffy's order, so the
10137    /// sum is the same to the last bit of an `f32` (an edge at x.5 rounds
10138    /// one way or the other on it).
10139    fn positioning_parent(&self, layout: LayoutId) -> Option<LayoutId> {
10140        let mut parent = self.layout.parent(layout)?;
10141        match self.layout.style(layout).position {
10142            Position::Absolute => {
10143                while !self.layout.style(parent).position.is_positioned() {
10144                    let Some(above) = self.layout.parent(parent) else {
10145                        break;
10146                    };
10147                    parent = above;
10148                }
10149            }
10150            Position::Fixed => {
10151                while let Some(above) = self.layout.parent(parent) {
10152                    parent = above;
10153                }
10154            }
10155            _ => {}
10156        }
10157        Some(parent)
10158    }
10159
10160    fn layout_origin(&self, layout: LayoutId) -> taffy::Point<f32> {
10161        let mut above = Vec::new();
10162        let mut at = self.positioning_parent(layout);
10163        while let Some(node) = at {
10164            above.push(node);
10165            at = self.positioning_parent(node);
10166        }
10167        above
10168            .iter()
10169            .rev()
10170            .fold(taffy::Point::ZERO, |origin, &node| {
10171                let l = self.layout.unrounded_layout(node);
10172                taffy::Point {
10173                    x: origin.x + l.location.x,
10174                    y: origin.y + l.location.y,
10175                }
10176            })
10177    }
10178
10179    /// `layout`'s layout, rounded to the surface's device pixels as Taffy's
10180    /// rounding pass rounds to whole points ([`rounded`]); on a grid
10181    /// surface, to its whole Cells.
10182    fn rounded_layout(&self, layout: LayoutId) -> taffy::Layout {
10183        rounded(
10184            self.layout.unrounded_layout(layout),
10185            self.containing_origin(layout),
10186            self.frame_ratio(),
10187        )
10188    }
10189
10190    /// The [`Origin`] of the box `layout` is placed in: the node around
10191    /// it, or its containing block ([`Core::positioning_parent`]).
10192    fn containing_origin(&self, layout: LayoutId) -> Origin {
10193        self.positioning_parent(layout)
10194            .map_or(Origin::default(), |parent| self.box_origin(parent))
10195    }
10196
10197    /// `layout`'s own box as the [`Origin`] of the nodes placed in it.
10198    fn box_origin(&self, layout: LayoutId) -> Origin {
10199        let origin = self.layout_origin(layout);
10200        let l = self.layout.unrounded_layout(layout);
10201        Origin::of(
10202            taffy::Point {
10203                x: origin.x + l.location.x,
10204                y: origin.y + l.location.y,
10205            },
10206            l.size,
10207            self.frame_ratio(),
10208        )
10209    }
10210
10211    /// What frames are rounded to, per axis, in "pixels" per point: the
10212    /// surface's device pixels, or on a grid surface its Cells (one Cell a
10213    /// pixel: [`terminal_layout::Grid::ratio`]).
10214    fn frame_ratio(&self) -> taffy::Size<f32> {
10215        match self.layout.grid() {
10216            Some(grid) => grid.ratio(),
10217            None => {
10218                let ratio = self.pixel_ratio();
10219                taffy::Size {
10220                    width: ratio,
10221                    height: ratio,
10222                }
10223            }
10224        }
10225    }
10226
10227    /// The surface's Cell size is now `cell` (`None`: it is no grid):
10228    /// styles are put on the grid, or taken off it, and everything is laid
10229    /// out again ([`grid`]).
10230    fn cell_changed(&mut self, cell: Option<Size<Points>>, dark: bool) {
10231        let grid = cell
10232            .and_then(terminal_layout::Grid::new)
10233            .map(|g| g.with_page(dark));
10234        let cell = grid.map(|g| Size::new(Points(g.width), Points(g.height)));
10235        if self.measure_cache.set_cell(cell) {
10236            self.fonts_changed();
10237        }
10238        if self.layout.set_grid(grid) {
10239            self.dirty_overlays();
10240            self.needs_layout = true;
10241        }
10242    }
10243
10244    /// The device pixels per point layouts and text measurements are rounded
10245    /// to: the environment's pixel ratio ([`MeasureCache::pixel_ratio`]).
10246    fn pixel_ratio(&self) -> f32 {
10247        self.measure_cache.pixel_ratio()
10248    }
10249
10250    /// The surface's pixel ratio is now `ratio`: frames are rounded to its
10251    /// device pixels and text is measured in them, so a new ratio measures
10252    /// text again and sends every frame that moves.
10253    fn pixel_ratio_changed(&mut self, ratio: f32) {
10254        if !self.measure_cache.set_pixel_ratio(ratio) {
10255            return;
10256        }
10257        self.fonts_changed();
10258        let layouts: Vec<LayoutId> = self
10259            .nodes
10260            .iter()
10261            .filter(|(_, n)| n.created)
10262            .filter_map(|(_, n)| n.layout)
10263            .collect();
10264        for layout in layouts {
10265            self.layout.mark_dirty(layout);
10266        }
10267        self.needs_layout = true;
10268    }
10269
10270    /// Lays out the main tree if it changed. Returns true if it did.
10271    fn layout_main(&mut self) -> bool {
10272        let root = self.nodes[self.root as usize].layout.expect("root layout");
10273        let available = taffy::Size {
10274            width: AvailableSpace::Definite(self.viewport.width.0),
10275            height: AvailableSpace::Definite(self.viewport.height.0),
10276        };
10277        // A clean root has nothing new to lay out, nor frames to emit.
10278        let main = self.layout.dirty(root);
10279        if main {
10280            // A main window that fits its content: laid out at its
10281            // content's size on those sides ([`Core::fit_window`]).
10282            let (fitting, fitted) = self
10283                .windows
10284                .get(&crate::ROOT_ID)
10285                .map_or(((false, false), false), |r| (r.fits(), r.fitted.is_some()));
10286            let mut available = available;
10287            if fitting != (false, false) || fitted {
10288                let mut style = root_style(self.viewport);
10289                if fitting.0 {
10290                    available.width = AvailableSpace::MaxContent;
10291                    style.size.width = taffy::Dimension::auto();
10292                }
10293                if fitting.1 {
10294                    available.height = AvailableSpace::MaxContent;
10295                    style.size.height = taffy::Dimension::auto();
10296                }
10297                self.layout.set_style(root, style);
10298            }
10299            self.layout_root(root, available);
10300            self.fit_window(self.root, root);
10301        }
10302        main
10303    }
10304
10305    /// Lays out screens, modals and header items whose size or content
10306    /// changed, outer ones first (a stack may live in a modal), and emits
10307    /// their frames.
10308    fn layout_roots(&mut self) {
10309        if self.roots.is_empty() {
10310            return;
10311        }
10312        let mut order: Vec<(u32, Key)> = self
10313            .roots
10314            .iter()
10315            .filter(|&&k| {
10316                let n = &self.nodes[k as usize];
10317                n.created
10318                    && n.parent != NO_KEY
10319                    && (!n.is_overlay() || self.overlay(k).is_some_and(|s| s.host.is_some()))
10320            })
10321            .map(|&k| (self.root_depth(k), k))
10322            .collect();
10323        order.sort_unstable();
10324        for (_, key) in order {
10325            self.layout_detached(key);
10326        }
10327    }
10328
10329    /// Input accessory `key` was attached to the tree (or detached): the
10330    /// inputs that name it are configured again.
10331    fn accessory_attached(&mut self, key: Key, attached: bool) {
10332        let node = &self.nodes[key as usize];
10333        let Some(name) = node.root.as_ref().and_then(|r| r.native_id.clone()) else {
10334            return;
10335        };
10336        let id = node.id;
10337        if attached {
10338            self.accessories.insert(name.clone(), id);
10339        } else if self.accessories.get(&name) == Some(&id) {
10340            self.accessories.remove(&name);
10341        } else {
10342            return;
10343        }
10344        let inputs: Vec<Key> = self
10345            .nodes
10346            .iter()
10347            .filter(|(_, n)| {
10348                n.input
10349                    .as_ref()
10350                    .is_some_and(|i| i.config.accessory_id.as_deref() == Some(&*name))
10351            })
10352            .map(|(k, _)| k as Key)
10353            .collect();
10354        for k in inputs {
10355            self.mark(k, dirty::INPUT);
10356        }
10357    }
10358
10359    /// Number of screens / modals / header items above `key`.
10360    fn root_depth(&self, mut key: Key) -> u32 {
10361        let mut depth = 0;
10362        key = self.nodes[key as usize].parent;
10363        while key != NO_KEY {
10364            let n = &self.nodes[key as usize];
10365            if n.is_layout_root() {
10366                depth += 1;
10367            }
10368            key = n.parent;
10369        }
10370        depth
10371    }
10372
10373    /// How far the system UI at the top (status bar) reaches into `key`:
10374    /// its root's top inset minus its offset in that root.
10375    fn top_overlap(&self, key: Key) -> f32 {
10376        let mut y = 0.0;
10377        let mut k = key;
10378        loop {
10379            let n = &self.nodes[k as usize];
10380            if k == self.root {
10381                return (self.safe_area.top.0 - y).max(0.0);
10382            }
10383            if n.is_layout_root() {
10384                let inset = match n.kind {
10385                    Kind::Modal => n.root.as_ref().map_or(0.0, |r| r.insets.top.0),
10386                    _ => 0.0,
10387                };
10388                return (inset - y).max(0.0);
10389            }
10390            if !n.frame.origin.y.0.is_nan() {
10391                y += n.frame.origin.y.0;
10392            }
10393            if n.parent == NO_KEY {
10394                return 0.0;
10395            }
10396            k = n.parent;
10397        }
10398    }
10399
10400    /// The platform draws a header of its own above screens (iOS,
10401    /// Android); without one ([`crate::NO_NATIVE_HEADER`]) a screen's
10402    /// `header` slot is placed at its top.
10403    fn native_header(&self) -> bool {
10404        self.header_heights != crate::NO_NATIVE_HEADER
10405    }
10406
10407    /// The size of screen `key`: its stack's (`None` outside a stack).
10408    fn screen_size(&self, key: Key) -> Option<Size<Points>> {
10409        let parent = self.nodes[key as usize].parent;
10410        let p = self.nodes.get(parent as usize)?;
10411        let stack_layout = p.layout.filter(|_| p.kind == Kind::Stack)?;
10412        let s = self.rounded_layout(stack_layout).size;
10413        Some(size_pt(s.width, s.height))
10414    }
10415
10416    /// The `header` slot item of screen `key`, once created.
10417    fn header_slot(&self, key: Key) -> Option<Key> {
10418        self.nodes[key as usize]
10419            .children
10420            .iter()
10421            .copied()
10422            .find(|&c| {
10423                let n = &self.nodes[c as usize];
10424                n.kind == Kind::HeaderItem
10425                    && n.created
10426                    && n.root
10427                        .as_ref()
10428                        .is_some_and(|r| r.slot == HeaderSlot::Header)
10429            })
10430    }
10431
10432    /// Without a native header: the height of screen `key`'s `header` slot,
10433    /// laid out first (as wide as the screen), 0 without one.
10434    fn drawn_header(&mut self, key: Key) -> f32 {
10435        let Some(item) = self.header_slot(key) else {
10436            return 0.0;
10437        };
10438        self.layout_detached(item);
10439        self.nodes[item as usize]
10440            .layout
10441            .map_or(0.0, |l| self.rounded_layout(l).size.height)
10442    }
10443
10444    fn layout_detached(&mut self, key: Key) {
10445        if self.nodes[key as usize].is_overlay() {
10446            self.layout_overlay(key);
10447            return;
10448        }
10449        let native_header = self.native_header();
10450        let drawn_header = if !native_header && self.nodes[key as usize].kind == Kind::Screen {
10451            self.drawn_header(key)
10452        } else {
10453            0.0
10454        };
10455        let title_room = {
10456            let n = &self.nodes[key as usize];
10457            let title = native_header
10458                && n.kind == Kind::HeaderItem
10459                && n.root.as_ref().is_some_and(|r| r.slot == HeaderSlot::Title);
10460            let parent = n.parent;
10461            if title && parent != NO_KEY {
10462                self.title_room(parent).unwrap_or(0.0)
10463            } else {
10464                0.0
10465            }
10466        };
10467        let node = &self.nodes[key as usize];
10468        let (Some(layout), kind, parent) = (node.layout, node.kind, node.parent) else {
10469            return;
10470        };
10471        let root = node.root.as_ref().expect("root state");
10472        let (size, header, available) = match kind {
10473            Kind::Screen => {
10474                let Some(size) = self.screen_size(key) else {
10475                    return;
10476                };
10477                let c = &root.screen;
10478                let measured = root
10479                    .header
10480                    .filter(|_| !c.large_title && !c.header_transparent);
10481                let header = if !native_header {
10482                    drawn_header
10483                } else if !c.header_visible {
10484                    0.0
10485                } else if let Some(measured) = measured {
10486                    measured
10487                } else {
10488                    let bar = if c.large_title {
10489                        self.header_heights.1
10490                    } else {
10491                        self.header_heights.0
10492                    };
10493                    bar.0 + self.top_overlap(parent)
10494                };
10495                (size, header, definite(size))
10496            }
10497            // A screen's `header` without a native header: as wide as the
10498            // screen, as tall as its content.
10499            Kind::HeaderItem if !native_header && root.slot == HeaderSlot::Header => {
10500                let Some(screen) = self.screen_size(parent) else {
10501                    return;
10502                };
10503                (
10504                    size_pt(screen.width.0, 0.0),
10505                    0.0,
10506                    taffy::Size {
10507                        width: AvailableSpace::Definite(screen.width.0),
10508                        height: AvailableSpace::MaxContent,
10509                    },
10510                )
10511            }
10512            // A native header's title view: at its content's width, at most
10513            // the room the bar leaves between its items (as the toolbar's own
10514            // title), so a long title shrinks instead of running under them.
10515            Kind::HeaderItem if native_header && root.slot == HeaderSlot::Title => (
10516                Size::default(),
10517                title_room,
10518                taffy::Size {
10519                    width: AvailableSpace::MaxContent,
10520                    height: AvailableSpace::MaxContent,
10521                },
10522            ),
10523            Kind::Modal => {
10524                // A window whose size is not known yet: its content's.
10525                let known = self.root_view_size(key);
10526                let size = known.unwrap_or_default();
10527                let mut available = match known {
10528                    Some(size) => definite(size),
10529                    None => taffy::Size {
10530                        width: AvailableSpace::MaxContent,
10531                        height: AvailableSpace::MaxContent,
10532                    },
10533                };
10534                // A window that fits its content: laid out at its content's
10535                // size on those sides ([`Core::fit_window`]).
10536                let (width, height) = self
10537                    .windows
10538                    .get(&node.id)
10539                    .map_or((false, false), |r| r.fits());
10540                if width {
10541                    available.width = AvailableSpace::MaxContent;
10542                }
10543                if height {
10544                    available.height = AvailableSpace::MaxContent;
10545                }
10546                (size, 0.0, available)
10547            }
10548            // As wide as the window, as tall as its content.
10549            Kind::InputAccessory => (
10550                size_pt(self.viewport.width.0, 0.0),
10551                0.0,
10552                taffy::Size {
10553                    width: AvailableSpace::Definite(self.viewport.width.0),
10554                    height: AvailableSpace::MaxContent,
10555                },
10556            ),
10557            _ => (
10558                Size::default(),
10559                0.0,
10560                taffy::Size {
10561                    width: AvailableSpace::MaxContent,
10562                    height: AvailableSpace::MaxContent,
10563                },
10564            ),
10565        };
10566        let changed = root.laid_out != Some((size, header));
10567        if !changed && !self.layout.dirty(layout) {
10568            return;
10569        }
10570        if kind == Kind::HeaderItem && native_header && root.slot == HeaderSlot::Title {
10571            let mut style = self.layout.style(layout).clone();
10572            style.max_size.width = if header > 0.0 {
10573                taffy::LengthPercentageAuto::length(header)
10574            } else {
10575                taffy::LengthPercentageAuto::auto()
10576            };
10577            self.layout.set_style(layout, style);
10578        } else if kind == Kind::InputAccessory
10579            || (kind == Kind::HeaderItem && size.width > Points::ZERO)
10580        {
10581            let mut style = self.layout.style(layout).clone();
10582            style.size.width = taffy::Dimension::length(size.width.0);
10583            self.layout.set_style(layout, style);
10584        } else if kind != Kind::HeaderItem {
10585            let config_padding = match kind {
10586                // Large titles and transparent headers lay the content out
10587                // under the native header (scroll views inset themselves
10588                // natively).
10589                Kind::Screen
10590                    if native_header
10591                        && (root.screen.header_transparent || root.screen.large_title) =>
10592                {
10593                    0.0
10594                }
10595                _ => header,
10596            };
10597            let mut style = self.nodes[key as usize]
10598                .base_layout
10599                .as_deref()
10600                .cloned()
10601                .unwrap_or_default();
10602            style.size = taffy::Size {
10603                width: taffy::Dimension::length(size.width.0),
10604                height: taffy::Dimension::length(size.height.0),
10605            };
10606            if kind == Kind::Modal {
10607                let id = self.nodes[key as usize].id;
10608                let (mut width, mut height) =
10609                    self.windows.get(&id).map_or((false, false), |r| r.fits());
10610                if self.root_view_size(key).is_none() {
10611                    (width, height) = (true, true);
10612                }
10613                if width {
10614                    style.size.width = taffy::Dimension::auto();
10615                }
10616                if height {
10617                    style.size.height = taffy::Dimension::auto();
10618                }
10619            }
10620            if config_padding > 0.0 {
10621                let base = match style.padding.top.into_raw() {
10622                    raw if raw.tag() == taffy::CompactLength::LENGTH_TAG => raw.value(),
10623                    _ => 0.0,
10624                };
10625                style.padding.top = taffy::LengthPercentage::length(base + config_padding);
10626            }
10627            self.layout.set_style(layout, style);
10628        }
10629        let header_changed = root.laid_out.is_none_or(|(_, h)| h != header);
10630        self.nodes[key as usize]
10631            .root
10632            .as_mut()
10633            .expect("root state")
10634            .laid_out = Some((size, header));
10635        self.layout_root(layout, available);
10636        if kind == Kind::Modal {
10637            self.fit_window(key, layout);
10638        }
10639        self.emit_frames(key);
10640        let screen = match kind {
10641            Kind::Screen if header_changed => Some(key),
10642            Kind::HeaderItem if self.header_item_emptied(key) => Some(parent),
10643            _ => None,
10644        };
10645        if let Some(screen) = screen {
10646            let id = self.nodes[screen as usize].id;
10647            if let Some(config) = self.screen_config(screen) {
10648                self.mount.push(MountItem::ScreenConfig {
10649                    id,
10650                    config: Box::new(config),
10651                });
10652            }
10653        }
10654    }
10655
10656    /// Header item `key` was laid out: records whether a leading,
10657    /// trailing or title one has no width (its content is gone, or shows nothing)
10658    /// and answers whether that changed, so its screen's options go out
10659    /// again with the bar's item left out or put back.
10660    fn header_item_emptied(&mut self, key: Key) -> bool {
10661        let width = self.nodes[key as usize]
10662            .layout
10663            .map_or(0.0, |l| self.rounded_layout(l).size.width);
10664        let root = self.nodes[key as usize].root.as_mut().expect("root state");
10665        if root.slot == HeaderSlot::Header {
10666            return false;
10667        }
10668        let empty = width <= 0.0;
10669        std::mem::replace(&mut root.empty, empty) != empty
10670    }
10671
10672    /// The width a native header leaves screen `key`'s title view: the
10673    /// screen's, less the bar's insets, the back button and the leading and
10674    /// trailing items (laid out first). `None` outside a stack.
10675    fn title_room(&mut self, key: Key) -> Option<f32> {
10676        /// The bar's inset at either end, and the gap after an item.
10677        const INSET: f32 = 16.0;
10678        /// The back button's room, its inset included.
10679        const BACK: f32 = 56.0;
10680        /// The room of a native bar button.
10681        const BUTTON: f32 = 48.0;
10682        let width = self.screen_size(key)?.width.0;
10683        let items: Vec<(Key, HeaderSlot)> = self.nodes[key as usize]
10684            .children
10685            .iter()
10686            .filter_map(|&c| {
10687                let n = &self.nodes[c as usize];
10688                let slot = n.root.as_ref()?.slot;
10689                (n.kind == Kind::HeaderItem
10690                    && n.created
10691                    && matches!(slot, HeaderSlot::Left | HeaderSlot::Right))
10692                .then_some((c, slot))
10693            })
10694            .collect();
10695        let mut room = width - 2.0 * INSET;
10696        let (mut left, mut right) = (false, false);
10697        for (item, slot) in items {
10698            self.layout_detached(item);
10699            let w = self.nodes[item as usize]
10700                .layout
10701                .map_or(0.0, |l| self.rounded_layout(l).size.width);
10702            room -= w + INSET;
10703            match slot {
10704                HeaderSlot::Left => left = true,
10705                _ => right = true,
10706            }
10707        }
10708        let screen = &self.nodes[key as usize];
10709        let config = &screen.root.as_ref()?.screen;
10710        if !right && !config.right_items.is_empty() {
10711            room -= config.right_items.len() as f32 * BUTTON;
10712        }
10713        if !left && !config.left_items.is_empty() {
10714            room -= config.left_items.len() as f32 * BUTTON;
10715        }
10716        // Not the stack's first screen: a back button leads the bar.
10717        let first = self.nodes[screen.parent as usize].children.first() == Some(&key);
10718        if !left && config.back_visible && !first {
10719            room -= BACK;
10720        }
10721        Some(room.max(1.0))
10722    }
10723
10724    /// The options of screen `key`, with its header items.
10725    fn screen_config(&self, key: Key) -> Option<ScreenConfig> {
10726        let node = &self.nodes[key as usize];
10727        let root = node.root.as_ref().filter(|_| node.kind == Kind::Screen)?;
10728        let mut config = root.screen.clone();
10729        config.header_height = Points(root.laid_out.map_or(0.0, |(_, h)| h));
10730        for &c in &node.children {
10731            let child = &self.nodes[c as usize];
10732            if child.kind != Kind::HeaderItem || !child.created {
10733                continue;
10734            }
10735            let slot = child.root.as_ref().map_or(HeaderSlot::Left, |r| r.slot);
10736            // A side's item with nothing to show leaves the bar without a
10737            // button there, unless the platform's own button stands in for
10738            // it (and presses it).
10739            let empty = child.root.as_ref().is_some_and(|r| r.empty);
10740            let system = match slot {
10741                HeaderSlot::Left => {
10742                    config.left_system_item.is_some() || config.left_symbol.is_some()
10743                }
10744                HeaderSlot::Right => {
10745                    config.right_system_item.is_some() || config.right_symbol.is_some()
10746                }
10747                // An empty title view gives the platform's title text back.
10748                HeaderSlot::Title => false,
10749                HeaderSlot::Header => true,
10750            };
10751            if empty && !system {
10752                continue;
10753            }
10754            let target = match slot {
10755                HeaderSlot::Left => &mut config.left,
10756                HeaderSlot::Right => &mut config.right,
10757                HeaderSlot::Title => &mut config.title_view,
10758                HeaderSlot::Header => &mut config.header_view,
10759            };
10760            *target = Some(child.id);
10761        }
10762        if let Some(style) = self.part_resolved(key, classes::Part::Header) {
10763            let background = style.view.background_color;
10764            config.background_color = (background.0 & 0xff != 0).then_some(background);
10765            config.title_color = style.text.color;
10766            config.tint_color = style.view.tint_color;
10767        }
10768        Some(config)
10769    }
10770
10771    /// Lays out the list cells that changed: items at their column's
10772    /// width, the header, footer and empty placeholder at the content's.
10773    fn layout_cells(&mut self) {
10774        for i in 0..self.lists.len() {
10775            let key = self.lists[i];
10776            let list = &self.nodes[key as usize];
10777            let Some(list_layout) = list.layout else {
10778                continue;
10779            };
10780            let state = list.list.as_ref().expect("list");
10781            let horizontal = state.horizontal;
10782            let l = self.rounded_layout(list_layout);
10783            let size = l.size;
10784            let cross = if !state.parent {
10785                if horizontal { size.height } else { size.width }
10786            } else if horizontal {
10787                // In its parent's viewport: the cells fill its content box.
10788                (size.height - l.border.top - l.border.bottom - l.padding.top - l.padding.bottom)
10789                    .max(0.0)
10790            } else {
10791                (size.width - l.border.left - l.border.right - l.padding.left - l.padding.right)
10792                    .max(0.0)
10793            };
10794            // In a terminal its scroll bar takes a column (a row) of its own
10795            // once the content overflows, as a scroll view's does.
10796            let cross = if state.parent {
10797                cross
10798            } else {
10799                let main = if horizontal {
10800                    size.width - l.border.left - l.border.right - l.padding.left - l.padding.right
10801                } else {
10802                    size.height - l.border.top - l.border.bottom - l.padding.top - l.padding.bottom
10803                };
10804                let room = self.layout.list_bar_room(list_layout, horizontal);
10805                if room > 0.0 && state.content_len() > main + 0.5 {
10806                    (cross - room).max(0.0)
10807                } else {
10808                    cross
10809                }
10810            };
10811            let cell = self
10812                .layout
10813                .grid()
10814                .map(|g| if horizontal { g.height } else { g.width });
10815            let item_cross = state.column(cross, 0, cell).1;
10816            let extra_cross = state.full_width(cross).1;
10817            let stretch = state
10818                .content
10819                .align_items
10820                .is_none_or(|a| a == taffy::AlignItems::STRETCH);
10821            let available = |c: f32| {
10822                let cross = if stretch {
10823                    AvailableSpace::Definite(c)
10824                } else {
10825                    AvailableSpace::MaxContent
10826                };
10827                if horizontal {
10828                    taffy::Size {
10829                        width: AvailableSpace::MaxContent,
10830                        height: cross,
10831                    }
10832                } else {
10833                    taffy::Size {
10834                        width: cross,
10835                        height: AvailableSpace::MaxContent,
10836                    }
10837                }
10838            };
10839            // Laying out even a clean root costs a tree walk (taffy rounds the
10840            // whole subtree), so only dirty cells are laid out again — all
10841            // of them when the list's cross size or columns changed.
10842            let list_state = self.nodes[key as usize].list.as_mut().expect("list");
10843            let resized = list_state.cells_cross != cross;
10844            list_state.cells_cross = cross;
10845            let cells = std::mem::take(&mut self.nodes[key as usize].children);
10846            for &cell in &cells {
10847                let node = &self.nodes[cell as usize];
10848                // Its built-in bar: laid out by `layout_scrollbars`.
10849                let (Some(cell_layout), false) = (node.layout, node.decoration) else {
10850                    continue;
10851                };
10852                let c = match node.slot {
10853                    Some(CellSlot::Item(_)) | None => item_cross,
10854                    Some(_) => extra_cross,
10855                };
10856                self.layout.set_host(cell_layout, list_layout);
10857                if resized || self.layout.dirty(cell_layout) {
10858                    self.layout_root(cell_layout, available(c));
10859                    self.nodes[cell as usize].relaid = true;
10860                }
10861            }
10862            self.nodes[key as usize].children = cells;
10863        }
10864    }
10865
10866    /// Lays out the tree under `root` within `available`.
10867    fn layout_root(&mut self, root: LayoutId, available: taffy::Size<AvailableSpace>) {
10868        let measure = leaf_measure(&self.text_engine, &mut self.measure_cache);
10869        self.layout
10870            .compute_layout_with_measure(root, available, measure);
10871    }
10872
10873    /// Lays out the relayout boundaries a change inside made dirty
10874    /// (`LayoutTree::relayout_boundaries`), returning those laid out on
10875    /// their own: their subtrees' frames are new.
10876    fn relayout_boundaries(&mut self) -> Vec<Key> {
10877        let measure = leaf_measure(&self.text_engine, &mut self.measure_cache);
10878        self.layout.relayout_boundaries(measure)
10879    }
10880
10881    /// Whether `key` is out of the layout: `display: none` on it or on a
10882    /// view it is laid out in (Taffy gives all of them no size).
10883    fn displays_none(&self, key: Key) -> bool {
10884        let mut k = key;
10885        while k != NO_KEY {
10886            let n = &self.nodes[k as usize];
10887            if let Some(layout) = n.layout
10888                && self.layout.displays_none(layout)
10889            {
10890                return true;
10891            }
10892            if n.is_layout_root() {
10893                return false;
10894            }
10895            k = n.parent;
10896        }
10897        false
10898    }
10899
10900    #[inline]
10901    fn queue_text(&mut self, key: Key) {
10902        let node = &mut self.nodes[key as usize];
10903        if !node.text_queued {
10904            node.text_queued = true;
10905            self.pending_text.push(key);
10906        }
10907    }
10908
10909    /// Makes the final layout of every queued text block whose content or
10910    /// box changed, and emits it.
10911    fn flush_text(&mut self) {
10912        let mut pending = std::mem::take(&mut self.pending_text);
10913        // Attachment views to place: (block, its final layout, content box).
10914        let mut placements: Vec<(Key, TextLayout, Bounds<Points>)> = Vec::new();
10915        for &key in &pending {
10916            let Some(node) = self.nodes.get_mut(key as usize) else {
10917                continue;
10918            };
10919            node.text_queued = false;
10920            let align_vertical = node.text_style.align_vertical.unwrap_or_default();
10921            let report_lines = node.events.contains(EventKind::TextLayout);
10922            // Shrinking stops at a tenth: smaller is unreadable anyway.
10923            let fit = node
10924                .paragraph
10925                .fit
10926                .then_some(node.paragraph.min_font_scale.max(0.1));
10927            let (id, created, Some(layout)) = (node.id, node.created, node.layout) else {
10928                continue;
10929            };
10930            if !created {
10931                continue;
10932            }
10933            if let Some(commit) = self.measure_cache.resizing
10934                && let Some(LeafContext::Text(cx)) = self.layout.get_node_context_mut(layout)
10935                && cx.near_screen != commit
10936                && cx
10937                    .laid_out
10938                    .as_ref()
10939                    .is_some_and(|l| Arc::ptr_eq(&l.text, &cx.text))
10940            {
10941                cx.held = true;
10942                continue;
10943            }
10944            // Whatever Taffy keeps for it (`emit_frames_in`).
10945            let hidden = self.displays_none(key);
10946            let mut content = if hidden {
10947                Bounds::default()
10948            } else {
10949                content_box(&self.rounded_layout(layout))
10950            };
10951            // The width Taffy measured its lines in, before its box was
10952            // rounded to device pixels (none on a grid, whose Cells hold
10953            // whole characters).
10954            let measured_width = (!hidden && self.layout.grid().is_none())
10955                .then(|| content_box(self.layout.unrounded_layout(layout)).size.width);
10956            let ratio = self.frame_ratio().width;
10957            let engine = &self.text_engine;
10958            let cache = &mut self.measure_cache;
10959            let Some(LeafContext::Text(cx)) = self.layout.get_node_context_mut(layout) else {
10960                continue;
10961            };
10962            let no_wrap = cx.text.no_wrap;
10963            let typeset = |rounded: Points| match measured_width {
10964                Some(measured) if !no_wrap => typeset_width(rounded, measured, ratio),
10965                _ => rounded,
10966            };
10967            if hidden {
10968                // Out of the layout (`display: none`). Its glyphs typeset
10969                // in its zero box would still show where a platform does
10970                // not clip text to its box (a browser), so it gets an
10971                // empty layout; the text itself stays what it is.
10972                if let Some((text, layout)) = cx.remount_metadata(content) {
10973                    self.mount.push(MountItem::Text {
10974                        id,
10975                        text,
10976                        layout,
10977                        content,
10978                    });
10979                    continue;
10980                }
10981                if matches!(&cx.laid_out, Some(l) if l.content == content) {
10982                    continue;
10983                }
10984                let layout =
10985                    engine.layout(&engine.prepare(&AttributedText::default()), content.size);
10986                cx.laid_out = Some(LaidText {
10987                    content,
10988                    layout: layout.clone(),
10989                    text: cx.text.clone(),
10990                });
10991                cx.metadata_changed = false;
10992                self.mount.push(MountItem::Text {
10993                    id,
10994                    text: cx.text.clone(),
10995                    layout,
10996                    content,
10997                });
10998                continue;
10999            }
11000            if cx.text.no_wrap {
11001                // One line at its natural width, past the box if need be.
11002                content.size.width = content
11003                    .size
11004                    .width
11005                    .max(measure_text(engine, cache, cx, None).width);
11006            }
11007            if align_vertical > Percentage(0.0) {
11008                // Text shorter than its box: moved down within it.
11009                let height =
11010                    measure_text(engine, cache, cx, Some(typeset(content.size.width).0)).height;
11011                if height < content.size.height {
11012                    content.origin.y += align_vertical.of(content.size.height - height);
11013                    content.size.height = height;
11014                }
11015            }
11016            if cx.pretty.is_some() && fit.is_none() {
11017                // Lines broken narrower than the box, where they go in it
11018                // as the text is aligned.
11019                let width = pretty_width(engine, cx, content.size.width);
11020                let spare = content.size.width - width;
11021                if spare > Points::ZERO {
11022                    content.origin.x += match cx.text.align {
11023                        TextAlign::Center => spare * 0.5,
11024                        TextAlign::Right => spare,
11025                        TextAlign::Auto if cx.text.rtl => spare,
11026                        _ => Points::ZERO,
11027                    };
11028                    content.size.width = width;
11029                }
11030            }
11031            if let Some((text, layout)) = cx.remount_metadata(content) {
11032                self.mount.push(MountItem::Text {
11033                    id,
11034                    text,
11035                    layout,
11036                    content,
11037                });
11038                continue;
11039            }
11040            let size = content.size;
11041            if let Some(min) = fit {
11042                // Shrunk to fit: its own text, laid out on its own.
11043                if matches!(&cx.laid_out, Some(l) if l.content == content) {
11044                    continue;
11045                }
11046                let text = Arc::new(fitted(
11047                    engine,
11048                    &cx.text,
11049                    &cx.alignments,
11050                    &cx.options,
11051                    size,
11052                    min,
11053                ));
11054                let prepared = engine.prepare_with(&text, &cx.alignments, &cx.options);
11055                let text_layout = engine.layout(&prepared, size);
11056                cx.laid_out = Some(LaidText {
11057                    content,
11058                    layout: text_layout.clone(),
11059                    text: text.clone(),
11060                });
11061                cx.metadata_changed = false;
11062                if report_lines {
11063                    self.events.push(crate::element::JsEvent::Event(
11064                        id,
11065                        EventKind::TextLayout,
11066                        text_lines(engine, &text, &text_layout),
11067                    ));
11068                    keep_geometry(
11069                        &self.geometry_engine,
11070                        &mut self.geometries,
11071                        id,
11072                        &text_layout,
11073                        &text,
11074                        &cx.spacers,
11075                    );
11076                }
11077                if !text.attachments.is_empty() {
11078                    placements.push((key, text_layout.clone(), content));
11079                }
11080                self.mount.push(MountItem::Text {
11081                    id,
11082                    text,
11083                    layout: text_layout,
11084                    content,
11085                });
11086                continue;
11087            }
11088            if let Some(lines) = lines_in_box(engine, cache, cx, typeset(size.width), size.height) {
11089                // A box shorter than its lines (a fixed height, no or a
11090                // larger `numberOfLines`): the lines that fit, the last one
11091                // cut as the text says (an ellipsis by default, `text-clip`
11092                // none), as CoreText does in a frame. Laid out on its own,
11093                // as a fitted text.
11094                if matches!(&cx.laid_out, Some(l) if l.content == content && l.text.max_lines == lines)
11095                {
11096                    continue;
11097                }
11098                let mut clamped = (*cx.text).clone();
11099                clamped.max_lines = lines;
11100                let text = Arc::new(clamped);
11101                let prepared = engine.prepare_with(&text, &cx.alignments, &cx.options);
11102                let text_layout =
11103                    engine.layout(&prepared, Size::new(typeset(size.width), size.height));
11104                cx.laid_out = Some(LaidText {
11105                    content,
11106                    layout: text_layout.clone(),
11107                    text: text.clone(),
11108                });
11109                cx.metadata_changed = false;
11110                if report_lines {
11111                    self.events.push(crate::element::JsEvent::Event(
11112                        id,
11113                        EventKind::TextLayout,
11114                        text_lines(engine, &text, &text_layout),
11115                    ));
11116                    keep_geometry(
11117                        &self.geometry_engine,
11118                        &mut self.geometries,
11119                        id,
11120                        &text_layout,
11121                        &text,
11122                        &cx.spacers,
11123                    );
11124                }
11125                if !text.attachments.is_empty() {
11126                    placements.push((key, text_layout.clone(), content));
11127                }
11128                self.mount.push(MountItem::Text {
11129                    id,
11130                    text,
11131                    layout: text_layout,
11132                    content,
11133                });
11134                continue;
11135            }
11136            let text_layout = match &cx.laid_out {
11137                Some(l) if l.content == content => continue,
11138                // Only moved (padding, vertical alignment): the same layout.
11139                Some(l) if l.content.size == size => l.layout.clone(),
11140                // Another width with the same lines in the same places: what
11141                // a window's resize does to most text, typeset for nothing.
11142                Some(l) if keeps_lines(cx, l, size) => l.layout.clone(),
11143                _ => {
11144                    let prepared = cx.prepared.get_or_insert_with(|| {
11145                        engine.prepare_with(&cx.text, &cx.alignments, &cx.options)
11146                    });
11147                    let layout =
11148                        engine.layout(prepared, Size::new(typeset(size.width), size.height));
11149                    if report_lines {
11150                        self.events.push(crate::element::JsEvent::Event(
11151                            id,
11152                            EventKind::TextLayout,
11153                            text_lines(engine, &cx.text, &layout),
11154                        ));
11155                        keep_geometry(
11156                            &self.geometry_engine,
11157                            &mut self.geometries,
11158                            id,
11159                            &layout,
11160                            &cx.text,
11161                            &cx.spacers,
11162                        );
11163                    }
11164                    layout
11165                }
11166            };
11167            cx.laid_out = Some(LaidText {
11168                content,
11169                layout: text_layout.clone(),
11170                text: cx.text.clone(),
11171            });
11172            cx.metadata_changed = false;
11173            if !cx.text.attachments.is_empty() {
11174                placements.push((key, text_layout.clone(), content));
11175            }
11176            self.mount.push(MountItem::Text {
11177                id,
11178                text: cx.text.clone(),
11179                layout: text_layout,
11180                content,
11181            });
11182        }
11183        pending.clear();
11184        self.pending_text = pending;
11185        for (key, layout, content) in placements {
11186            self.place_attachments(key, &layout, content);
11187        }
11188    }
11189
11190    /// Moves the views of text block `key`'s attachments onto their
11191    /// placeholders in `layout` (content box `content`); cut off ones out
11192    /// of sight.
11193    fn place_attachments(&mut self, key: Key, layout: &TextLayout, content: Bounds<Points>) {
11194        let mut points = self.text_engine.attachments(layout);
11195        if let Some(l) = self.nodes[key as usize].layout {
11196            // Padding of spans is no view's.
11197            let cx = self.text_cx(l);
11198            if !cx.spacers.is_empty() {
11199                let mut indices = cx.text.attachments.iter().map(|a| a.index);
11200                points.retain(|_| indices.next().is_none_or(|i| !cx.spacers.contains(&i)));
11201            }
11202        }
11203        let attached = std::mem::take(&mut self.nodes[key as usize].attached);
11204        for (i, &id) in attached.iter().enumerate() {
11205            let Ok(a) = self.key(id) else { continue };
11206            let Some(l) = self.nodes[a as usize].layout else {
11207                continue;
11208            };
11209            let size = self.rounded_layout(l).size;
11210            let (x, y) = match points.get(i).copied().flatten() {
11211                Some(p) => (content.origin.x.0 + p.x.0, content.origin.y.0 + p.y.0),
11212                // Far away, like unbound list cells.
11213                None => (-100_000.0, 0.0),
11214            };
11215            self.set_frame(a, rect(x, y, size.width, size.height));
11216        }
11217        self.nodes[key as usize].attached = attached;
11218    }
11219
11220    /// Emits the frame of `key` and its subtree (if changed).
11221    fn emit_frames(&mut self, key: Key) {
11222        let parent = self.nodes[key as usize].parent;
11223        let hidden = parent != NO_KEY && self.displays_none(parent);
11224        let origin = self.nodes[key as usize]
11225            .layout
11226            .and_then(|l| self.layout.parent(l))
11227            .map_or(Origin::default(), |parent| self.box_origin(parent));
11228        self.emit_frames_in(key, hidden, origin);
11229    }
11230
11231    /// [`Core::emit_frames`] of `key`, `hidden` when a view around it is
11232    /// `display: none`. A view in such a subtree has no frame whatever
11233    /// Taffy keeps for it: Taffy can leave a node moved into a hidden
11234    /// subtree with its former layout (its dirty marking stops at the
11235    /// first node whose cache is empty, which hidden nodes' always are),
11236    /// and never rounds the absolutely positioned ones there (they are
11237    /// rounded through their containing block, which hidden layout does
11238    /// not record), so their native views would keep showing at their
11239    /// former size in a parent of no size.
11240    ///
11241    /// `origin` is where the layout of the view around it is in its layout
11242    /// root ([`Origin`]), carried down the walk.
11243    fn emit_frames_in(&mut self, key: Key, hidden: bool, origin: Origin) {
11244        let node = &self.nodes[key as usize];
11245        let Some(layout) = node.layout else { return };
11246        if !node.created {
11247            if node.culled {
11248                self.cull_frames_in(key, hidden, origin);
11249            }
11250            return;
11251        }
11252        let hidden = hidden || self.layout.displays_none(layout);
11253        if hidden {
11254            self.layout.emitted(layout);
11255            self.nodes[key as usize].emitted = None;
11256            if self.nodes[key as usize].follow.is_some() {
11257                self.laid_follower(key, None, false, (0.0, 0.0));
11258            }
11259            self.set_frame(key, Bounds::default());
11260            // An input's field would still show at its former content box
11261            // where a platform does not clip a view's children (a browser),
11262            // so it gets none either.
11263            let node = &mut self.nodes[key as usize];
11264            if let Some(input) = node.input.as_mut()
11265                && input.content.is_some_and(|c| c != Bounds::default())
11266            {
11267                input.content = Some(Bounds::default());
11268                self.mount.push(MountItem::InputContent {
11269                    id: node.id,
11270                    content: Bounds::default(),
11271                });
11272            }
11273            if self.nodes[key as usize].kind.is_container() {
11274                let children = std::mem::take(&mut self.nodes[key as usize].children);
11275                for &child in &children {
11276                    if !self.nodes[child as usize].is_layout_root() {
11277                        self.emit_frames_in(child, true, origin);
11278                    }
11279                }
11280                self.nodes[key as usize].children = children;
11281            }
11282            return;
11283        }
11284        let node = &self.nodes[key as usize];
11285        let unrounded = *self.layout.unrounded_layout(layout);
11286        // An absolute view in a positioned parent (React Native's default
11287        // `relative`) is placed in that parent, whose origin is `origin`,
11288        // summed in the same order as `layout_origin` sums it: only one
11289        // placed further up walks there (every cell of a table would walk to
11290        // the root, each frame the tree is laid out).
11291        let position = self.layout.style(layout).position;
11292        let escaping = position == Position::Fixed
11293            || (position == Position::Absolute
11294                && !self
11295                    .layout
11296                    .parent(layout)
11297                    .is_some_and(|p| self.layout.style(p).position.is_positioned()));
11298        let ratio = self.frame_ratio();
11299        // Nothing in the subtree was laid out anew and its origin moved by
11300        // whole device pixels (or not at all), its edges as they were: every
11301        // frame in it, relative to its parent, rounds as it did. A scroll
11302        // that moves a table's rows walks the rows' origin, not each cell.
11303        if !self.layout.stale(layout)
11304            && !node.escapes
11305            && !node.is_overlay()
11306            && !node.decoration
11307            && !self.nodes.get(node.parent as usize).is_some_and(|p| p.rtl)
11308            && node.emitted.is_some_and(|(at, r)| {
11309                let moved = |a: f32, b: f32, ratio: f32| {
11310                    let d = (a - b) * ratio;
11311                    d == d.round()
11312                };
11313                r == ratio
11314                    && at.back == origin.back
11315                    && moved(origin.at.x, at.at.x, ratio.width)
11316                    && moved(origin.at.y, at.at.y, ratio.height)
11317            })
11318        {
11319            self.nodes[key as usize].emitted = Some((origin, ratio));
11320            return;
11321        }
11322        self.layout.emitted(layout);
11323        let containing = if escaping {
11324            self.containing_origin(layout)
11325        } else {
11326            origin
11327        };
11328        let inner = Origin::of(
11329            taffy::Point {
11330                x: containing.at.x + unrounded.location.x,
11331                y: containing.at.y + unrounded.location.y,
11332            },
11333            unrounded.size,
11334            ratio,
11335        );
11336        let l = rounded(&unrounded, containing, ratio);
11337        let offset = origin.to(containing, ratio);
11338        let mut frame = rect(
11339            l.location.x + offset.x,
11340            l.location.y + offset.y,
11341            l.size.width,
11342            l.size.height,
11343        );
11344        // Children of a right-to-left horizontal scroll view: mirrored in
11345        // its content (not its bar, over the viewport).
11346        if let Some(parent) = self.nodes.get(node.parent as usize)
11347            && !node.decoration
11348            && parent.rtl
11349            && let Some(ScrollState {
11350                horizontal: true,
11351                content: Some(content),
11352                ..
11353            }) = parent.scroll.as_deref()
11354            && parent.kind == Kind::Scroll
11355        {
11356            frame.origin.x = content.width - frame.origin.x - frame.size.width;
11357        }
11358        if node.is_overlay() {
11359            frame.origin = self.overlay_origin(key, frame);
11360        }
11361        // A multiline input's bar: over it, laid out on its own.
11362        let beside = self.nodes[key as usize].beside;
11363        if beside != NO_KEY {
11364            frame.origin = self.nodes[beside as usize].frame.origin;
11365        } else if self.nodes[key as usize].decoration {
11366            // A scroll view's bar is laid out on its own, at no location:
11367            // `origin` is where it sits in the viewport (its
11368            // `scrollbar_inset`, [`Core::layout_scrollbars`]).
11369            let offset = Origin::default().to(origin, ratio);
11370            frame.origin.x.0 += offset.x;
11371            frame.origin.y.0 += offset.y;
11372        }
11373        if self.nodes[key as usize].follow.is_some() {
11374            // Its frame along the main axis is the element's it follows,
11375            // laid out by now or not: placed once every frame is out.
11376            let column = self.layout.parent(layout).is_some_and(|p| {
11377                let style = self.layout.style(p);
11378                style.display == taffy::Display::Flex
11379                    && matches!(
11380                        style.flex_direction,
11381                        taffy::FlexDirection::Column | taffy::FlexDirection::ColumnReverse
11382                    )
11383            });
11384            let m = unrounded.margin;
11385            let margins = if column {
11386                (round(m.top, ratio.height), round(m.bottom, ratio.height))
11387            } else {
11388                (round(m.left, ratio.width), round(m.right, ratio.width))
11389            };
11390            self.laid_follower(key, Some(frame), column, margins);
11391        } else {
11392            self.set_frame(key, frame);
11393        }
11394        self.sync_cell_style(key, layout, &unrounded);
11395        self.sync_focus_ring(key);
11396        let kind = self.nodes[key as usize].kind;
11397        if kind == Kind::Input {
11398            let content = content_box(&l);
11399            let node = &mut self.nodes[key as usize];
11400            let input = node.input.as_mut().expect("input state");
11401            if input.content != Some(content) {
11402                input.content = Some(content);
11403                self.mount.push(MountItem::InputContent {
11404                    id: node.id,
11405                    content,
11406                });
11407            }
11408            if node.events.contains(EventKind::ContentSizeChange) {
11409                self.report_content_size(key, content.size.width.0);
11410            }
11411        }
11412        if kind == Kind::Scroll {
11413            let horizontal = self.nodes[key as usize]
11414                .scroll
11415                .as_ref()
11416                .is_some_and(|s| s.horizontal);
11417            self.set_scroll_content(key, scroll_extent(&l, horizontal));
11418        }
11419        // List cells are positioned by `update_lists`, roots by
11420        // `layout_roots`.
11421        let mut escapes = escaping;
11422        if kind.is_container() && kind != Kind::List {
11423            let children = std::mem::take(&mut self.nodes[key as usize].children);
11424            for &child in &children {
11425                if !self.nodes[child as usize].is_layout_root() {
11426                    self.emit_frames_in(child, false, inner);
11427                    escapes |= self.nodes[child as usize].escapes;
11428                }
11429            }
11430            self.nodes[key as usize].children = children;
11431            self.update_overflow(key);
11432        }
11433        let node = &mut self.nodes[key as usize];
11434        node.escapes = escapes;
11435        node.emitted = Some((origin, ratio));
11436    }
11437
11438    /// In a terminal, mounts node `key` without the borders its layout
11439    /// `l` gives no Cell (`Node::cell_border`) and with whether that layout
11440    /// shows its label (`Node::cell_label`), again when either changes;
11441    /// off a terminal, with its borders as styled again and no label.
11442    fn sync_cell_style(&mut self, key: Key, layout: LayoutId, l: &taffy::Layout) {
11443        let w = self.nodes[key as usize].view_style.borders.widths;
11444        let styled = [w.top, w.right, w.bottom, w.left]
11445            .iter()
11446            .any(|&v| v > Points::ZERO);
11447        // Only a bordered view's style changes.
11448        let sides = self.layout.grid().filter(|_| styled).map(|_| {
11449            let b = l.border;
11450            [b.top, b.right, b.bottom, b.left]
11451                .iter()
11452                .enumerate()
11453                .fold(0u8, |m, (bit, &v)| m | (u8::from(v > 0.0) << bit))
11454        });
11455        let label = self.layout.labelled(layout);
11456        let node = &mut self.nodes[key as usize];
11457        if node.cell_border == sides && node.cell_label == label {
11458            return;
11459        }
11460        node.cell_border = sides;
11461        node.cell_label = label;
11462        let id = node.id;
11463        let style = self.mounted_view_style(key);
11464        self.mount.push(MountItem::ViewStyle { id, style });
11465    }
11466
11467    /// Queues node `key`'s frame for its layout listeners once it was laid
11468    /// out: a listener added after layout still learns the frame.
11469    fn report_frame(&mut self, key: Key) {
11470        let node = &self.nodes[key as usize];
11471        if !node.frame.origin.x.0.is_nan() {
11472            self.events.push(crate::element::JsEvent::Event(
11473                node.id,
11474                EventKind::Layout,
11475                EventPayload::Layout(node.frame),
11476            ));
11477        }
11478    }
11479
11480    fn set_frame(&mut self, key: Key, frame: Bounds<Points>) {
11481        let node = &mut self.nodes[key as usize];
11482        if node.frame != frame {
11483            let resized = node.frame.size != frame.size;
11484            node.frame = frame;
11485            self.note_resized(key, resized);
11486            // What views follow may have moved.
11487            self.follow_changed |= !self.followers.is_empty();
11488            let node = &self.nodes[key as usize];
11489            let (id, is_text) = (node.id, node.kind == Kind::Text);
11490            if node.events.contains(EventKind::Layout) {
11491                self.events.push(crate::element::JsEvent::Event(
11492                    id,
11493                    EventKind::Layout,
11494                    EventPayload::Layout(frame),
11495                ));
11496            }
11497            if node.created {
11498                self.mount.push(MountItem::Frame { id, frame });
11499            }
11500            let node = &self.nodes[key as usize];
11501            // A list's cell moved: the logical order goes by where cells are.
11502            if self.track_tree_order
11503                && node.parent != NO_KEY
11504                && self.nodes[node.parent as usize].list.is_some()
11505            {
11506                self.tree_order_changed = true;
11507            }
11508            let node = &self.nodes[key as usize];
11509            // Translations by a fraction of the size follow it, and so does
11510            // the perspective of its parent, seen from the parent's center.
11511            let parent_perspective = self.perspective_steps(key) > 0;
11512            if node.created && (node.view_style.transform.has_fractions() || parent_perspective) {
11513                let style = self.mounted_view_style(key);
11514                self.mount.push(MountItem::ViewStyle { id, style });
11515            }
11516            if node.child_perspective.is_some() {
11517                // Its center moved for its children.
11518                let children = node.children.clone();
11519                for c in children {
11520                    self.mark(c, dirty::VIEW);
11521                }
11522            }
11523            if is_text {
11524                self.queue_text(key);
11525            }
11526            // A view box fits into the new size.
11527            let node = &self.nodes[key as usize];
11528            if node.kind == Kind::Canvas && node.drawing.as_ref().is_some_and(|d| d.fit().is_some())
11529            {
11530                self.fitted_pending.push(key);
11531            }
11532        }
11533    }
11534
11535    fn set_scroll_content(&mut self, key: Key, size: Size<Points>) {
11536        let node = &mut self.nodes[key as usize];
11537        let (id, rtl, kind, viewport) = (node.id, node.rtl, node.kind, node.frame.size.width.0);
11538        if let Some(scroll) = node.scroll.as_mut()
11539            && scroll.content != Some(size)
11540        {
11541            let old = scroll.content.replace(size);
11542            // Items are only inserted before it since (a `ScrollBy`, the
11543            // layout animation), so it is at its index or later.
11544            let batch = self.batches;
11545            let queued = scroll
11546                .content_item
11547                .filter(|&(b, _)| b == batch)
11548                .and_then(|(_, i)| {
11549                    let at = self.mount.get(i..)?.iter().position(
11550                        |m| matches!(m, MountItem::ScrollContent { id: queued, .. } if *queued == id),
11551                    )?;
11552                    Some(i + at)
11553                });
11554            // A shrink after a scroll must keep the earlier extent until
11555            // that scroll has applied. Growth can replace the extent once.
11556            let shrunk = old.is_some_and(|old| {
11557                if scroll.horizontal {
11558                    size.width < old.width
11559                } else {
11560                    size.height < old.height
11561                }
11562            });
11563            let keep_earlier = shrunk
11564                && queued.is_some_and(|j| {
11565                    self.mount[j + 1..].iter().any(|item| match item {
11566                        MountItem::ScrollBy { id: scrolled, .. } => *scrolled == id,
11567                        MountItem::Command {
11568                            id: scrolled,
11569                            command: Command::ScrollTo { .. },
11570                        } => *scrolled == id,
11571                        _ => false,
11572                    })
11573                });
11574            if let Some(j) = queued
11575                && !keep_earlier
11576            {
11577                self.mount[j] = MountItem::ScrollContent { id, size };
11578            }
11579            if queued.is_none() || keep_earlier {
11580                scroll.content_item = Some((batch, self.mount.len()));
11581                self.mount.push(MountItem::ScrollContent { id, size });
11582            }
11583            // Right to left, a horizontal scroll view starts at its right
11584            // end and keeps its distance from it as the content changes.
11585            if kind == Kind::Scroll && scroll.horizontal && rtl {
11586                match old {
11587                    None => self.commands.push((
11588                        id,
11589                        Command::ScrollTo {
11590                            x: (size.width - Points(viewport)).max(Points::ZERO),
11591                            y: Points::ZERO,
11592                            animated: false,
11593                        },
11594                    )),
11595                    Some(old) if old.width != size.width => {
11596                        let dx = size.width - old.width;
11597                        self.mount.push(MountItem::ScrollBy {
11598                            id,
11599                            dx,
11600                            dy: Points::ZERO,
11601                        });
11602                        self.scroll_issued(key, PendingScroll::By(dx.0));
11603                    }
11604                    Some(_) => {}
11605                }
11606            }
11607        }
11608    }
11609
11610    /// Measures rendered cells, keeps the visible content anchored, picks
11611    /// the items to render and positions the cells of every list.
11612    fn update_lists(&mut self, relayout: bool) {
11613        // A cell measured before JS's render of its content arrives would
11614        // record the size of its empty placeholders.
11615        let mut awaiting = std::mem::take(&mut self.awaiting_renders);
11616        self.cells_awaiting_renders(&mut awaiting);
11617        self.awaiting_renders = awaiting;
11618        for i in 0..self.lists.len() {
11619            let key = self.lists[i];
11620            // Lists in their parent's viewport come after, outer ones first.
11621            if self.nodes[key as usize]
11622                .list
11623                .as_ref()
11624                .is_some_and(|l| l.parent)
11625            {
11626                continue;
11627            }
11628            self.update_list(key, relayout, None);
11629        }
11630        if !self.parent_lists.is_empty() {
11631            if self.outer_moved {
11632                self.resolve_outer();
11633            }
11634            for i in 0..self.parent_lists.len() {
11635                let key = self.parent_lists[i];
11636                if !self.nodes[key as usize].created {
11637                    continue;
11638                }
11639                // Out of the tree, or not placed yet.
11640                let Some(outer) = self.outer_input(key) else {
11641                    continue;
11642                };
11643                self.update_list(key, relayout, Some(outer));
11644            }
11645        }
11646        if !self.sticky_nodes.is_empty()
11647            || !self.sticky_scrollers.is_empty()
11648            || !self.decorated.is_empty()
11649        {
11650            self.update_sticky_views(relayout);
11651        }
11652        if !self.sticky_views.is_empty() {
11653            self.send_page_sticky();
11654        }
11655    }
11656
11657    /// Hides the attachments of text `key` (views and images inside it) that
11658    /// are inside a hidden span, `hidden` when `key` is one, and shows the
11659    /// others: nothing of a hidden span is drawn or takes presses.
11660    fn hide_attachments(&mut self, key: Key, hidden: bool) {
11661        let count = self.nodes[key as usize].children.len();
11662        for i in 0..count {
11663            let c = self.nodes[key as usize].children[i];
11664            let child = &self.nodes[c as usize];
11665            if child.is_overlay() {
11666                continue;
11667            }
11668            match child.kind {
11669                Kind::RawText | Kind::Overlay => {}
11670                Kind::Text => {
11671                    let hidden = hidden || child.view_style.hidden;
11672                    self.hide_attachments(c, hidden);
11673                }
11674                _ if child.layout.is_some() => self.set_hidden_in_text(c, hidden),
11675                _ => {}
11676            }
11677        }
11678    }
11679
11680    /// Hides attachment `key` with the hidden span it is in, or shows it
11681    /// again; sent at once, as [`Core::set_spare`].
11682    fn set_hidden_in_text(&mut self, key: Key, hidden: bool) {
11683        let node = &mut self.nodes[key as usize];
11684        if node.hidden_in_text == hidden {
11685            return;
11686        }
11687        node.hidden_in_text = hidden;
11688        if !node.created {
11689            // Its new view gets both (`ensure_created`).
11690            return;
11691        }
11692        let (id, props) = (node.id, node.mounted_props());
11693        let style = self.mounted_view_style(key);
11694        self.mount.push(MountItem::ViewStyle { id, style });
11695        self.mount.push(MountItem::ViewProps { id, props });
11696    }
11697
11698    /// Hides list cell `key`, which has no item but still shows its last
11699    /// row (`visibility: hidden` and `accessibilityElementsHidden`), or
11700    /// shows it again as its list places it. Sent at once: this round's
11701    /// dirty flags were flushed before the lists' update.
11702    fn set_spare(&mut self, key: Key, spare: bool) {
11703        let node = &mut self.nodes[key as usize];
11704        if node.spare == spare {
11705            return;
11706        }
11707        node.spare = spare;
11708        // A spare cell shows no row for views to follow (`follow.rs`).
11709        self.follow_changed |= !self.followers.is_empty();
11710        let node = &self.nodes[key as usize];
11711        if !node.created {
11712            // Its new view gets both (`ensure_created`).
11713            return;
11714        }
11715        let (id, props) = (node.id, node.mounted_props());
11716        let style = self.mounted_view_style(key);
11717        self.mount.push(MountItem::ViewStyle { id, style });
11718        self.mount.push(MountItem::ViewProps { id, props });
11719    }
11720
11721    /// Hides list cell `key`, which the render window left behind, from
11722    /// assistive technology, or reads it again as its list places it: its
11723    /// frame is where its row was laid out last, which rows measured since
11724    /// may have moved past. Its props only: it stays drawn, out of sight.
11725    fn set_left_behind(&mut self, key: Key, left_behind: bool) {
11726        let node = &mut self.nodes[key as usize];
11727        if node.left_behind == left_behind {
11728            return;
11729        }
11730        node.left_behind = left_behind;
11731        if !node.created || node.spare {
11732            // Its new view gets them (`ensure_created`), or `set_spare`
11733            // sends them as it shows the cell again.
11734            return;
11735        }
11736        let (id, props) = (node.id, node.mounted_props());
11737        self.mount.push(MountItem::ViewProps { id, props });
11738    }
11739
11740    /// [`Core::update_lists`] for list `key`; `outer`: where a list in its
11741    /// parent's viewport is in the view it is virtualized against.
11742    fn update_list(
11743        &mut self,
11744        key: Key,
11745        relayout: bool,
11746        outer: Option<parent_viewport::OuterInput>,
11747    ) {
11748        let moved = match &outer {
11749            Some(o) => self.nodes[key as usize]
11750                .list
11751                .as_mut()
11752                .expect("list")
11753                .set_outer(o.start, o.offset, o.viewport, o.max, o.settled),
11754            None => false,
11755        };
11756        let node = &self.nodes[key as usize];
11757        if !node.created {
11758            return;
11759        }
11760        // Under `display: none` it has no size, which is no viewport to
11761        // empty its window by: it keeps its rows bound until it shows again
11762        // (a page kept alive under a hidden tab).
11763        if self.displays_none(key) {
11764            return;
11765        }
11766        let list = node.list.as_ref().expect("list");
11767        if !(relayout || moved || list.dirty || self.commands.iter().any(|c| c.0 == node.id)) {
11768            return;
11769        }
11770        let (id, events) = (node.id, node.events);
11771        let horizontal = list.horizontal;
11772        let l = self.rounded_layout(node.layout.expect("list layout"));
11773        let (main, cross) = match &outer {
11774            // The view's viewport, and the list's content box across.
11775            Some(o) => (o.viewport, o.cross),
11776            None if horizontal => (l.size.width, l.size.height),
11777            None => (l.size.height, l.size.width),
11778        };
11779        let main_of = |s: taffy::Size<f32>| if horizontal { s.width } else { s.height };
11780
11781        // Sizes of cells showing their item, and of the extras.
11782        let mut ready = std::mem::take(&mut self.cells_scratch);
11783        ready.clear();
11784        ready.extend(
11785            list.slots
11786                .iter()
11787                .filter_map(|s| s.ready().map(|i| (i, s.cell))),
11788        );
11789        let extras = list.extras;
11790        // An inverted list that loads at its start keeps its rows in
11791        // place when scrolled away from it (`keeps_visible_rows`).
11792        self.nodes[key as usize]
11793            .list
11794            .as_mut()
11795            .expect("list")
11796            .loads_at_start = events.contains(EventKind::LoadMoreAtStart);
11797        let mut anchor = 0.0;
11798        // Extras first: a footer that shrank moves the content's end, and
11799        // rows measured after it are judged against the offset the
11800        // shrunk content allows (#3925).
11801        for (kind, extra) in [ExtraKind::Header, ExtraKind::Footer, ExtraKind::Empty]
11802            .into_iter()
11803            .zip(extras)
11804        {
11805            if self.awaiting_renders.binary_search(&extra.cell).is_ok() {
11806                continue;
11807            }
11808            if let Some(cell_layout) = self.nodes.get(extra.cell as usize).and_then(|c| c.layout) {
11809                let size = main_of(self.rounded_layout(cell_layout).size);
11810                let list = self.nodes[key as usize].list.as_mut().expect("list");
11811                anchor += list.measured_extra(kind, size);
11812            }
11813        }
11814
11815        for &(index, cell) in &ready {
11816            // Waiting for JS's render: it keeps its estimate (or the size
11817            // measured last) until the holder arrives and lays it out
11818            // again. A list in a view sized by its content would otherwise
11819            // shrink to nothing and leave no row in its window to render.
11820            if self.awaiting_renders.binary_search(&cell).is_ok() {
11821                continue;
11822            }
11823            if let Some(cell_layout) = self.nodes.get(cell as usize).and_then(|c| c.layout) {
11824                let size = main_of(self.rounded_layout(cell_layout).size);
11825                let list = self.nodes[key as usize].list.as_mut().expect("list");
11826                anchor += list.measured(index, size);
11827            }
11828        }
11829
11830        // Its own scroll view's range takes the content inset in; in its
11831        // parent's viewport, the view around it has the range.
11832        let inset = match (&outer, self.nodes[key as usize].scroll.as_deref()) {
11833            (None, Some(scroll)) => {
11834                let i = scroll.behavior.content_inset;
11835                if horizontal {
11836                    (i.left.0, i.right.0)
11837                } else {
11838                    (i.top.0, i.bottom.0)
11839                }
11840            }
11841            _ => (0.0, 0.0),
11842        };
11843        let list = self.nodes[key as usize].list.as_mut().expect("list");
11844        // Not on the first layout: there is nothing to clamp yet.
11845        let grew = outer.is_none() && list.viewport > 0.0 && main > list.viewport;
11846        list.viewport = main;
11847        list.inset = inset;
11848        list.offset += anchor;
11849        // A splice above the viewport already moved the offset, to keep
11850        // the visible rows in place: like measurements, that says nothing
11851        // about where the user is.
11852        let spliced = list.take_splice_anchor();
11853        anchor += spliced;
11854        let kept = anchor;
11855        // A row growing under its own layout animation (a reveal) moves
11856        // the end while its frames slide: a scroll to the new end would
11857        // land at once, ahead of them, so the list keeps its place.
11858        let revealing = !self.scoped_layout.is_empty() && {
11859            let scoped = &self.scoped_layout;
11860            scoped.iter().any(|&(scope, ..)| {
11861                self.key(scope)
11862                    .is_ok_and(|k| k != key && self.is_within(k, key))
11863            })
11864        };
11865        let list = self.nodes[key as usize].list.as_mut().expect("list");
11866        list.revealing = revealing;
11867        // Inverted lists keep their distance from the end instead;
11868        // `maintainVisibleContentPosition` follows the end near it.
11869        anchor += list.anchor_end(kept);
11870        // The last scroll command's target moves as its cells are
11871        // measured: the list follows it.
11872        let mut retarget = None;
11873        match list.follow_pin(anchor) {
11874            Follow::Stay => {}
11875            Follow::By(delta) => anchor += delta,
11876            Follow::To(offset) => retarget = Some(offset),
11877        }
11878        // `maintainVisibleContentPosition={{ animated }}`: the end moved
11879        // away by a large step, so the list animates there instead of
11880        // jumping, and the pin keeps the animation's target at the end as
11881        // the content goes on growing.
11882        if list.take_animated_end() {
11883            let end = list.target_offset(PinTarget::End);
11884            list.pin(Some(PinTarget::End), end, true);
11885            retarget = Some(end);
11886        }
11887
11888        // The End key's commands, if any, are resolved below with the
11889        // rest (`Core::key_scrolled`).
11890        list.key_ends.clear();
11891        // Scroll commands for the list, now that sizes are known: the
11892        // window follows a jump in this same commit. In its parent's
11893        // viewport, the view around it scrolls instead.
11894        let mut outer_to = None;
11895        // The `ScrollTo`s sent with this layout, recorded after its
11896        // anchoring `ScrollBy` (below): the platform applies that one
11897        // first, a mount item before the commands. Counted the other way,
11898        // a report between the two would replay the `ScrollBy` over the
11899        // `ScrollTo` and leave the list believed away from where it is.
11900        let mut scrolls_to = Vec::new();
11901        for (target, command) in &mut self.commands {
11902            if *target != id {
11903                continue;
11904            }
11905            let list = self.nodes[key as usize].list.as_mut().expect("list");
11906            let (pin, animated) = match *command {
11907                Command::ScrollToIndex {
11908                    index,
11909                    animated,
11910                    view_position,
11911                    view_offset,
11912                } => (
11913                    Some(PinTarget::Index {
11914                        index,
11915                        view_position: view_position.0,
11916                        view_offset: view_offset.0,
11917                    }),
11918                    animated,
11919                ),
11920                Command::ScrollToEnd { animated } => (Some(PinTarget::End), animated),
11921                Command::ScrollTo { animated, .. } => (None, animated),
11922                _ => continue,
11923            };
11924            let offset = match (pin, &*command) {
11925                (Some(pin), _) => list.target_offset(pin),
11926                (None, &Command::ScrollTo { x, y, .. }) => {
11927                    let offset = if horizontal { x.0 } else { y.0 };
11928                    if outer.is_some() {
11929                        list.clamped(offset)
11930                    } else {
11931                        offset
11932                    }
11933                }
11934                _ => continue,
11935            };
11936            // An offset of the app's own ends the pin.
11937            list.pin(pin, offset, animated);
11938            // A new command replaces the pin's retargeting.
11939            retarget = None;
11940            if !animated {
11941                list.jump(offset);
11942            }
11943            if let Some(o) = &outer {
11944                outer_to = Some((o.start + offset, animated));
11945                continue;
11946            }
11947            scrolls_to.push((offset, animated));
11948            let (x, y) = if horizontal {
11949                (Points(offset), Points::ZERO)
11950            } else {
11951                (Points::ZERO, Points(offset))
11952            };
11953            *command = Command::ScrollTo { x, y, animated };
11954        }
11955        if outer_to.is_some() {
11956            // Sent to the view around the list instead.
11957            self.commands.retain(|(target, command)| {
11958                *target != id
11959                    || !matches!(
11960                        command,
11961                        Command::ScrollTo { .. }
11962                            | Command::ScrollToIndex { .. }
11963                            | Command::ScrollToEnd { .. }
11964                    )
11965            });
11966        }
11967        if let (Some(offset), Some(o)) = (retarget, &outer) {
11968            outer_to = Some((o.start + offset, true));
11969        } else if let Some(offset) = retarget {
11970            scrolls_to.push((offset, true));
11971            let (x, y) = if horizontal {
11972                (Points(offset), Points::ZERO)
11973            } else {
11974                (Points::ZERO, Points(offset))
11975            };
11976            let command = Command::ScrollTo {
11977                x,
11978                y,
11979                animated: true,
11980            };
11981            self.commands.push((id, command));
11982        }
11983
11984        // The components' own lists bind in the core, at once; the
11985        // runtime's pace their overscan.
11986        let paced = !self.components.is_virtual_list(id);
11987        let list = self.nodes[key as usize].list.as_mut().expect("list");
11988        list.paced = paced;
11989        let mut binds = Vec::new();
11990        let edges = list.update_window(&mut binds);
11991        if edges.end {
11992            self.events.push(crate::element::JsEvent::Event(
11993                id,
11994                EventKind::LoadMore,
11995                EventPayload::None,
11996            ));
11997        }
11998        if edges.start && events.contains(EventKind::LoadMoreAtStart) {
11999            self.events.push(crate::element::JsEvent::Event(
12000                id,
12001                EventKind::LoadMoreAtStart,
12002                EventPayload::None,
12003            ));
12004        }
12005        if !binds.is_empty() {
12006            self.list_binds.push(ListBind { list: id, binds });
12007        }
12008        if list.paced && list.has_paced() && !self.paced_lists.contains(&id) {
12009            self.paced_lists.push(id);
12010        }
12011        if events.contains(EventKind::ViewableItemsChange) {
12012            let viewable = list.viewable_items();
12013            if viewable != list.viewable {
12014                list.viewable = viewable;
12015                let (first, last) = viewable.map_or((-1.0, -1.0), |(f, l)| (f as f64, l as f64));
12016                self.events.push(crate::element::JsEvent::Event(
12017                    id,
12018                    EventKind::ViewableItemsChange,
12019                    EventPayload::Map(vec![
12020                        ("first", PayloadValue::Number(first)),
12021                        ("last", PayloadValue::Number(last)),
12022                    ]),
12023                ));
12024            }
12025        }
12026
12027        // Position cells that show their item (the window may have
12028        // changed which ones). Descendant frames only change when the
12029        // cell was laid out again.
12030        let list = self.nodes[key as usize].list.as_ref().expect("list");
12031        let sticky = list.sticky_enabled();
12032        ready.clear();
12033        ready.extend(
12034            list.slots
12035                .iter()
12036                .filter_map(|s| s.ready().map(|i| (i, s.cell))),
12037        );
12038        // A cell bound just now to the row it already shows (it took it
12039        // back after the items changed) gets no render to lay it out
12040        // again, and was not ready when the list measured above: measured
12041        // now, the rows after it are placed after its real size.
12042        for &(index, cell) in &ready {
12043            if self.awaiting_renders.binary_search(&cell).is_ok() {
12044                continue;
12045            }
12046            if let Some(cell_layout) = self.nodes.get(cell as usize).and_then(|c| c.layout) {
12047                let size = main_of(self.rounded_layout(cell_layout).size);
12048                let list = self.nodes[key as usize].list.as_mut().expect("list");
12049                list.measured_unknown(index, size);
12050            }
12051        }
12052        let list = self.nodes[key as usize].list.as_ref().expect("list");
12053        let content_len = list.content_len();
12054        let blocks = list.blocks();
12055        // Cells left without an item, or not showing theirs yet (a paced
12056        // bind, or one the frame's rounds did not reach), still show their
12057        // last one. Those in the render window (the data changed, the list
12058        // jumped) would show through: move them out of sight. They, the ones
12059        // never placed and, once the items changed, all of them are hidden
12060        // until placed again ([`Core::set_spare`]); the few the window leaves
12061        // behind while scrolling are out of sight already and soon reused,
12062        // so they stay drawn, but screen readers skip them: they would read
12063        // rows out of the window, by frames rows measured since may have
12064        // passed ([`Core::set_left_behind`]).
12065        let (window_start, window_end) = list.render_window();
12066        let motion = outer.is_none() && self.list_motion.active();
12067        if motion {
12068            let cells: Vec<Key> = list
12069                .slots
12070                .iter()
12071                .map(|s| s.cell)
12072                .chain(list.extras.iter().map(|e| e.cell))
12073                .collect();
12074            self.note_cell_starts(cells);
12075        }
12076        let list = self.nodes[key as usize].list.as_ref().expect("list");
12077        // In its parent's viewport, the cells start inside the list's
12078        // border and padding.
12079        let inset = outer.map_or((0.0, 0.0), |o| o.inset);
12080        let unbound: Vec<Key> = list
12081            .slots
12082            .iter()
12083            .filter(|s| s.ready().is_none() && s.cell != u32::MAX)
12084            .map(|s| s.cell)
12085            .collect();
12086        let changed = std::mem::take(
12087            &mut self.nodes[key as usize]
12088                .list
12089                .as_mut()
12090                .expect("list")
12091                .items_changed,
12092        );
12093        for cell in unbound {
12094            let frame = self.nodes[cell as usize].frame;
12095            if frame.size.width.0.is_nan() {
12096                // Never placed: nowhere to move it from.
12097                self.set_spare(cell, true);
12098                continue;
12099            }
12100            let (start, size) = if horizontal {
12101                (frame.origin.x.0 - inset.0, frame.size.width.0)
12102            } else {
12103                (frame.origin.y.0 - inset.0, frame.size.height.0)
12104            };
12105            if start + size <= window_start || start >= window_end {
12106                if changed {
12107                    self.set_spare(cell, true);
12108                } else {
12109                    self.set_left_behind(cell, true);
12110                }
12111                continue;
12112            }
12113            self.set_spare(cell, true);
12114            let away = if horizontal {
12115                Bounds {
12116                    origin: Point::new(Points(-HIDDEN), frame.origin.y),
12117                    ..frame
12118                }
12119            } else {
12120                Bounds {
12121                    origin: Point::new(frame.origin.x, Points(-HIDDEN)),
12122                    ..frame
12123                }
12124            };
12125            if frame != away {
12126                self.set_frame(cell, away);
12127                self.nodes[key as usize]
12128                    .list
12129                    .as_mut()
12130                    .expect("list")
12131                    .unplace(cell);
12132            }
12133        }
12134        let mut sticky_cells = Vec::new();
12135        let place = |this: &mut Self, cell: Key, at: f32, row: f32, (x, width): (f32, f32)| {
12136            let cell_layout = this.nodes.get(cell as usize).and_then(|c| c.layout)?;
12137            let size = this.rounded_layout(cell_layout).size;
12138            let list = this.nodes[key as usize].list.as_ref().expect("list");
12139            let mut main_at = list.to_content(at, row.max(main_of(size)));
12140            let mut x = x;
12141            if outer.is_some() {
12142                main_at += inset.0;
12143                x += inset.1;
12144            }
12145            let cell_cross = if horizontal { size.height } else { size.width };
12146            x = list.align_cross(x, width, cell_cross);
12147            let frame = if horizontal {
12148                rect(main_at, x, size.width, cell_cross)
12149            } else {
12150                rect(x, main_at, cell_cross, size.height)
12151            };
12152            this.set_frame(cell, frame);
12153            this.set_left_behind(cell, false);
12154            this.set_spare(cell, false);
12155            if std::mem::take(&mut this.nodes[cell as usize].relaid) {
12156                // A cell that waits to be made (`pace.rs`) made none of
12157                // its views: they wait with it, placed as culled views
12158                // are, so the ones that show are made when the cell is,
12159                // not behind every view that waits out of sight.
12160                let waits = {
12161                    let node = &this.nodes[cell as usize];
12162                    !node.created && node.culled
12163                };
12164                let children = std::mem::take(&mut this.nodes[cell as usize].children);
12165                for &child in &children {
12166                    if waits {
12167                        let node = &mut this.nodes[child as usize];
12168                        if !node.created && !node.is_layout_root() {
12169                            node.culled = true;
12170                        }
12171                    }
12172                    this.emit_frames(child);
12173                }
12174                this.nodes[cell as usize].children = children;
12175                this.update_overflow(cell);
12176                this.cells_framed = true;
12177            }
12178            Some(main_of(size))
12179        };
12180        // In a terminal the columns are whole Cells of the width the cells
12181        // were laid out at (`layout_cells`: without the scroll bar's
12182        // column).
12183        let unit = self
12184            .layout
12185            .grid()
12186            .map(|g| if horizontal { g.height } else { g.width });
12187        let columns_cross = {
12188            let laid = self.nodes[key as usize]
12189                .list
12190                .as_ref()
12191                .expect("list")
12192                .cells_cross;
12193            if unit.is_some() && laid.is_finite() {
12194                laid
12195            } else {
12196                cross
12197            }
12198        };
12199        let mut placed = list_motion::Placed::default();
12200        for &(index, cell) in &ready {
12201            let list = self.nodes[key as usize].list.as_ref().expect("list");
12202            let (at, row) = (list.item_at(index), list.row_extent(index));
12203            let column = list.column(columns_cross, list.column_of(index), unit);
12204            let Some(size) = place(self, cell, at, row, column) else {
12205                continue;
12206            };
12207            let list = self.nodes[key as usize].list.as_mut().expect("list");
12208            if list.place(index) {
12209                placed.new.push(cell);
12210            } else {
12211                placed.kept.push(cell);
12212            }
12213            let list = self.nodes[key as usize].list.as_ref().expect("list");
12214            if sticky && list.sticky.binary_search(&index).is_ok() {
12215                let range = list.sticky_range(index, self.nodes[cell as usize].id, size);
12216                sticky_cells.push(range);
12217            }
12218        }
12219        let full = self.nodes[key as usize]
12220            .list
12221            .as_ref()
12222            .expect("list")
12223            .full_width(columns_cross);
12224        for (extra, at) in extras
12225            .iter()
12226            .zip([blocks.header, blocks.footer, blocks.body])
12227        {
12228            if extra.cell != u32::MAX && place(self, extra.cell, at, 0.0, full).is_some() {
12229                placed.kept.push(extra.cell);
12230            }
12231        }
12232        self.cells_scratch = ready;
12233
12234        sticky_cells.sort_by_key(|c| c.cell);
12235        let list = self.nodes[key as usize].list.as_mut().expect("list");
12236        if let Some(o) = &outer {
12237            // The view around the list pins them, with its other lists'.
12238            if sticky_cells != list.sent_sticky {
12239                let old = std::mem::replace(&mut list.sent_sticky, sticky_cells);
12240                self.page_sticky_changed(key, o.view, &old);
12241            }
12242        } else if sticky_cells != list.sent_sticky {
12243            // Sent at the end of the commit in one set with the other
12244            // views it pins (its built-in bar, its sticky views, its lists'
12245            // rows in its viewport): a set of its rows alone would drop the
12246            // others and raise its rows above its bar.
12247            list.sent_sticky = sticky_cells;
12248            self.sticky_views.push(key);
12249        }
12250
12251        if let Some(o) = &outer {
12252            // The view around the list scrolls (the commit sends it at
12253            // its end; a scroll to an offset after the anchoring, which
12254            // it supersedes), and the list takes its new length in layout.
12255            if anchor != 0.0 {
12256                self.ask_outer(o.view, None, anchor);
12257            }
12258            if outer_to.is_some() {
12259                self.ask_outer(o.view, outer_to, 0.0);
12260            }
12261            self.sync_spacer(key, false);
12262            return;
12263        }
12264        let content = if horizontal {
12265            size_pt(content_len, cross)
12266        } else {
12267            size_pt(cross, content_len)
12268        };
12269        // Platforms clamp the offset to the content: grow the content
12270        // before scrolling, scroll before shrinking it.
12271        let old_len = self.nodes[key as usize]
12272            .scroll
12273            .as_ref()
12274            .and_then(|s| s.content)
12275            .map_or(0.0, |c| if horizontal { c.width.0 } else { c.height.0 });
12276        let list = self.nodes[key as usize].list.as_mut().expect("list");
12277        if anchor != 0.0 {
12278            list.issue_scroll_by(anchor);
12279        }
12280        for (offset, animated) in scrolls_to {
12281            list.issue_scroll_to(offset, animated);
12282        }
12283        let scroll_by = (anchor != 0.0).then(|| {
12284            let (dx, dy) = if horizontal {
12285                (Points(anchor), Points::ZERO)
12286            } else {
12287                (Points::ZERO, Points(anchor))
12288            };
12289            MountItem::ScrollBy { id, dx, dy }
12290        });
12291        // Platforms clamp the offset to the content and the viewport:
12292        // scroll before the viewport grows or the content shrinks, and
12293        // after the content grows (a shrinking viewport's frame comes
12294        // first anyway).
12295        let frame_at = grew
12296            .then(|| {
12297                self.mount
12298                    .iter()
12299                    .position(|m| matches!(m, MountItem::Frame { id: f, .. } if *f == id))
12300            })
12301            .flatten();
12302        match (scroll_by, frame_at) {
12303            // The viewport and the content both grow (rows arriving as a
12304            // placeholder beside the list goes away): the content first,
12305            // then the scroll, then the frame. A frame grown over the old
12306            // content clamps the scroll back to its start.
12307            (Some(item), Some(at)) if content_len > old_len => {
12308                self.set_scroll_content(key, content);
12309                match self
12310                    .mount
12311                    .iter()
12312                    .rposition(|m| matches!(m, MountItem::ScrollContent { id: c, .. } if *c == id))
12313                {
12314                    Some(queued) if queued > at => {
12315                        let grown = self.mount.remove(queued);
12316                        self.mount.insert(at, grown);
12317                        self.mount.insert(at + 1, item);
12318                    }
12319                    _ => self.mount.insert(at, item),
12320                }
12321            }
12322            (Some(item), Some(at)) => {
12323                self.mount.insert(at, item);
12324                self.set_scroll_content(key, content);
12325            }
12326            (Some(item), None) if content_len < old_len => {
12327                self.mount.push(item);
12328                self.set_scroll_content(key, content);
12329            }
12330            (item, _) => {
12331                self.set_scroll_content(key, content);
12332                self.mount.extend(item);
12333            }
12334        }
12335        if motion {
12336            self.move_list_cells(key, id, horizontal, anchor, placed);
12337        }
12338    }
12339}
12340
12341/// How far out of sight unbound list cells are moved.
12342const HIDDEN: f32 = 1.0e6;
12343
12344/// Where `x` is in `items`, looked for from both ends at once, and how
12345/// many items were looked at: few for an item near either end.
12346fn position_from_ends<T: PartialEq>(items: &[T], x: &T) -> Option<(usize, usize)> {
12347    let (mut front, mut back) = (0, items.len());
12348    while front < back {
12349        if items[front] == *x {
12350            return Some((front, 2 * front + 1));
12351        }
12352        back -= 1;
12353        if items[back] == *x {
12354            return Some((back, 2 * (items.len() - back)));
12355        }
12356        front += 1;
12357    }
12358    None
12359}
12360
12361/// Where `x` is in `items`, looked for outward from `near` (or the last
12362/// item, past the end), and how many items were looked at: few when it is
12363/// near.
12364fn position_near<T: PartialEq>(items: &[T], x: &T, near: usize) -> Option<(usize, usize)> {
12365    let near = near.min(items.len().checked_sub(1)?);
12366    let mut looked = 0;
12367    // Every item is at most `len - 1` from `near`.
12368    for distance in 0..items.len() {
12369        let below = near.checked_sub(distance);
12370        let above = (distance > 0)
12371            .then_some(near + distance)
12372            .filter(|&i| i < items.len());
12373        for i in [below, above].into_iter().flatten() {
12374            looked += 1;
12375            if items[i] == *x {
12376                return Some((i, looked));
12377            }
12378        }
12379    }
12380    None
12381}
12382
12383/// The content box (inside padding and border) of a laid-out node.
12384/// Taffy's rounding of a coordinate, to the nearest device pixel of
12385/// `ratio` pixels per point rather than to whole points: on a display whose
12386/// ratio is not a whole number (Android's 2.625) whole points fall between
12387/// pixels, so the platform rounding each view's frame to pixels in its parent
12388/// would make a child a pixel taller than its parent (a scroll view then cuts
12389/// its last row of pixels off).
12390fn round(value: f32, ratio: f32) -> f32 {
12391    (pixel(value, ratio) / f64::from(ratio)) as f32
12392}
12393
12394/// The device pixel [`round`] puts `value` on, counted from the root's
12395/// origin. `value` is an `f32` sum of offsets, a hair off the position it
12396/// stands for, and `/ ratio` is never exact at a fractional ratio: snapped
12397/// to a 64th of a pixel first, an edge on a half pixel (a 28 point row at
12398/// 2.625 is 73.5 pixels) always rounds the same way, wherever a scroll put
12399/// it, instead of taking one pixel or the next by that hair.
12400fn pixel(value: f32, ratio: f32) -> f64 {
12401    (snapped(value, ratio) + 0.5).floor()
12402}
12403
12404/// `value` in device pixels, snapped to a 64th of a pixel ([`pixel`]).
12405fn snapped(value: f32, ratio: f32) -> f64 {
12406    let p = f64::from(value) * f64::from(ratio);
12407    (p * 64.0).round() / 64.0
12408}
12409
12410/// The device pixels the edges of a box from `start`, `len` long, are on:
12411/// each edge's [`pixel`], but for a box under a pixel thick whose edges
12412/// both round to one pixel. It would take none (half a point at one pixel
12413/// per point vanished wherever it ended on a half pixel), and takes the
12414/// pixel on the side of that edge most of it is on instead: a rule against
12415/// its parent's edge stays inside the parent, and no other box's edge
12416/// moves, so neighbours still meet (the rule covers a pixel of one). A
12417/// length under a 64th of a pixel (zero but for `f32`) still takes none.
12418fn edges(start: f32, len: f32, ratio: f32) -> (f64, f64) {
12419    let end = start + len;
12420    let (from, to) = (pixel(start, ratio), pixel(end, ratio));
12421    let (a, b) = (snapped(start, ratio), snapped(end, ratio));
12422    if from != to || b <= a {
12423        (from, to)
12424    } else if a + b < 2.0 * from {
12425        (from - 1.0, from)
12426    } else {
12427        (from, from + 1.0)
12428    }
12429}
12430
12431/// Where the box a node is placed in (the view around it, or its
12432/// containing block) is in its layout root: unrounded, as Taffy's rounding
12433/// carries it down ([`Core::layout_origin`]), and whether [`edges`] put a
12434/// leading edge on the pixel before the one that position rounds to (a box
12435/// under a pixel thick mostly before it). A node's frame is from those
12436/// edges, so the children of such a box are on it.
12437#[derive(Clone, Copy, Debug, Default, PartialEq)]
12438struct Origin {
12439    at: taffy::Point<f32>,
12440    back: taffy::Point<bool>,
12441}
12442
12443impl Origin {
12444    /// The box at `at`, `size` large, rounded to `ratio`.
12445    fn of(at: taffy::Point<f32>, size: taffy::Size<f32>, ratio: taffy::Size<f32>) -> Origin {
12446        let back =
12447            |start: f32, len: f32, ratio: f32| edges(start, len, ratio).0 < pixel(start, ratio);
12448        Origin {
12449            at,
12450            back: taffy::Point {
12451                x: back(at.x, size.width, ratio.width),
12452                y: back(at.y, size.height, ratio.height),
12453            },
12454        }
12455    }
12456
12457    /// The device pixels its leading edges are on.
12458    fn lead(self, ratio: taffy::Size<f32>) -> taffy::Point<f64> {
12459        taffy::Point {
12460            x: pixel(self.at.x, ratio.width) - f64::from(u8::from(self.back.x)),
12461            y: pixel(self.at.y, ratio.height) - f64::from(u8::from(self.back.y)),
12462        }
12463    }
12464
12465    /// The offset in points from its leading edges to `to`'s, from the
12466    /// whole pixels between them ([`span`]).
12467    fn to(self, to: Origin, ratio: taffy::Size<f32>) -> taffy::Point<f32> {
12468        let (from, to) = (self.lead(ratio), to.lead(ratio));
12469        taffy::Point {
12470            x: ((to.x - from.x) / f64::from(ratio.width)) as f32,
12471            y: ((to.y - from.y) / f64::from(ratio.height)) as f32,
12472        }
12473    }
12474}
12475
12476/// The distance in points from `from` to `to`, each rounded to a device
12477/// pixel ([`round`]): computed from the whole pixels between them, so the
12478/// same pixels give the same `f32` wherever they are. The difference of two
12479/// rounded points (`round(to) - round(from)`) would differ in its last bits
12480/// as a scroll moves the edges, and every frame in a scrolled region would
12481/// be sent again unchanged.
12482fn span(from: f32, to: f32, ratio: f32) -> f32 {
12483    ((pixel(to, ratio) - pixel(from, ratio)) / f64::from(ratio)) as f32
12484}
12485
12486/// The width a text block is typeset in: the width Taffy measured its lines
12487/// in (`measured`, its unrounded content box), when its box rounded to
12488/// device pixels (`rounded`) is within a pixel of it. A box whose edges fall
12489/// between pixels can round a pixel narrower than the text was measured in
12490/// (a list item's content 21 points in, 57.75 pixels at 2.75): typeset in
12491/// that, a line that fit by less than the pixel wrapped once more than its
12492/// box was made tall for, and its last line ran over the block after it (a
12493/// browser) or was cut (a platform that clips text to its view). Typeset in
12494/// the width it was measured in, the lines are the ones its height has; the
12495/// text reaches less than a pixel past its rounded box.
12496fn typeset_width(rounded: Points, measured: Points, ratio: f32) -> Points {
12497    if measured.0.is_finite() && ((measured.0 - rounded.0) * ratio).abs() < 1.0 {
12498        measured
12499    } else {
12500        rounded
12501    }
12502}
12503
12504/// `value` rounded up to a device pixel of `ratio` pixels per point. A
12505/// value that is a whole pixel but for `f32` (`56.0 / 2.625 * 2.625` is
12506/// `56.000004`) stays that pixel; a value really over one gets the next
12507/// pixel even when it is over by less than the tolerance: a text measured
12508/// `78.000_49` points wide (a PingFang glyph's 1020 / 1028 em beside SF's
12509/// 1/128 point advances) wraps in a box of 78.
12510fn ceil_to_pixel(value: Points, ratio: f32) -> Points {
12511    let up = (value.0 * ratio - 1.0e-3).ceil().max(0.0) / ratio;
12512    Points(if up < value.0 { up + 1.0 / ratio } else { up })
12513}
12514
12515/// A scroll view's scrollable extent from its rounded layout. The overflow
12516/// rectangle is CSS's scrollable overflow, measured from the padding box
12517/// origin: a scroll container's in-flow content reaches its trailing
12518/// padding there (an empty one is its padding), and an absolutely
12519/// positioned child its own box, so only the leading border is added. The
12520/// cross axis keeps the viewport's length, which the content spans (a
12521/// vertical scroll view's width, a horizontal one's height). The main axis
12522/// is the content's own extent, below the viewport too: a platform adds its
12523/// own insets around the viewport (iOS's bars under a large title), and a
12524/// floor there gives it a range to scroll over content that fits.
12525fn scroll_extent(l: &taffy::Layout, horizontal: bool) -> Size<Points> {
12526    let o = l.scrollable_overflow_rect;
12527    let (width, height) = (l.border.left + o.right(), l.border.top + o.bottom());
12528    if horizontal {
12529        size_pt(width, height.max(l.size.height))
12530    } else {
12531        size_pt(width.max(l.size.width), height)
12532    }
12533}
12534
12535/// `layout` rounded as Taffy's rounding pass (`taffy::round_layout`) rounds
12536/// it, to device pixels of `ratio` pixels per point on each axis
12537/// ([`round`]; on a grid surface a Cell is a pixel: [`terminal_layout::Grid::ratio`]),
12538/// `origin` being the node around it in its layout root (its containing
12539/// block): edges are rounded where they are in the root, so adjacent
12540/// views stay adjacent, and a box under a pixel thick keeps one ([`edges`]).
12541/// The location is from the leading edges of the box around it as they
12542/// were rounded. The core rounds itself: Taffy's pass reaches the
12543/// absolutely positioned nodes through their containing block's list,
12544/// which it can leave holding removed nodes (a panic) or never fill (a
12545/// hidden subtree's), while here every node is reached through its parent,
12546/// its logical parent; out-of-flow offsets use their Taffy containing block.
12547fn rounded(layout: &taffy::Layout, origin: Origin, ratio: taffy::Size<f32>) -> taffy::Layout {
12548    let mut out = *layout;
12549    let (x, y) = (
12550        origin.at.x + layout.location.x,
12551        origin.at.y + layout.location.y,
12552    );
12553    let (rx, ry) = (ratio.width, ratio.height);
12554    let (x0, x1) = edges(x, layout.size.width, rx);
12555    let (y0, y1) = edges(y, layout.size.height, ry);
12556    let lead = origin.lead(ratio);
12557    let points = |pixels: f64, ratio: f32| (pixels / f64::from(ratio)) as f32;
12558    out.location.x = points(x0 - lead.x, rx);
12559    out.location.y = points(y0 - lead.y, ry);
12560    out.size.width = points(x1 - x0, rx);
12561    out.size.height = points(y1 - y0, ry);
12562    out.scrollbar_size.width = round(layout.scrollbar_size.width, rx);
12563    out.scrollbar_size.height = round(layout.scrollbar_size.height, ry);
12564    out.border.left = span(x, x + layout.border.left, rx);
12565    out.border.right = span(
12566        x + layout.size.width - layout.border.right,
12567        x + layout.size.width,
12568        rx,
12569    );
12570    out.border.top = span(y, y + layout.border.top, ry);
12571    out.border.bottom = span(
12572        y + layout.size.height - layout.border.bottom,
12573        y + layout.size.height,
12574        ry,
12575    );
12576    // Padding is rounded from the border's inner edge, not from the outer
12577    // edge as the border is: rounded each from the outer edge, a border and
12578    // a padding of 1.5 and 6 points at 1.1 pixels per point took 2 + 7
12579    // pixels where their 8.25 pixels round to 8, and a text measured to fit
12580    // its content box (a label as wide as its content) wrapped in the pixel
12581    // or two its insets took from it. Rounded at its edges, the content box
12582    // is as many pixels as the text was measured.
12583    let (left, right) = (
12584        x + layout.border.left,
12585        x + layout.size.width - layout.border.right,
12586    );
12587    let (top, bottom) = (
12588        y + layout.border.top,
12589        y + layout.size.height - layout.border.bottom,
12590    );
12591    out.padding.left = span(left, left + layout.padding.left, rx);
12592    out.padding.right = span(right - layout.padding.right, right, rx);
12593    out.padding.top = span(top, top + layout.padding.top, ry);
12594    out.padding.bottom = span(bottom - layout.padding.bottom, bottom, ry);
12595    let o = layout.scrollable_overflow_rect;
12596    // Taffy packs the scroll-origin directions into the rectangle's signs;
12597    // keep them, and keep the origin inside the rounded rectangle.
12598    out.scrollable_overflow_rect = taffy::ScrollableOverflow::new(
12599        taffy::Rect {
12600            left: points(pixel(x + o.left(), rx) - x0, rx).min(0.0),
12601            right: points(pixel(x + o.right(), rx) - x0, rx).max(0.0),
12602            top: points(pixel(y + o.top(), ry) - y0, ry).min(0.0),
12603            bottom: points(pixel(y + o.bottom(), ry) - y0, ry).max(0.0),
12604        },
12605        o.is_reversed(),
12606    );
12607    out
12608}
12609
12610fn content_box(l: &taffy::Layout) -> Bounds<Points> {
12611    rect(
12612        l.padding.left + l.border.left,
12613        l.padding.top + l.border.top,
12614        (l.size.width - l.padding.left - l.padding.right - l.border.left - l.border.right).max(0.0),
12615        (l.size.height - l.padding.top - l.padding.bottom - l.border.top - l.border.bottom)
12616            .max(0.0),
12617    )
12618}
12619
12620/// An image's minimum and maximum content-box sizes ([`image_size`]).
12621#[derive(Default)]
12622struct ImageLimits {
12623    min: taffy::Size<Option<f32>>,
12624    max: taffy::Size<Option<f32>>,
12625}
12626
12627impl ImageLimits {
12628    fn width(&self, w: f32) -> f32 {
12629        clamp_side(w, self.min.width, self.max.width)
12630    }
12631
12632    fn height(&self, h: f32) -> f32 {
12633        clamp_side(h, self.min.height, self.max.height)
12634    }
12635}
12636
12637fn clamp_side(v: f32, min: Option<f32>, max: Option<f32>) -> f32 {
12638    let v = max.map_or(v, |max| v.min(max));
12639    min.map_or(v, |min| v.max(min))
12640}
12641
12642/// Size of an image with a known natural size: fill a known dimension and
12643/// keep the aspect ratio for the other, within `limits`.
12644fn image_size(
12645    natural: Size<Points>,
12646    w: Option<f32>,
12647    h: Option<f32>,
12648    limits: &ImageLimits,
12649) -> taffy::Size<f32> {
12650    let ratio = if natural.height > Points::ZERO {
12651        natural.width / natural.height
12652    } else {
12653        1.0
12654    };
12655    let (width, height) = match (w, h) {
12656        (Some(w), None) => (w, limits.height(w / ratio)),
12657        (None, Some(h)) => (limits.width(h * ratio), h),
12658        (Some(w), Some(h)) => (w, h),
12659        (None, None) => {
12660            let width = limits.width(natural.width.0);
12661            let height = width / ratio;
12662            let clamped = limits.height(height);
12663            if clamped == height {
12664                (width, height)
12665            } else {
12666                (limits.width(clamped * ratio), clamped)
12667            }
12668        }
12669    };
12670    taffy::Size { width, height }
12671}
12672
12673/// Measures a text block: per-node cache, then the shared content-addressed
12674/// cache, then the platform engine.
12675/// Keeps a Rust component's text block's final layout for its
12676/// [`crate::Text::on_text_layout`] listener, which hears it with the
12677/// block's `TextLayout` event ([`Core::component_event`]). Only the core's
12678/// nodes (odd ids, the components'): JS hears the lines.
12679fn keep_geometry(
12680    engine: &Option<Rc<dyn crate::text::GeometryEngine>>,
12681    geometries: &mut rustc_hash::FxHashMap<NodeId, crate::text::TextGeometry>,
12682    id: NodeId,
12683    layout: &TextLayout,
12684    text: &Arc<AttributedText>,
12685    spacers: &[u32],
12686) {
12687    if let Some(engine) = engine.as_ref().filter(|_| id % 2 == 1) {
12688        geometries.insert(
12689            id,
12690            crate::text::TextGeometry::new(engine.clone(), layout.clone(), text.clone(), spacers),
12691        );
12692    }
12693}
12694
12695/// The lines of `layout` with their characters.
12696/// How many lines of a wrapping text fit a box `height` tall when its
12697/// lines are taller: `None` when they all fit, the text does not wrap, or
12698/// its `numberOfLines` already keeps fewer. At least one line shows (cut).
12699fn lines_in_box<M: TextEngine>(
12700    engine: &M,
12701    cache: &mut MeasureCache,
12702    cx: &mut TextContext<M::Prepared>,
12703    width: Points,
12704    height: Points,
12705) -> Option<u32> {
12706    // Half a point of slack: rounding of the box to device pixels.
12707    const SLACK: f32 = 0.5;
12708    if cx.text.no_wrap || cx.text.text.is_empty() {
12709        return None;
12710    }
12711    let measured = measure_text(engine, cache, cx, Some(width.0));
12712    if measured.height.0 <= height.0 + SLACK {
12713        return None;
12714    }
12715    let prepared = cx
12716        .prepared
12717        .get_or_insert_with(|| engine.prepare_with(&cx.text, &cx.alignments, &cx.options));
12718    let layout = engine.layout(prepared, Size::new(width, measured.height));
12719    let lines = engine.lines(&layout);
12720    let (fit, total) = match lines.as_slice() {
12721        [] => return None,
12722        // An engine reporting the block as one line (the estimating
12723        // one): lines as tall as it says, one under the other.
12724        [line] if line.height > Points::ZERO => (
12725            ((height.0 + SLACK) / line.height.0).floor() as u32,
12726            (measured.height.0 / line.height.0).round() as u32,
12727        ),
12728        [_] => return None,
12729        lines => (
12730            lines
12731                .iter()
12732                .take_while(|l| (l.y + l.height).0 <= height.0 + SLACK)
12733                .count() as u32,
12734            lines.len() as u32,
12735        ),
12736    };
12737    let fit = fit.max(1);
12738    let limit = cx.text.max_lines;
12739    (fit < total && (limit == 0 || fit < limit)).then_some(fit)
12740}
12741
12742fn text_lines<M: TextEngine>(
12743    engine: &M,
12744    text: &AttributedText,
12745    layout: &TextLayout,
12746) -> EventPayload {
12747    let units: Vec<u16> = text.text.encode_utf16().collect();
12748    let mut lines = engine.lines(layout);
12749    for line in &mut lines {
12750        let (start, end) = (line.start as usize, (line.end as usize).min(units.len()));
12751        if start < end {
12752            line.text = String::from_utf16_lossy(&units[start..end]);
12753        }
12754    }
12755    EventPayload::TextLayout(lines)
12756}
12757
12758/// `text` with its fonts scaled down (to at least `min`) until it fits
12759/// `size` within its line limit: the largest scale that fits, by
12760/// bisection.
12761fn fitted<M: TextEngine>(
12762    engine: &M,
12763    text: &AttributedText,
12764    alignments: &crate::AttachmentAlignments,
12765    options: &crate::TextOptions,
12766    size: Size<Points>,
12767    min: f32,
12768) -> AttributedText {
12769    let scaled = |scale: f32| {
12770        let mut t = text.clone();
12771        if let Some(strut) = &mut t.paragraph_strut {
12772            strut.font_size *= scale;
12773            strut.line_height *= scale;
12774        }
12775        for span in &mut t.spans {
12776            span.style.font_size *= scale;
12777            span.style.line_height *= scale;
12778            span.style.letter_spacing *= scale;
12779        }
12780        t
12781    };
12782    let fits = |t: &AttributedText| {
12783        // Untruncated, the text must be no taller than its truncated self
12784        // (nothing cut) and than the box.
12785        let all = AttributedText {
12786            max_lines: 0,
12787            ..t.clone()
12788        };
12789        let full = engine.measure(
12790            &engine.prepare_with(&all, alignments, options),
12791            Some(size.width),
12792        );
12793        let limited = if t.max_lines > 0 {
12794            engine
12795                .measure(
12796                    &engine.prepare_with(t, alignments, options),
12797                    Some(size.width),
12798                )
12799                .height
12800        } else {
12801            Points(f32::INFINITY)
12802        };
12803        full.height <= size.height.min(limited) + Points(0.5)
12804            && full.width <= size.width + Points(0.5)
12805    };
12806    if fits(text) {
12807        return text.clone();
12808    }
12809    let (mut lo, mut hi) = (min, 1.0f32);
12810    if !fits(&scaled(lo)) {
12811        return scaled(lo);
12812    }
12813    for _ in 0..7 {
12814        let mid = (lo + hi) / 2.0;
12815        if fits(&scaled(mid)) {
12816            lo = mid;
12817        } else {
12818            hi = mid;
12819        }
12820    }
12821    scaled(lo)
12822}
12823
12824/// Min-content keeps every unbreakable segment intact. Measure the styled
12825/// segments with the platform engine rather than estimating glyph advances.
12826/// The size a text far from the screen is laid out at until it is
12827/// measured (`cull.rs`): its characters at an average advance of its
12828/// largest font, broken into lines at `max_width`, each line as high as
12829/// its line height.
12830fn estimate_text(text: &AttributedText, max_width: Option<f32>) -> Size<Points> {
12831    let (_, line) = text_metrics(text);
12832    let mut width = 0.0f32;
12833    let mut lines = 0u32;
12834    for paragraph in text.text.split('\n') {
12835        let w = estimate_line(text, paragraph).0;
12836        width = width.max(match max_width {
12837            Some(max) => w.min(max),
12838            None => w,
12839        });
12840        lines += match max_width {
12841            Some(max) if max > 0.0 && !text.no_wrap => (w / max).ceil().max(1.0) as u32,
12842            _ => 1,
12843        };
12844    }
12845    if text.max_lines > 0 {
12846        lines = lines.min(text.max_lines);
12847    }
12848    Size::new(Points(width.ceil()), Points((lines as f32 * line).ceil()))
12849}
12850
12851/// The estimated advance of `run`, in `text`'s largest font: wide
12852/// characters (CJK, emoji) a font size each, others a little over half.
12853fn estimate_line(text: &AttributedText, run: &str) -> Points {
12854    let (size, _) = text_metrics(text);
12855    Points(
12856        run.chars()
12857            .map(|c| {
12858                if c as u32 >= 0x2e80 {
12859                    size
12860                } else {
12861                    size * 0.55
12862                }
12863            })
12864            .sum(),
12865    )
12866}
12867
12868/// `text`'s largest font size and the line height it gives (the style's,
12869/// or 1.2 of the font size).
12870fn text_metrics(text: &AttributedText) -> (f32, f32) {
12871    let (font, line) = text.approx_metrics();
12872    (font.0, line.0)
12873}
12874
12875fn min_content_width<M: TextEngine>(
12876    engine: &M,
12877    cache: &mut MeasureCache,
12878    cx: &mut TextContext<M::Prepared>,
12879) -> Points {
12880    if let Some(width) = cx.min_content {
12881        return width;
12882    }
12883    if cx.deferred {
12884        // Its longest word, estimated (not kept: measured once it is made).
12885        return cx
12886            .text
12887            .text
12888            .split_whitespace()
12889            .map(|word| estimate_line(&cx.text, word))
12890            .fold(Points::ZERO, Points::max);
12891    }
12892    let text = &cx.text;
12893    let mut offsets = Vec::with_capacity(text.text.chars().count() + 1);
12894    let mut utf16 = 0u32;
12895    for (byte, ch) in text.text.char_indices() {
12896        offsets.push((utf16, byte));
12897        utf16 += ch.len_utf16() as u32;
12898    }
12899    offsets.push((utf16, text.text.len()));
12900    let byte_at = |offset: u32| {
12901        offsets[offsets
12902            .binary_search_by_key(&offset, |&(at, _)| at)
12903            .unwrap()]
12904        .1
12905    };
12906    let mut start = 0usize;
12907    let mut width = Points::ZERO;
12908    for (end, _) in unicode_linebreak::linebreaks(&text.text) {
12909        let word = text.text[start..end].trim_end_matches([' ', '\t', '\n', '\r', '\u{000c}']);
12910        let from = offsets[offsets
12911            .binary_search_by_key(&start, |&(_, byte)| byte)
12912            .unwrap()]
12913        .0;
12914        let to = from + word.encode_utf16().count() as u32;
12915        if from < to {
12916            let mut part = AttributedText {
12917                no_wrap: true,
12918                rtl: text.rtl,
12919                writing_direction: text.writing_direction,
12920                ..Default::default()
12921            };
12922            for span in &text.spans {
12923                let (lo, hi) = (from.max(span.start), to.min(span.end));
12924                if lo < hi {
12925                    part.push(&text.text[byte_at(lo)..byte_at(hi)], span.style);
12926                }
12927            }
12928            for attachment in &text.attachments {
12929                if (from..to).contains(&attachment.index) {
12930                    let mut attachment = *attachment;
12931                    attachment.index -= from;
12932                    part.attachments.push(attachment);
12933                }
12934            }
12935            let hash = part.layout_hash();
12936            let measured = cache.get(hash, None).unwrap_or_else(|| {
12937                let measured = engine.measure(&engine.prepare(&part), None);
12938                cache.insert(hash, None, measured);
12939                measured
12940            });
12941            width = width.max(measured.width);
12942        }
12943        start = end;
12944    }
12945    cx.min_content = Some(width);
12946    width
12947}
12948
12949/// What measures the leaves in every layout pass ([`measure_leaf`]): one
12950/// closure type for all of them, so Taffy's algorithms, generic over it,
12951/// are made once.
12952fn leaf_measure<'a, M: TextEngine>(
12953    engine: &'a M,
12954    cache: &'a mut MeasureCache,
12955) -> impl FnMut(
12956    taffy::LayoutInput,
12957    LayoutId,
12958    Option<&mut LeafContext<M::Prepared>>,
12959    &taffy::Style,
12960    layout_tree::Aligned,
12961) -> taffy::LayoutOutput
12962+ 'a {
12963    move |input, _, cx, style, aligned| measure_leaf(engine, cache, input, cx, style, aligned)
12964}
12965
12966/// A leaf's layout (`taffy::compute_leaf_layout`): Taffy resolves its
12967/// style's sizes, padding, border, minimums, maximums and aspect ratio;
12968/// only its content (a text, an image's natural size, a native
12969/// component's own size) is measured here. A text aligned by baseline gives
12970/// its first line's baseline too ([`text_baseline`]): Taffy aligns a flex
12971/// row's items by baseline (`align-items: baseline`) with it, and by their
12972/// bottom edges without it.
12973fn measure_leaf<M: TextEngine>(
12974    engine: &M,
12975    cache: &mut MeasureCache,
12976    input: taffy::LayoutInput,
12977    mut cx: Option<&mut LeafContext<M::Prepared>>,
12978    style: &taffy::Style,
12979    aligned: layout_tree::Aligned,
12980) -> taffy::LayoutOutput {
12981    let mut output = measure_leaf_size(engine, cache, input, cx.as_deref_mut(), style);
12982    // Taffy asks for baselines by laying the items out (its baseline pass),
12983    // so measuring alone typesets nothing more.
12984    if aligned == layout_tree::Aligned::Baseline
12985        && input.run_mode == taffy::RunMode::PerformLayout
12986        && let Some(LeafContext::Text(cx)) = cx
12987    {
12988        use taffy::util::ResolveOrZero;
12989        let resolve = |_: taffy::CalcHandle, _: f32| 0.0;
12990        let padding = style
12991            .padding
12992            .resolve_or_zero(input.parent_size.width, resolve);
12993        let border = style
12994            .border
12995            .resolve_or_zero(input.parent_size.width, resolve);
12996        let width = output.size.width - padding.left - padding.right - border.left - border.right;
12997        if let Some(baseline) = text_baseline(engine, cx, width.max(0.0)) {
12998            output.baselines.first = Some(padding.top + border.top + baseline.0);
12999        }
13000    }
13001    output
13002}
13003
13004/// How far below the top of `cx`'s text its first line's baseline is, laid
13005/// out `width` wide ([`TextEngine::first_baseline`]); none for a text
13006/// measured by an estimate (`cull.rs`), which is not typeset.
13007fn text_baseline<M: TextEngine>(
13008    engine: &M,
13009    cx: &mut TextContext<M::Prepared>,
13010    width: f32,
13011) -> Option<Points> {
13012    if cx.deferred {
13013        return None;
13014    }
13015    if let Some((w, baseline)) = cx.baseline
13016        && w == width
13017    {
13018        return baseline;
13019    }
13020    let prepared = cx
13021        .prepared
13022        .get_or_insert_with(|| engine.prepare_with(&cx.text, &cx.alignments, &cx.options));
13023    let baseline = engine.first_baseline(prepared, Points(width));
13024    cx.baseline = Some((width, baseline));
13025    baseline
13026}
13027
13028/// A leaf's size ([`measure_leaf`]).
13029fn measure_leaf_size<M: TextEngine>(
13030    engine: &M,
13031    cache: &mut MeasureCache,
13032    input: taffy::LayoutInput,
13033    cx: Option<&mut LeafContext<M::Prepared>>,
13034    style: &taffy::Style,
13035) -> taffy::LayoutOutput {
13036    use taffy::{MaybeResolve as _, ResolveOrZero as _};
13037    // An input's text scrolls within its maximum height: its content is
13038    // never taller than its content box can be. Taffy leaves the maximum out
13039    // of the content size it asks for a flex basis (`SizingMode::ContentSize`)
13040    // and a column container sizes itself from the flex bases, so without
13041    // this a long value grew the input's parent past the input.
13042    let input_max_height = match &cx {
13043        Some(LeafContext::Text(cx)) if cx.field.is_some() => {
13044            let parent = input.parent_size;
13045            let max: Option<f32> = style
13046                .max_size
13047                .height
13048                .maybe_resolve(parent.height, |_, _| 0.0);
13049            max.map(|max| {
13050                let inset = (style.padding.resolve_or_zero(parent.width, |_, _| 0.0)
13051                    + style.border.resolve_or_zero(parent.width, |_, _| 0.0))
13052                .vertical_axis_sum();
13053                match style.box_sizing {
13054                    taffy::BoxSizing::BorderBox => (max - inset).max(0.0),
13055                    taffy::BoxSizing::ContentBox => max,
13056                }
13057            })
13058        }
13059        _ => None,
13060    };
13061    // Taffy hands a size it asks for (`RunMode::ComputeSize`) the known
13062    // sizes of the border box, as a stretched item's width is, and the
13063    // available space of the content box. What is measured fits the
13064    // content box: a text measured as wide as its border box wraps fewer
13065    // lines than it is laid out in, and the platforms cut the rest.
13066    let inset = {
13067        let parent = input.parent_size.width;
13068        let mut inset = (style.padding.resolve_or_zero(parent, |_, _| 0.0)
13069            + style.border.resolve_or_zero(parent, |_, _| 0.0))
13070        .sum_axes();
13071        // Scroll bars' gutters, as Taffy reserves them.
13072        if style.overflow.y == taffy::Overflow::Scroll {
13073            inset.width += style.scrollbar_width;
13074        }
13075        if style.overflow.x == taffy::Overflow::Scroll {
13076            inset.height += style.scrollbar_width;
13077        }
13078        inset
13079    };
13080    let image = matches!(cx, Some(LeafContext::Image(_)));
13081    // An image with a natural size keeps its aspect ratio within its
13082    // minimum and maximum sizes, as CSS's replaced elements do: a 60 × 30
13083    // image with a 40 point maximum width is 40 × 20, not 40 × 30. Taffy
13084    // clamps the measured size afterwards, one axis at a time.
13085    let image_limits = match &cx {
13086        Some(LeafContext::Image(Some(_))) => {
13087            let parent = input.parent_size;
13088            let content = |v: Option<f32>, inset: f32| {
13089                v.map(|v| match style.box_sizing {
13090                    taffy::BoxSizing::BorderBox => (v - inset).max(0.0),
13091                    taffy::BoxSizing::ContentBox => v,
13092                })
13093            };
13094            let inset = (style.padding.resolve_or_zero(parent.width, |_, _| 0.0)
13095                + style.border.resolve_or_zero(parent.width, |_, _| 0.0))
13096            .sum_axes();
13097            let min: taffy::Size<Option<f32>> = style.min_size.maybe_resolve(parent, |_, _| 0.0);
13098            let max: taffy::Size<Option<f32>> = style.max_size.maybe_resolve(parent, |_, _| 0.0);
13099            ImageLimits {
13100                min: taffy::Size {
13101                    width: content(min.width, inset.width),
13102                    height: content(min.height, inset.height),
13103                },
13104                max: taffy::Size {
13105                    width: content(max.width, inset.width),
13106                    height: content(max.height, inset.height),
13107                },
13108            }
13109        }
13110        _ => ImageLimits::default(),
13111    };
13112    let mut output = taffy::compute_leaf_layout(
13113        input,
13114        style,
13115        |_, _| 0.0,
13116        |known, available| {
13117            let known = taffy::Size {
13118                width: known.width.map(|w| (w - inset.width).max(0.0)),
13119                height: known.height.map(|h| (h - inset.height).max(0.0)),
13120            };
13121            // The space Taffy offers the content box is the space around
13122            // the box less its padding and border, negative where that
13123            // space is narrower than they are (a column squeezed while it
13124            // resizes). The content then has no room, as with a known
13125            // size: an input measured as wide as that negative space gave
13126            // Taffy a negative overflow, which its debug assertions reject.
13127            let available = taffy::Size {
13128                width: available.width.map_definite_value(|w| w.max(0.0)),
13129                height: available.height.map_definite_value(|h| h.max(0.0)),
13130            };
13131            if let Some(LeafContext::Image(Some(natural))) = cx {
13132                return image_size(*natural, known.width, known.height, &image_limits);
13133            }
13134            measure_content(engine, cache, cx, known, available, input_max_height)
13135        },
13136    );
13137    // An image is drawn inside its box whatever its fit (CSS's replaced
13138    // elements have no scrollable overflow). Taffy lays a leaf out without
13139    // the sizes its style gives it (`RunMode::PerformLayout`), so what was
13140    // measured is the natural size: a 24 point icon in a 14 point box
13141    // would give the scroll view around it 10 points to scroll.
13142    if image {
13143        let o = output.scrollable_overflow_rect;
13144        let mut rect = o.rect();
13145        rect.right = rect.right.min(output.size.width);
13146        rect.bottom = rect.bottom.min(output.size.height);
13147        output.scrollable_overflow_rect = taffy::ScrollableOverflow::new(rect, o.is_reversed());
13148    }
13149    output
13150}
13151
13152/// The size of a leaf's content: `known` and `available` are its content
13153/// box's ([`measure_leaf_size`]).
13154fn measure_content<M: TextEngine>(
13155    engine: &M,
13156    cache: &mut MeasureCache,
13157    cx: Option<&mut LeafContext<M::Prepared>>,
13158    known: taffy::Size<Option<f32>>,
13159    available: taffy::Size<AvailableSpace>,
13160    input_max_height: Option<f32>,
13161) -> taffy::Size<f32> {
13162    match cx {
13163        Some(LeafContext::Text(cx)) => {
13164            // An input's text scrolls in it (or wraps at its width):
13165            // the input's width does not come from the text.
13166            let field = cx
13167                .field
13168                .as_deref_mut()
13169                .map(|field| measure_text(engine, cache, field, None));
13170            let field_width = field.map(|size| size.width.0);
13171            let max_width = if cx.text.no_wrap {
13172                None
13173            } else {
13174                known.width.or(match (available.width, field_width) {
13175                    (AvailableSpace::Definite(w), Some(field)) => Some(field.min(w)),
13176                    (AvailableSpace::Definite(w), None) => Some(w),
13177                    (_, Some(field)) => Some(field),
13178                    (AvailableSpace::MinContent, None) => {
13179                        Some(min_content_width(engine, cache, cx).0)
13180                    }
13181                    (AvailableSpace::MaxContent, None) => None,
13182                })
13183            };
13184            let width = known.width.or(field_width.and(max_width));
13185            // A single-line input uses the field sample's width. When its font
13186            // determines the line height too, shaping the edited value would
13187            // change neither dimension.
13188            let measured = match field {
13189                Some(sample)
13190                    if width.is_some()
13191                        && cx.text.max_lines == 1
13192                        && engine.uniform_input_line_height() =>
13193                {
13194                    sample
13195                }
13196                _ => measure_text(engine, cache, cx, max_width),
13197            };
13198            taffy::Size {
13199                width: width.unwrap_or(measured.width.0),
13200                height: known.height.unwrap_or(match input_max_height {
13201                    Some(max) => measured.height.0.min(max),
13202                    None => measured.height.0,
13203                }),
13204            }
13205        }
13206        Some(LeafContext::Image(Some(natural))) => {
13207            image_size(*natural, known.width, known.height, &ImageLimits::default())
13208        }
13209        Some(LeafContext::Native(Some(own))) => taffy::Size {
13210            width: known.width.unwrap_or(own.width.0),
13211            height: known.height.unwrap_or(own.height.0),
13212        },
13213        _ => taffy::Size::ZERO,
13214    }
13215}
13216
13217fn measure_text<M: TextEngine>(
13218    engine: &M,
13219    cache: &mut MeasureCache,
13220    cx: &mut TextContext<M::Prepared>,
13221    max_width: Option<f32>,
13222) -> Size<Points> {
13223    if let Some((w, size)) = cx.cache
13224        && w == max_width
13225    {
13226        return size;
13227    }
13228    let typed = max_width.map(Points);
13229    // Far from the screen with no view: estimated, unless the size is
13230    // known (`cull.rs`).
13231    if cx.deferred {
13232        let size = cache.get(cx.layout_hash, typed).unwrap_or_else(|| {
13233            cx.estimated = true;
13234            estimate_text(&cx.text, max_width)
13235        });
13236        cx.cache = Some((max_width, size));
13237        return size;
13238    }
13239    if let (Some(width), Some(same)) = (max_width, cx.same_lines)
13240        && (same.narrowest..=same.widest).contains(&width)
13241    {
13242        cx.cache = Some((max_width, same.size));
13243        return same.size;
13244    }
13245    // A limit on lines cuts the last one to the width.
13246    let greedy = engine.breaks_lines_greedily() && cx.text.max_lines == 0;
13247    let size = match cache.get(cx.layout_hash, typed) {
13248        Some(size) => size,
13249        None => {
13250            // Far from the screen during a resize: it keeps its height for
13251            // now ([`Core::set_resizing`]).
13252            if let (Some(commit), Some((_, last))) = (cache.resizing, cx.cache)
13253                && cx.near_screen != commit
13254            {
13255                cx.held = true;
13256                return Size::new(
13257                    max_width.map_or(last.width, |w| last.width.min(Points(w))),
13258                    last.height,
13259                );
13260            }
13261            let prepared = cx
13262                .prepared
13263                .get_or_insert_with(|| engine.prepare_with(&cx.text, &cx.alignments, &cx.options));
13264            // Round up so rendering never truncates the last glyph, to a
13265            // device pixel: to a whole point the box grows past the text by
13266            // up to a point, all of it below the last line.
13267            let ratio = cache.pixel_ratio();
13268            let on_pixels = |size: Size<Points>| {
13269                cache
13270                    .on_cells(size)
13271                    .unwrap_or_else(|| size.map(|v| ceil_to_pixel(v, ratio)))
13272            };
13273            // Growing: measured a little wider, the next widths are known
13274            // too, unless a line takes another word by then.
13275            let ahead = max_width.filter(|width| {
13276                greedy && !cx.no_ahead && cx.same_lines.is_some_and(|same| *width > same.widest)
13277            });
13278            let ahead = ahead.and_then(|width| {
13279                let wider = Points(width + SAME_LINES_AHEAD);
13280                let size = on_pixels(engine.measure(prepared, Some(wider)));
13281                cx.no_ahead = size.width.0 > width;
13282                (size.width.0 <= width).then_some((wider.0, size))
13283            });
13284            let (measured, size) = match ahead {
13285                Some(found) => found,
13286                None => (
13287                    max_width.unwrap_or(f32::INFINITY),
13288                    on_pixels(engine.measure(prepared, typed)),
13289                ),
13290            };
13291            cache.insert(cx.layout_hash, typed, size);
13292            if greedy && size.width.0 <= measured {
13293                cx.same_lines = Some(SameLines {
13294                    narrowest: size.width.0,
13295                    widest: measured,
13296                    size,
13297                });
13298            }
13299            size
13300        }
13301    };
13302    cx.cache = Some((max_width, size));
13303    size
13304}
13305
13306/// Whether `laid`, the layout of `cx`'s text, stands for a box of `size`:
13307/// both widths break its lines the same ([`SameLines`]) and its lines start
13308/// at the box's left, wherever its right is.
13309/// The width `text-pretty` breaks a text's lines at in a box `width` wide:
13310/// narrower when its last line would hold less than a quarter of it (a
13311/// word or two left alone below a paragraph), as narrow as it takes for
13312/// that line to hold a quarter of the width without adding a line. The
13313/// platform's own line breaking decides where the lines break at it; a
13314/// text that cannot do better keeps the box's width.
13315fn pretty_width<M: TextEngine>(
13316    engine: &M,
13317    cx: &mut TextContext<M::Prepared>,
13318    width: Points,
13319) -> Points {
13320    if let Some(&(w, out)) = cx.pretty.as_deref()
13321        && w == width.0
13322    {
13323        return out;
13324    }
13325    let out = narrower_lines(engine, cx, width).unwrap_or(width);
13326    if let Some(p) = &mut cx.pretty {
13327        **p = (width.0, out);
13328    }
13329    out
13330}
13331
13332/// How short a last line `text-pretty` leaves alone: a quarter of the box.
13333const PRETTY_LAST_LINE: f32 = 0.25;
13334
13335fn narrower_lines<M: TextEngine>(
13336    engine: &M,
13337    cx: &mut TextContext<M::Prepared>,
13338    width: Points,
13339) -> Option<Points> {
13340    let text = &cx.text;
13341    if text.no_wrap || text.max_lines > 0 || width <= Points::ZERO || text.text.contains('\n') {
13342        return None;
13343    }
13344    let prepared = cx
13345        .prepared
13346        .get_or_insert_with(|| engine.prepare_with(&cx.text, &cx.alignments, &cx.options));
13347    let height = engine.measure(prepared, Some(width)).height;
13348    // How short the last line is at `w`, `None` past a line more.
13349    let short = |w: Points| -> Option<bool> {
13350        let size = engine.measure(prepared, Some(w));
13351        if size.height > height {
13352            return None;
13353        }
13354        let lines = engine.lines(&engine.layout(prepared, Size { width: w, height }));
13355        let last = lines.last()?;
13356        Some(lines.len() > 1 && last.width < w * PRETTY_LAST_LINE)
13357    };
13358    if short(width) != Some(true) {
13359        return None;
13360    }
13361    // Narrowing moves words down to the last line: find the widest width
13362    // whose last line is no longer short, between the box and the
13363    // narrowest width with as many lines.
13364    let lines = engine
13365        .lines(&engine.layout(prepared, Size { width, height }))
13366        .len();
13367    let (mut lo, mut hi) = (width * ((lines - 1) as f32 / lines as f32), width);
13368    let mut found = None;
13369    for _ in 0..8 {
13370        let mid = (lo + hi) * 0.5;
13371        match short(mid) {
13372            Some(false) => {
13373                found = Some(mid);
13374                lo = mid;
13375            }
13376            Some(true) => hi = mid,
13377            None => lo = mid,
13378        }
13379        if hi - lo < Points(1.0) {
13380            break;
13381        }
13382    }
13383    found
13384}
13385
13386fn keeps_lines<P>(cx: &TextContext<P>, laid: &LaidText, size: Size<Points>) -> bool {
13387    let Some(same) = cx.same_lines else {
13388        return false;
13389    };
13390    let widths = same.narrowest..=same.widest;
13391    laid.content.size.height == size.height
13392        && widths.contains(&laid.content.size.width.0)
13393        && widths.contains(&size.width.0)
13394        && Arc::ptr_eq(&laid.text, &cx.text)
13395        && lines_start_left(&cx.text)
13396}
13397
13398/// Whether every line of `text` starts at the left of its box. A paragraph's
13399/// direction may come from its first strong character, so `auto` alignment
13400/// with a character of a right-to-left script does not count.
13401fn lines_start_left(text: &AttributedText) -> bool {
13402    match text.align {
13403        TextAlign::Left => !text.text.chars().any(is_right_to_left),
13404        TextAlign::Auto => {
13405            !text.rtl
13406                && text.writing_direction != Some(true)
13407                && !text.text.chars().any(is_right_to_left)
13408        }
13409        TextAlign::Center | TextAlign::Right | TextAlign::Justify => false,
13410    }
13411}
13412
13413/// Whether `c` is in a block of a right-to-left script.
13414fn is_right_to_left(c: char) -> bool {
13415    matches!(
13416        c as u32,
13417        0x0590..=0x08FF | 0xFB1D..=0xFDFF | 0xFE70..=0xFEFF | 0x10800..=0x10FFF | 0x1E800..=0x1EFFF
13418    )
13419}
13420
13421fn definite(size: Size<Points>) -> taffy::Size<AvailableSpace> {
13422    taffy::Size {
13423        width: AvailableSpace::Definite(size.width.0),
13424        height: AvailableSpace::Definite(size.height.0),
13425    }
13426}
13427
13428/// The message for a refused URL.
13429/// The URL a web view prop loads at or resolves against, when it is one.
13430fn web_url(prop: &Prop) -> Option<&str> {
13431    match prop {
13432        Prop::Native(
13433            NativeProp::Src(Some(url))
13434            | NativeProp::BaseUrl(Some(url))
13435            | NativeProp::Source(
13436                crate::WebSource::Uri(url)
13437                | crate::WebSource::Html {
13438                    base_url: Some(url),
13439                    ..
13440                },
13441            ),
13442        ) => Some(url),
13443        _ => None,
13444    }
13445}
13446
13447fn not_granted(what: &str, uri: &str, capability: &str) -> String {
13448    let advice = crate::access::grant_advice(uri, capability);
13449    format!("{what} {uri} is not granted: {advice}")
13450}
13451
13452/// The message for a refused media source, read against `base` as
13453/// `Access::media_url` reads it.
13454fn media_not_granted(what: &str, uri: &str, base: Option<&str>) -> String {
13455    let advice = crate::access::media_grant_advice(uri, base);
13456    format!("{what} {uri} is not granted: {advice}")
13457}
13458
13459/// A page with nothing to load and no scripts: what a web view whose manual
13460/// Applies one property to a control.
13461fn apply_native(control: &mut NativeProps, prop: NativeProp) {
13462    use NativeProp as P;
13463    match (control, prop) {
13464        (NativeProps::WebView(p), P::Source(v)) => p.source = v,
13465        // `src`, `html` and `baseUrl` make one source: `html` shows over
13466        // `src`, with the base URL set before or after it.
13467        (NativeProps::WebView(p), P::Src(Some(url))) => {
13468            if !matches!(p.source, crate::WebSource::Html { .. }) {
13469                p.source = crate::WebSource::Uri(url.clone());
13470            }
13471            p.src = Some(url);
13472        }
13473        (NativeProps::WebView(p), P::Src(None)) => {
13474            p.src = None;
13475            if matches!(p.source, crate::WebSource::Uri(_)) {
13476                p.source = crate::WebSource::None;
13477            }
13478        }
13479        (NativeProps::WebView(p), P::Html(Some(html))) => {
13480            p.source = crate::WebSource::Html {
13481                html,
13482                base_url: p.base_url.clone(),
13483            };
13484        }
13485        (NativeProps::WebView(p), P::Html(None)) => {
13486            if matches!(p.source, crate::WebSource::Html { .. }) {
13487                p.source = match &p.src {
13488                    Some(url) => crate::WebSource::Uri(url.clone()),
13489                    None => crate::WebSource::None,
13490                };
13491            }
13492        }
13493        (NativeProps::WebView(p), P::BaseUrl(url)) => {
13494            if let crate::WebSource::Html { base_url, .. } = &mut p.source {
13495                base_url.clone_from(&url);
13496            }
13497            p.base_url = url;
13498        }
13499        (NativeProps::WebView(p), P::AllowOrigin(v)) => {
13500            p.allow_origin = v.and_then(|o| crate::access::WebOrigin::parse(&o).ok());
13501        }
13502        (NativeProps::WebView(p), P::AllowNavigation(v)) => {
13503            p.allow_navigation = v.and_then(|h| crate::access::WebHosts::parse(&h).ok());
13504        }
13505        (NativeProps::WebView(p), P::InjectedJavaScript(v)) => p.injected_js = v,
13506        (NativeProps::WebView(p), P::InjectedJavaScriptBefore(v)) => p.injected_js_before = v,
13507        (NativeProps::WebView(p), P::UserAgent(v)) => p.user_agent = v,
13508        (NativeProps::WebView(p), P::Scrollable(v)) => p.scrollable = v,
13509        (NativeProps::WebView(p), P::JavaScriptEnabled(v)) => p.javascript_enabled = v,
13510        (NativeProps::WebView(p), P::BackForwardGestures(v)) => p.back_forward_gestures = v,
13511        (NativeProps::WebView(p), P::Incognito(v)) => p.incognito = v,
13512        (NativeProps::WebView(p), P::Zoomable(v)) => p.zoomable = v,
13513        (NativeProps::WebView(p), P::UrlSchemes(v)) => p.url_schemes = v,
13514        (NativeProps::WebView(p), P::DeferDownloads(v)) => p.defer_downloads = v,
13515        (NativeProps::Video(p), P::Source(v)) => {
13516            p.source = match v {
13517                crate::WebSource::Uri(uri) => Some(uri),
13518                _ => None,
13519            }
13520        }
13521        (NativeProps::Video(p), P::Src(v)) => p.source = v,
13522        (NativeProps::Video(p), P::Poster(v)) => p.poster = v,
13523        (NativeProps::Video(p), P::Paused(v)) => p.paused = v,
13524        (NativeProps::Video(p), P::Muted(v)) => p.muted = v,
13525        (NativeProps::Video(p), P::Volume(v)) => p.volume = v.clamp(0.0, 1.0),
13526        (NativeProps::Video(p), P::Rate(v)) => p.rate = v.max(0.0),
13527        (NativeProps::Video(p), P::Repeat(v)) => p.repeat = v,
13528        (NativeProps::Video(p), P::VideoResizeMode(v)) => p.resize_mode = v,
13529        (NativeProps::Video(p), P::Controls(v)) => p.controls = v,
13530        (NativeProps::Video(p), P::ProgressInterval(v)) => p.progress_interval_ms = v.max(16.0),
13531        (NativeProps::Video(p), P::AudioSession(v)) => p.audio_session = v,
13532        _ => {}
13533    }
13534}
13535
13536/// `style` with its font metrics multiplied for the user's text size.
13537fn scaled(mut style: ResolvedTextStyle, multiplier: f32) -> ResolvedTextStyle {
13538    if multiplier != 1.0 {
13539        style.font_size *= multiplier;
13540        style.line_height *= multiplier;
13541    }
13542    style
13543}
13544
13545fn root_style(viewport: Size<Points>) -> taffy::Style {
13546    let mut style = taffy::Style {
13547        size: taffy::Size {
13548            width: taffy::Dimension::length(viewport.width.0),
13549            height: taffy::Dimension::length(viewport.height.0),
13550        },
13551        ..Style::default().layout
13552    };
13553    crate::style::resolve_normal_alignment(&mut style);
13554    style
13555}
13556
13557/// The hash of a text context's content, attachments and options: it keys
13558/// the measurement caches.
13559fn text_layout_hash(
13560    alignments: &crate::AttachmentAlignments,
13561    text: &crate::AttributedText,
13562    options: &crate::TextOptions,
13563) -> u64 {
13564    use std::hash::{Hash as _, Hasher as _};
13565    let mut h = std::collections::hash_map::DefaultHasher::new();
13566    alignments.layout_hash(text).hash(&mut h);
13567    options.indent.map(|indent| indent.0.to_bits()).hash(&mut h);
13568    h.finish()
13569}
13570
13571/// `align` in a layout of direction `rtl`: left and right trade places
13572/// right to left, as all left / right properties do.
13573fn directed_align(align: TextAlign, rtl: bool) -> TextAlign {
13574    match (align, rtl) {
13575        (TextAlign::Left, true) => TextAlign::Right,
13576        (TextAlign::Right, true) => TextAlign::Left,
13577        (align, _) => align,
13578    }
13579}
13580
13581/// The press events.
13582/// The gestures and touches a view handles besides presses: one with a
13583/// handler of them is something the user moves (a draggable ball), which a
13584/// terminal keeps (`terminal_layout::Role::interactive`).
13585const HANDLED: [EventKind; 7] = [
13586    EventKind::PanStart,
13587    EventKind::PanEnd,
13588    EventKind::PinchStart,
13589    EventKind::PinchEnd,
13590    EventKind::RotationStart,
13591    EventKind::RotationEnd,
13592    EventKind::Touch,
13593];
13594
13595const PRESSES: [EventKind; 4] = [
13596    EventKind::Press,
13597    EventKind::LongPress,
13598    EventKind::PressDown,
13599    EventKind::PressUp,
13600];
13601
13602/// The events a `disabled` view does not mount ([`Node::mounted_events`]).
13603const DISABLED_OFF: [EventKind; 8] = [
13604    EventKind::Press,
13605    EventKind::LongPress,
13606    EventKind::PressDown,
13607    EventKind::PressUp,
13608    EventKind::ContextMenu,
13609    EventKind::FileDragEnter,
13610    EventKind::FileDragLeave,
13611    EventKind::FileDrop,
13612];
13613
13614/// Whether `disabled` changes what a view with `events` mounts.
13615fn disabling_changes(events: EventMask) -> bool {
13616    DISABLED_OFF.iter().any(|&e| events.contains(e))
13617}
13618
13619/// A span's horizontal padding at its first and last character, in
13620/// points (its block is right to left when `rtl`). Percentages, of no box
13621/// a span has, count as none.
13622fn span_padding(node: &Node, rtl: bool) -> (f32, f32) {
13623    let Some(style) = node.base_layout.as_deref() else {
13624        return (0.0, 0.0);
13625    };
13626    let len = |p: taffy::LengthPercentage| match p.into_raw().tag() {
13627        taffy::CompactLength::LENGTH_TAG => p.into_raw().value().max(0.0),
13628        _ => 0.0,
13629    };
13630    let (left, right) = (len(style.padding.left), len(style.padding.right));
13631    if rtl { (right, left) } else { (left, right) }
13632}
13633
13634/// A span's top and bottom padding, which only its background takes (as
13635/// a CSS inline box's): the line keeps its height. Percentages count as
13636/// none.
13637fn span_vertical_padding(node: &Node) -> (Points, Points) {
13638    let Some(style) = node.base_layout.as_deref() else {
13639        return (Points::ZERO, Points::ZERO);
13640    };
13641    let len = |p: taffy::LengthPercentage| match p.into_raw().tag() {
13642        taffy::CompactLength::LENGTH_TAG => Points(p.into_raw().value().max(0.0)),
13643        _ => Points::ZERO,
13644    };
13645    (len(style.padding.top), len(style.padding.bottom))
13646}
13647
13648/// The background a nested text's view style gives its characters.
13649fn span_background(style: &ViewStyle, node: NodeId) -> Option<crate::text::TextBackground> {
13650    (style.background_color.0 & 0xff != 0).then_some(crate::text::TextBackground {
13651        color: style.background_color,
13652        radius: style.border_radius.max(Points::ZERO),
13653        node,
13654        top: Points::ZERO,
13655        bottom: Points::ZERO,
13656    })
13657}
13658
13659/// Whether a span with `events` takes presses (a link in its text block).
13660fn pressable(events: EventMask) -> bool {
13661    PRESSES.iter().any(|&e| events.contains(e))
13662}
13663
13664/// `content` with a line break after every [`MEASURED_RUN`] characters of
13665/// a run without a line-break opportunity, as a multiline input's value is measured.
13666///
13667/// Line breakers search back over the whole run for a break opportunity
13668/// at the end of every line they lay out (CoreText through ICU), so one
13669/// long run (minified JSON, Base64) costs time quadratic in its length:
13670/// 13 s to measure a 474 KB minified JSON on an Apple silicon Mac, on the
13671/// engine thread, at every edit. Broken into runs of 1024 it takes 47 ms. The
13672/// input shows and reports its own text; the measured height can only
13673/// grow by a line per break, and text without such runs is measured as is.
13674fn broken_runs(content: &str) -> std::borrow::Cow<'_, str> {
13675    let mut broken: Option<String> = None;
13676    let (mut start, mut from) = (0, 0);
13677    for (end, _) in unicode_linebreak::linebreaks(content) {
13678        let mut run = 0;
13679        for (offset, c) in content[start..end].char_indices() {
13680            let i = start + offset;
13681            // The final character may itself provide the break (space or
13682            // newline). Do not introduce another line immediately before it.
13683            if run == MEASURED_RUN && i + c.len_utf8() < end {
13684                let broken = broken.get_or_insert_with(|| {
13685                    String::with_capacity(content.len() + content.len() / MEASURED_RUN)
13686                });
13687                broken.push_str(&content[from..i]);
13688                broken.push('\n');
13689                (run, from) = (0, i);
13690            }
13691            run += 1;
13692        }
13693        start = end;
13694    }
13695    match broken {
13696        Some(mut broken) => {
13697            broken.push_str(&content[from..]);
13698            broken.into()
13699        }
13700        None => content.into(),
13701    }
13702}
13703
13704/// A visual style being installed on a node ([`Core::install_style`]):
13705/// resolved for it alone (`T`, [`Core::set_style`]) or shared with the nodes
13706/// whose classes resolved alike (`Option<Rc<T>>`, `None` the default,
13707/// [`classes::ResolvedClassStyle`]). Generic rather than an enum so that a
13708/// shared style moves as a pointer, not as large as an owned one.
13709trait StyleSlot<T: SharedDefault>: Sized {
13710    fn get(&self) -> &T;
13711    /// Whether `held` holds it already (by pointer first for a shared one).
13712    fn same(&self, held: &Sparse<T>) -> bool;
13713    fn install(self, held: &mut Sparse<T>);
13714}
13715
13716impl<T: SharedDefault + Clone> StyleSlot<T> for T {
13717    fn get(&self) -> &T {
13718        self
13719    }
13720
13721    fn same(&self, held: &Sparse<T>) -> bool {
13722        **held == *self
13723    }
13724
13725    fn install(self, held: &mut Sparse<T>) {
13726        held.set(self);
13727    }
13728}
13729
13730impl<T: SharedDefault + Clone> StyleSlot<T> for Option<Rc<T>> {
13731    fn get(&self) -> &T {
13732        self.as_deref().unwrap_or_else(|| T::shared_default())
13733    }
13734
13735    fn same(&self, held: &Sparse<T>) -> bool {
13736        match (&held.0, self) {
13737            (None, None) => true,
13738            (Some(a), Some(b)) => Rc::ptr_eq(a, b) || **a == **b,
13739            (Some(a), None) => **a == *T::shared_default(),
13740            (None, Some(b)) => *T::shared_default() == **b,
13741        }
13742    }
13743
13744    fn install(self, held: &mut Sparse<T>) {
13745        held.0 = self;
13746    }
13747}
13748
13749/// The layout style being installed on a node, [`StyleSlot`]'s
13750/// counterpart: `taffy::Style` or a shared `Rc<taffy::Style>`.
13751trait LayoutSlot: Sized {
13752    fn get(&self) -> &taffy::Style;
13753    /// The node's own copy to adjust (`env()`, insets).
13754    fn to_mut(&mut self) -> &mut taffy::Style;
13755    fn into_owned(self) -> taffy::Style;
13756    /// Makes it `node`'s style in `tree`; whether that changed it.
13757    fn set_on<C>(self, tree: &mut LayoutTree<C>, node: LayoutId) -> bool;
13758}
13759
13760impl LayoutSlot for taffy::Style {
13761    fn get(&self) -> &taffy::Style {
13762        self
13763    }
13764
13765    fn to_mut(&mut self) -> &mut taffy::Style {
13766        self
13767    }
13768
13769    fn into_owned(self) -> taffy::Style {
13770        self
13771    }
13772
13773    fn set_on<C>(self, tree: &mut LayoutTree<C>, node: LayoutId) -> bool {
13774        tree.set_style(node, self)
13775    }
13776}
13777
13778impl LayoutSlot for Rc<taffy::Style> {
13779    fn get(&self) -> &taffy::Style {
13780        self
13781    }
13782
13783    fn to_mut(&mut self) -> &mut taffy::Style {
13784        Rc::make_mut(self)
13785    }
13786
13787    fn into_owned(self) -> taffy::Style {
13788        Rc::unwrap_or_clone(self)
13789    }
13790
13791    fn set_on<C>(self, tree: &mut LayoutTree<C>, node: LayoutId) -> bool {
13792        tree.set_style_shared(node, self)
13793    }
13794}
13795
13796/// What [`Core::install_style`] makes a node's style: a resolved
13797/// [`Style`] after [`prepare_layout`] and [`clip_overflow`].
13798struct StyleRecord<L, V, X> {
13799    layout: L,
13800    view: V,
13801    text: X,
13802    paint: Option<Rc<PaintStyle>>,
13803    animated: Vec<(AnimationProp, crate::animation::NodeId)>,
13804    /// A sticky box's insets, taken out of its layout.
13805    sticky: Option<taffy::Rect<taffy::LengthPercentageAuto>>,
13806    perspective: Option<Points>,
13807    object_fit: Option<ResizeMode>,
13808    wants_fixed: bool,
13809    env: crate::style::EnvEdges,
13810    z_index: i32,
13811    vertical_align: crate::style::VerticalAlign,
13812    has_logical: bool,
13813    rtl: bool,
13814}
13815
13816/// What a resolved layout takes before it is installed, for `rtl`
13817/// ([`Core::set_style`], [`Core::resolved_styles`]): CSS's `normal`
13818/// alignment resolved and its start / end sides placed. A sticky box's insets
13819/// say where it sticks, not where it is laid out: they are taken out and
13820/// returned.
13821fn prepare_layout(
13822    layout: &mut taffy::Style,
13823    view: &mut ViewStyle,
13824    logical: &crate::style::Logical,
13825    rtl: bool,
13826    sticky: bool,
13827) -> Option<taffy::Rect<taffy::LengthPercentageAuto>> {
13828    crate::style::resolve_normal_alignment(layout);
13829    crate::style::apply_direction(layout, view, logical, rtl);
13830    sticky.then(|| {
13831        let auto = taffy::LengthPercentageAuto::auto();
13832        std::mem::replace(
13833            &mut layout.inset,
13834            taffy::Rect {
13835                left: auto,
13836                right: auto,
13837                top: auto,
13838                bottom: auto,
13839            },
13840        )
13841    })
13842}
13843
13844/// `overflow: "hidden"` clips in layout as well as in paint: what a box
13845/// clips away must not reach an enclosing scroll view's content size, or a
13846/// child laid out wider than its box and scaled down with a transform
13847/// (transforms do not affect layout) leaves the scroll view scrollable across
13848/// its own axis. `Clip`, not `Hidden`: both stop the overflow from
13849/// propagating, but `Hidden` is a scroll container in CSS and would also make
13850/// the box's automatic minimum size as a flex or grid item 0, which clipping
13851/// the paint must not do. Set here rather than while parsing the style so that
13852/// what `overflow` sets as a style stays what it was.
13853fn clip_overflow(layout: &mut taffy::Style, clip: bool) {
13854    let clip = if clip {
13855        taffy::Overflow::Clip
13856    } else {
13857        taffy::Overflow::Visible
13858    };
13859    layout.overflow = taffy::Point { x: clip, y: clip };
13860}
13861
13862/// `Rc` equality, by pointer first.
13863fn opt_rc_eq<T: PartialEq>(a: Option<&Rc<T>>, b: Option<&Rc<T>>) -> bool {
13864    match (a, b) {
13865        (None, None) => true,
13866        (Some(a), Some(b)) => Rc::ptr_eq(a, b) || **a == **b,
13867        _ => false,
13868    }
13869}
13870
13871/// What a leaf of `kind` measures with, if anything: texts and inputs (an
13872/// input measures like a text block holding its text or placeholder) their
13873/// text, images their image, native components the size they report.
13874fn leaf_context<P>(kind: Kind) -> Option<LeafContext<P>> {
13875    match kind {
13876        Kind::Text | Kind::Input => Some(LeafContext::Text(Box::new(TextContext::new(
13877            Arc::default(),
13878        )))),
13879        Kind::Image => Some(LeafContext::Image(None)),
13880        Kind::Native => Some(LeafContext::Native(None)),
13881        _ => None,
13882    }
13883}
13884
13885/// What a mount item changed of what shows, for the shaders that read what
13886/// is behind them ([`Core::mark_shader_inputs`]).
13887enum Shown {
13888    /// Nothing that shows: input, accessibility, the pictures' own marks,
13889    /// animated values (they reach the views on the UI thread, whose
13890    /// platform pictures the backdrops again), views leaving (their old
13891    /// parents stand in for them: `unlinked_from`).
13892    Nothing,
13893    /// What a view shows, or where.
13894    View(NodeId),
13895    /// Anything, anywhere: the appearance, the order of the tree, a
13896    /// transition. An item not known here is one, to be safe.
13897    Everywhere,
13898}
13899
13900fn shown_by(item: &MountItem) -> Shown {
13901    use MountItem as M;
13902    match item {
13903        M::Events { .. }
13904        | M::Keymap(_)
13905        | M::Gestures { .. }
13906        | M::AccessibilityLabel { .. }
13907        | M::ShaderInput { .. }
13908        | M::LayoutAnimation(_)
13909        | M::Animation(_)
13910        | M::ComponentPropSlots { .. }
13911        | M::TrackStates { .. }
13912        | M::InputContent { .. }
13913        | M::Remove { .. }
13914        | M::Delete { .. } => Shown::Nothing,
13915        M::Insert { child, .. } => Shown::View(*child),
13916        M::ProjectStates { id, .. }
13917        | M::ScrollConfig { id, .. }
13918        | M::ScrollBy { id, .. }
13919        | M::StickyCells { id, .. }
13920        | M::ScrollBehavior { id, .. }
13921        | M::Refreshing { id, .. }
13922        | M::AnimationBindings { id, .. }
13923        | M::ScreenConfig { id, .. }
13924        | M::ModalConfig { id, .. } => Shown::View(*id),
13925        M::Command { id, command } => {
13926            use crate::ops::Command as C;
13927            match command {
13928                // Outside the window's content: the system's, the app's,
13929                // another program's.
13930                C::ExitApp
13931                | C::PostMessage { .. }
13932                | C::SendInput { .. }
13933                | C::SetJsResponder { .. }
13934                | C::ClearJsResponder
13935                | C::Announce { .. }
13936                | C::ImageInfo { .. }
13937                | C::AccessibilityFocus
13938                | C::Measure { .. }
13939                | C::MeasureScrollPosition { .. }
13940                | C::SetClipboard { .. }
13941                | C::SetClipboardItem(_)
13942                | C::ReadClipboard { .. }
13943                | C::SetClipboardImage { .. }
13944                | C::ReadClipboardImage { .. }
13945                | C::ReadClipboardFiles { .. }
13946                | C::PickImages { .. }
13947                | C::PickFiles { .. }
13948                | C::OpenUrl { .. }
13949                | C::OpenAppSettings { .. }
13950                | C::PickScreenColor { .. }
13951                | C::RenderCanvas { .. }
13952                | C::FileRequest { .. }
13953                | C::Audio { .. }
13954                | C::Notification { .. }
13955                | C::Desktop { .. }
13956                | C::HostCall { .. }
13957                | C::HostPost { .. } => Shown::Nothing,
13958                // The design tokens: every view's colors.
13959                C::Tokens { .. } => Shown::Everywhere,
13960                _ => Shown::View(*id),
13961            }
13962        }
13963        item => item.view().map_or(Shown::Everywhere, Shown::View),
13964    }
13965}
13966
13967/// What collecting a text block's text gathers about its attachments, and
13968/// what it places them by.
13969struct TextAttachments<'a> {
13970    /// Where each sits in its line.
13971    alignments: crate::AttachmentAlignments,
13972    /// The empty attachments standing for spans' horizontal padding.
13973    spacers: Vec<u32>,
13974    /// The baselines of their own the views holding text stand by
13975    /// ([`Core::attachment_baselines`]).
13976    baselines: &'a [(Key, Points)],
13977    /// The first of `baselines` not met yet: they are in the attachments'
13978    /// order ([`Core::attachments_of`]).
13979    next_baseline: usize,
13980}