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 = if laid.text.spans == self.text.spans {
1267            self.text.clone()
1268        } else {
1269            // A fitted text draws its scaled spans: the new metadata goes
1270            // on them.
1271            let mut text = (*laid.text).clone();
1272            text.set_metadata(&self.text);
1273            Arc::new(text)
1274        };
1275        laid.text = text.clone();
1276        self.metadata_changed = false;
1277        Some((text, laid.layout.clone()))
1278    }
1279}
1280
1281/// What an input is as wide as when nothing gives it a width, whatever it
1282/// holds: as CSS's `<input size="20">`, twenty digits.
1283const FIELD_SAMPLE: &str = "00000000000000000000";
1284
1285/// Measured leaves: text blocks and images with a known natural size.
1286enum LeafContext<P> {
1287    /// Boxed: a text's context is far larger than an image's, and a leaf
1288    /// slot of every node would carry the difference.
1289    Text(Box<TextContext<P>>),
1290    Image(Option<Size<Points>>),
1291    /// A registered native component's own size, once it reported one.
1292    Native(Option<Size<Points>>),
1293}
1294
1295/// A request for the JS runtime to render list items into cells.
1296#[derive(Debug, Clone, PartialEq, Eq)]
1297pub struct ListBind {
1298    /// The list.
1299    pub list: NodeId,
1300    /// `(slot, item index)` pairs.
1301    pub binds: Vec<(u32, u32)>,
1302}
1303
1304/// Takes list `list`'s binds still queued (`Core::list_binds`, a
1305/// component's list's that a commit's last round asked for), as its items
1306/// change: the runtime moves its cells with the items before they could
1307/// run, so they would show items at indices that are no longer theirs. The
1308/// list asks for its cells again ([`ListState::unrequest`]). Returns their
1309/// slots.
1310fn take_queued_binds(binds: &mut Vec<ListBind>, list: NodeId) -> Vec<u32> {
1311    let mut slots = Vec::new();
1312    binds.retain(|b| {
1313        if b.list != list {
1314            return true;
1315        }
1316        slots.extend(b.binds.iter().map(|&(slot, _)| slot));
1317        false
1318    });
1319    slots
1320}
1321
1322/// How deep views nest under the root: an insert that would put a view
1323/// deeper is refused ([`ApplyError::TooDeep`]). Layout, mounting and the
1324/// walks of the tree recurse once per level, on the native stack, which
1325/// neither the node quota nor the interpreter's stack limit bounds: without
1326/// this a chain of views overflows it and aborts the process. Far deeper
1327/// than a UI nests, and shallow enough for the engine thread's 8 MiB stack
1328/// in a debug build.
1329pub const MAX_TREE_DEPTH: usize = 1024;
1330
1331/// An op referenced a node in an impossible way. This is a renderer bug;
1332/// the op is skipped and the tree stays consistent.
1333#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1334pub enum ApplyError {
1335    /// The id is unknown (never created or already released).
1336    UnknownNode(NodeId),
1337    /// The id is already in use.
1338    DuplicateNode(NodeId),
1339    /// The child is not a child of the given parent.
1340    NotAChild(NodeId),
1341    /// The `before` sibling is not a child of the given parent.
1342    BadAnchor(NodeId),
1343    /// The insert would create a cycle.
1344    Cycle(NodeId),
1345    /// Creating the node would exceed the node quota ([`Core::set_max_nodes`]).
1346    TooManyNodes(usize),
1347    /// The insert would nest views deeper than the depth quota
1348    /// ([`MAX_TREE_DEPTH`]).
1349    TooDeep(usize),
1350    /// A new id far beyond the ids in use (ids index a table, so they must
1351    /// stay dense).
1352    IdOutOfRange(NodeId),
1353}
1354
1355impl ApplyError {
1356    /// The app went over a quota or sent what no runtime sends: it should
1357    /// be stopped rather than continue.
1358    pub fn is_fatal(&self) -> bool {
1359        matches!(
1360            self,
1361            ApplyError::TooManyNodes(_) | ApplyError::TooDeep(_) | ApplyError::IdOutOfRange(_)
1362        )
1363    }
1364}
1365
1366/// What [`Core::retag`] knows of the mount items of a round of renders,
1367/// which only grows at its end until the round is over.
1368#[derive(Default)]
1369struct Retags {
1370    /// The views whose `Create` is among the items looked at.
1371    made: rustc_hash::FxHashSet<NodeId>,
1372    /// The items looked at.
1373    seen: usize,
1374    /// The views that took another kind, with the number of items then:
1375    /// their `Create` and `Insert` before that go.
1376    retagged: rustc_hash::FxHashMap<NodeId, usize>,
1377}
1378
1379/// The shadow tree of one surface.
1380///
1381/// Feed it [`Op`]s with [`Core::apply`], then call [`Core::commit`] once per
1382/// JS turn to get the [`MountBatch`] for the platform. Lists may then ask
1383/// the runtime to render more items ([`Core::take_list_binds`]); the engine
1384/// runs those and commits again within the same frame.
1385pub struct Core<M: TextEngine> {
1386    nodes: Slab<Node>,
1387    /// Node id -> key + 1 (0 = none). Ids are dense, so this is a flat vec.
1388    slots: crate::id_table::IdTable<Key>,
1389    /// The extent reached by admitted ids. JS keeps issuing new ids after a page is freed.
1390    admitted_id_extent: usize,
1391    /// Raw text runs kept without a node (#1345): a run not in the tree,
1392    /// or the only child of a text block or span, which shows it. Any
1393    /// other use makes its node ([`Core::materialize_run`]).
1394    runs: rustc_hash::FxHashMap<NodeId, Run>,
1395    /// Text block or span -> the run it holds in [`Core::runs`].
1396    folded: rustc_hash::FxHashMap<Key, NodeId>,
1397    layout: LayoutTree<LeafContext<M::Prepared>>,
1398    text_engine: Rc<M>,
1399    /// The engine for [`crate::text::TextGeometry`] (`None` for an engine
1400    /// that is not `'static`).
1401    geometry_engine: Option<Rc<dyn crate::text::GeometryEngine>>,
1402    /// Final layouts kept for Rust components' `on_text_layout` until
1403    /// their `TextLayout` events are dispatched ([`keep_geometry`]).
1404    geometries: rustc_hash::FxHashMap<NodeId, crate::text::TextGeometry>,
1405    measure_cache: MeasureCache,
1406    /// Counts the commits of resizes ([`Core::mark_near_screen`]).
1407    resizing_commit: u32,
1408    /// The next layout follows a change of the viewport, or the text that
1409    /// waited through a burst of resizes: scroll views keep their place
1410    /// through it (`resize_anchor`).
1411    resize_settling: bool,
1412    /// Text blocks whose final layout must be (re)made after layout.
1413    pending_text: Vec<Key>,
1414    /// Text blocks with attachments (checked for attachments laid out
1415    /// again).
1416    attachment_blocks: Vec<Key>,
1417    /// Live list nodes.
1418    lists: Vec<Key>,
1419    /// The lists in their parent's viewport (`viewport="parent"`), outer
1420    /// ones first ([`Core::resolve_outer`]).
1421    parent_lists: Vec<Key>,
1422    /// Views moved in a tree with such lists: their views are found again.
1423    outer_moved: bool,
1424    /// Such a list changed length: the commit lays the page out again.
1425    extent_changed: bool,
1426    /// Scroll views cull their content ([`Core::set_content_culling`]).
1427    culls_content: bool,
1428    /// The scroll views with culled views in their content (`cull.rs`).
1429    culling: Vec<Key>,
1430    /// One of them scrolled, or culled a view, since they were looked at.
1431    cull_dirty: bool,
1432    /// Culled views were made in this round: their styles go out in
1433    /// another.
1434    cull_made: bool,
1435    /// A list gave the views in a cell their frames in this round, after
1436    /// culling looked at the scroll views among them (`cull.rs`).
1437    cells_framed: bool,
1438    /// The walk of [`Core::sync_culled`], kept for its buffer: each view
1439    /// with where it is in the scroll view's content and how far the
1440    /// transforms around it may move it (`cull.rs`).
1441    cull_scratch: Vec<(Key, f32, f32, f32, f32)>,
1442    /// How far the animation graph's values may go: how far an animated
1443    /// transform may move a view culling looks at
1444    /// (`animation/reach.rs`).
1445    reach: crate::animation::Reach,
1446    /// Views out of sight spread over turns (`pace.rs`).
1447    pace: pace::Pace,
1448    /// Lists' rows under this turn's layout animation (`list_motion.rs`).
1449    list_motion: list_motion::ListMotion,
1450    /// The placeholders of `<Each>` rows ([`Op::Placeholder`]), with their
1451    /// ids (a key may be another node's by now).
1452    placeholders: Vec<(Key, NodeId)>,
1453    /// The placeholders whose rows JS is asked to render next
1454    /// ([`crate::element::JsEvent::Rows`]).
1455    asked_rows: Vec<NodeId>,
1456    /// Placeholders were sized again in this round: laid out again
1457    /// before culling looks at them.
1458    placeholders_resized: bool,
1459    /// The scroll views such lists asked to scroll in this commit.
1460    outer_asked: Vec<Key>,
1461    /// The views whose lists' sticky cells changed in this commit.
1462    sticky_views: Vec<Key>,
1463    /// Views with `position: sticky` ([`Core::update_sticky_views`]).
1464    sticky_nodes: Vec<Key>,
1465    /// The scroll views their ranges were last sent to.
1466    sticky_scrollers: Vec<Key>,
1467    /// What makes the views' bars when the app draws them with the
1468    /// built-in one ([`Core::set_builtin_scrollbars`]).
1469    builtin_scrollbars: Option<(crate::element::ScrollbarSource, crate::element::AnyValue)>,
1470    /// Scroll views and lists whose built-in bar may come or go
1471    /// ([`Core::sync_scrollbars`]).
1472    scrollbars_pending: Vec<Key>,
1473    /// The multiline inputs scroll watches follow, sorted
1474    /// ([`Core::sync_watched_inputs`]).
1475    watched_inputs: Vec<NodeId>,
1476    /// Canvases fitting a view box into their box
1477    /// ([`crate::canvas::ViewPaint::Fit`]) to send once this round's
1478    /// layout gave them their size ([`Core::send_fitted`]).
1479    fitted_pending: Vec<Key>,
1480    /// Scroll views and lists that show a built-in bar.
1481    decorated: Vec<Key>,
1482    /// Sticky views came, went or moved: their ranges are worked out
1483    /// again.
1484    sticky_changed: bool,
1485    /// Views whose frame follows an element's ([`Core::place_followers`]).
1486    followers: Vec<Key>,
1487    /// Views naming other elements for assistive technologies
1488    /// ([`Core::sync_relations`]).
1489    relators: Vec<relations::Relator>,
1490    /// What they follow, or frames around them, changed since they were
1491    /// placed.
1492    follow_changed: bool,
1493    /// The warning about `bottom` / `right` sticky insets was logged.
1494    sticky_warned: bool,
1495    /// The warning about animated insets of views that are not sticky, or
1496    /// on the axis their scroll view does not scroll, was logged.
1497    inset_warned: bool,
1498    /// Compiled shaders by the hash of their source, with their errors
1499    /// (an app setting the same source again compiles it once).
1500    shaders: rustc_hash::FxHashMap<u64, Result<crate::shader::Shader, crate::shader::ShaderError>>,
1501    /// Web views whose URL `webview.hosts` does not grant, set while the
1502    /// app may add an origin at run time (`webview.runtimeOrigin`): their
1503    /// `allowOrigin` may come later in the same render, so they are
1504    /// checked when their props go out ([`Self::settle_web_urls`]).
1505    web_unchecked: rustc_hash::FxHashSet<(Key, NodeId)>,
1506    /// Shader transitions this commit starts ([`MountItem::ShaderTransition`]),
1507    /// put first in its batch.
1508    transition_starts: Vec<MountItem>,
1509    /// The shader views whose layers read pictures (`sample_content`, ...).
1510    pictured: rustc_hash::FxHashSet<NodeId>,
1511    /// The parents views left this commit, while any shader reads
1512    /// pictures: what is above them changed though their mount items no
1513    /// longer lead there ([`Core::mark_shader_inputs`]).
1514    unlinked_from: Vec<NodeId>,
1515    /// Live screens, modals and header items.
1516    roots: Vec<Key>,
1517    /// Attached input accessories by `nativeID`.
1518    accessories: rustc_hash::FxHashMap<Box<str>, NodeId>,
1519    /// Height of the native header bar of screens: normal and large title.
1520    header_heights: (Points, Points),
1521    /// Natural sizes of the platform's controls.
1522    /// The surface's safe-area insets (stacks at the top extend their
1523    /// headers under the status bar).
1524    safe_area: EdgeInsets,
1525    /// Where the root view's anchored overlays may go, in its coordinates,
1526    /// when the platform shows them beyond the root view
1527    /// ([`Core::set_overlay_area`]).
1528    overlay_bounds: Option<crate::geometry::Bounds<Points>>,
1529    /// The distance overlays without a `margin` of their own keep from the
1530    /// edges of their room ([`Core::set_snap_to_window_margin`]).
1531    snap_to_window_margin: Points,
1532    list_binds: Vec<ListBind>,
1533    /// The lists keeping items rendered ([`Core::sync_kept`]).
1534    kept_lists: Vec<Key>,
1535    /// The nodes of the last [`Core::set_kept`].
1536    selection_kept: Vec<NodeId>,
1537    /// [`Core::sync_kept`]'s buffer, reused.
1538    kept_scratch: Vec<Key>,
1539    /// The runtime's lists with overscan cells waiting to bind
1540    /// ([`Core::take_paced_list_binds`]), in the order they asked.
1541    paced_lists: Vec<NodeId>,
1542    /// [`Core::take_paced_list_binds`]'s buffer, reused.
1543    paced_scratch: Vec<(u32, u32)>,
1544    /// The events for JS, in order (the platform's and the core's events,
1545    /// Rust components' events, calls' results).
1546    events: Vec<crate::element::JsEvent>,
1547    /// Reused buffer of `(item index, cell)` for list updates.
1548    cells_scratch: Vec<(u32, Key)>,
1549    /// The list cells whose content waits for the app's render functions
1550    /// this round (sorted; [`Core::cells_awaiting_renders`]): not measured.
1551    awaiting_renders: Vec<Key>,
1552    root: Key,
1553    viewport: Size<Points>,
1554    mount: Vec<MountItem>,
1555    track_tree_order: bool,
1556    tree_order_changed: bool,
1557    /// The tree changed: the shown overlays' places in the Tab order are
1558    /// found again ([`Core::order_overlays_for_tab`]).
1559    tab_places_stale: bool,
1560    /// A key listener or capture rule changed, or an overlay moved in:
1561    /// the shown overlays' `key_parent` overrides are found again
1562    /// ([`Core::sync_key_parents`]).
1563    key_ancestry_dirty: bool,
1564    /// Mount the states nodes show as parts of a control
1565    /// ([`MountItem::ProjectStates`]).
1566    mount_projected: bool,
1567    /// Batches handed out so far: tells this batch's mount indexes from
1568    /// earlier ones'.
1569    batches: u64,
1570    /// Component roots taking their kind in this round of renders
1571    /// ([`Core::retag`]).
1572    retags: Option<Box<Retags>>,
1573    /// Imperative calls, run after everything else in the batch.
1574    commands: Vec<(NodeId, Command)>,
1575    /// Where the keyboard focus goes back to in this commit, and the popup
1576    /// it comes back from, unless a `focus()` moves it out of that popup
1577    /// ([`crate::element::ElementRef::focus_back`]).
1578    focus_back: Option<(NodeId, Option<NodeId>)>,
1579    /// The focus the popups that give it back to these nodes opened
1580    /// with, when a pointer opened them
1581    /// ([`crate::element::ElementRef::focus_back_origin`]): one per
1582    /// trigger, its latest opening.
1583    focus_origins: Vec<(NodeId, Option<(Key, NodeId)>)>,
1584    /// The trigger a popup a pointer opened gave the focus back to, off
1585    /// macOS and iOS, until the focus is reported: the pointer's focus,
1586    /// however the popup closed (`focus_by_pointer`).
1587    pointer_focus_back: Option<NodeId>,
1588    /// Animates the layout changes of the next commit.
1589    layout_animation: Option<LayoutAnimation>,
1590    /// Nodes whose change animates the frames it moves in the next commit,
1591    /// or their own frame alone when true (`layout_scope.rs`).
1592    scoped_layout: Vec<(NodeId, crate::LayoutTransition, bool)>,
1593    /// Nodes that changed size while `scoped_layout` waits.
1594    resized: Vec<Key>,
1595    /// Nodes that lost a child while `scoped_layout` waits.
1596    restructured: Vec<Key>,
1597    /// The nodes whose padding or margin uses `env()` (`Node::env`).
1598    env_styled: rustc_hash::FxHashSet<NodeId>,
1599    /// Scratch of [`Core::sync_env`].
1600    env_scratch: Vec<NodeId>,
1601    /// The keyboard's height changed since the last commit: what that
1602    /// commit moves (an `env()` term, or a style that reads the keyboard's
1603    /// height) moves with the keyboard.
1604    keyboard_moved: bool,
1605    /// The screens and modals with a `statusBar`, in the order they got
1606    /// it: few, so attaching and detaching only flag them for the commit.
1607    status_bar_nodes: Vec<Key>,
1608    /// The tree changed with `status_bar_nodes` in it: the commit checks
1609    /// which are in the tree.
1610    status_bars_moved: bool,
1611    /// The pages with a `supportedOrientations` (their
1612    /// [`crate::ModalConfig::PORTRAIT`] bits), in the order they got it.
1613    orientation_pages: Vec<(Key, u8)>,
1614    /// What [`Command::Orientations`] last said (0: the app's own).
1615    orientations_shown: u8,
1616    /// Nodes whose classes say `pointer-events-none`: without any, moving
1617    /// nodes skips what CSS's inherited `pointer-events` needs.
1618    pointer_none_classes: u32,
1619    /// The tops of the `pointer-events-*` regions that views joined or
1620    /// left, or whose classes changed, since the last round: worked out
1621    /// once each, before the round's mount items
1622    /// ([`Self::flush_pointer_events`]). Worked out on every move, a
1623    /// region's whole subtree was walked for each view inserted in it (an
1624    /// editor's highlighted rows: 1600 spans, 2500 views, 10 ms a commit).
1625    pointer_pending: Vec<Key>,
1626    /// Views whose hit slop changed since the last round: the areas of the
1627    /// views around them are worked out again after the layout
1628    /// ([`Self::update_slop_overflow`]).
1629    slop_moved: Vec<Key>,
1630    /// The view with the keyboard focus, by key and id (keys are reused),
1631    /// as the platform reports it (`classes::focus_reported`).
1632    focus: Option<(Key, NodeId)>,
1633    /// The focus and the views around it, innermost first: the views in
1634    /// `focus-within` (`classes::update_focus_within`).
1635    focus_chain: Vec<(Key, NodeId)>,
1636    /// The chain before, reused.
1637    focus_scratch: Vec<(Key, NodeId)>,
1638    /// The focus was reported or a view of its chain moved since the
1639    /// chain was last worked out: the next commit round does it once,
1640    /// whatever order the reports came in.
1641    focus_moved: bool,
1642    /// A view reported losing the focus and none took it since: the chain
1643    /// waits for the next display frame before it lets go, so a move
1644    /// that comes as a blur then a focus in two messages, with a commit
1645    /// between them, is one change of `focus-within`, not a leave and a
1646    /// new enter.
1647    blur_held: bool,
1648    /// The chain changed since the focus watches last looked
1649    /// (`ElementRef::on_focus_in`).
1650    focus_within_changed: bool,
1651    /// What the user last gave the surface input with, as the platform
1652    /// reports it (`classes::set_input_modality`); `None` before any.
1653    modality: Option<crate::platform::InputModality>,
1654    /// The focus shows (`focus-visible:`), decided when it was reported
1655    /// (`classes::focus_shows`) and again when a key is typed.
1656    focus_visible: bool,
1657    /// The keyboard moved the focus, on a platform whose tooltips follow
1658    /// it (`classes::focus_shows_hints`), decided when it was reported
1659    /// and kept until it moves again, whatever is typed meanwhile: only
1660    /// such a focus shows the hint of the anchor it comes to
1661    /// (`overlay::focus_hints`).
1662    focus_by_keyboard: bool,
1663    /// A pointer moved the focus where it is (a press, a popup a press
1664    /// used giving it back), decided when it was reported and kept until
1665    /// it moves again: the keymap's `Keymap::pointer_focus`.
1666    focus_by_pointer: bool,
1667    /// The keymap the app mounted last, while one of its bindings asks
1668    /// how the focus came ([`crate::keymap::Keymap::takes_over_pointer_focus`]),
1669    /// and the `focus_by_pointer` it was mounted with: mounted again as
1670    /// that changes.
1671    pointer_keymap: Option<(Arc<crate::keymap::Keymap>, bool)>,
1672    /// A shown modal closed; focus reports restore context until the next
1673    /// user action, rather than requesting another hint.
1674    restoring_modal_focus: bool,
1675    /// Modals made in this commit: each gives the keyboard focus to its
1676    /// first control as it opens (`focus_opened_modals`).
1677    modals_opened: Vec<(Key, NodeId)>,
1678    /// The control an opening dialog gave the focus to, until the focus
1679    /// is reported there or the user acts: that focus shows no hint, as
1680    /// a desktop dialog's first control shows no tooltip when it opens,
1681    /// so the first Escape closes the dialog (`classes::focus_reported`).
1682    modal_focus_given: Option<NodeId>,
1683    /// The view in the `FOCUS_VISIBLE` state, by key and id
1684    /// (`classes::update_focus_visible`).
1685    focus_visible_on: Option<(Key, NodeId)>,
1686    /// `focus_visible` changed with the focus staying where it is: the
1687    /// next commit round moves the state.
1688    focus_visible_moved: bool,
1689    /// The parts projected focused (`project_focused`: a tree's or a
1690    /// list's cursor), by key and id: they show `focus-visible:` while the
1691    /// focus does, restyled when it starts or stops showing
1692    /// (`classes::styled_states`).
1693    projected_focus: Vec<(Key, NodeId)>,
1694    /// Short completed presses whose `PRESSED` state is held until a
1695    /// deadline so same-turn tap-to-click gestures still render `:active`.
1696    pressed_impulses: Vec<(Key, NodeId, crate::time::Instant)>,
1697    /// The views a pointer passed on into an element is over
1698    /// (`ElementRef::hover_at`), by element, innermost first.
1699    passed_hovers: rustc_hash::FxHashMap<NodeId, Vec<NodeId>>,
1700    /// Nodes whose `position: fixed` changed: made overlays (or views again)
1701    /// as the commit starts ([`Core::sync_fixed`]).
1702    fixed_changed: Vec<(Key, NodeId)>,
1703    /// The advance of each font's `0` (CSS's `ch`), by family, size,
1704    /// weight and italic.
1705    zero_advances: rustc_hash::FxHashMap<(Option<crate::style::FontFamily>, u32, u16, bool), f32>,
1706    /// Nodes with lengths in `ch` styled since the last commit, perhaps
1707    /// before the views around them (and their fonts) were in place
1708    /// ([`Core::sync_ch`]).
1709    ch_styled: Vec<(Key, NodeId)>,
1710    /// Nodes reading font-relative lengths, so ordinary inserts do no extra walk.
1711    ch_readers: usize,
1712    /// Nodes whose inherited text color changed since they were styled
1713    /// with it (`currentColor`; [`Core::sync_colors`]).
1714    color_changed: Vec<(Key, NodeId)>,
1715    /// The user's preferred text size (1.0 is the default).
1716    font_scale: f32,
1717    /// The font text is drawn with unless it sets its own: the tokens'
1718    /// `font-sans` (`None`: the system's), as a page's is Tailwind's
1719    /// `--font-sans`.
1720    default_font: Option<crate::style::FontFamily>,
1721    queue: Vec<Key>,
1722    /// Parents whose children moved, each once: their children's positions
1723    /// are looked at before the next flush (`classes.rs` `flush_positions`),
1724    /// once however many joined or left.
1725    position_parents: Vec<Key>,
1726    needs_layout: bool,
1727    /// Parsed classes and the theme.
1728    tailwind: Tailwind,
1729    /// Resolved class styles shared by the nodes whose classes resolve alike
1730    /// (the same `ClassList` under the same inputs it reads,
1731    /// `classes::ResolvedKey`).
1732    resolved_styles:
1733        rustc_hash::FxHashMap<classes::ResolvedKey, std::rc::Rc<classes::ResolvedClassStyle>>,
1734    /// Tests resolve every class style afresh, to compare with the cache.
1735    #[cfg(test)]
1736    resolve_uncached: bool,
1737    /// What class variants read from the environment (`dark` as shown:
1738    /// [`Core::set_appearance`]).
1739    class_env: ClassEnvironment,
1740    /// The appearance the app asked for.
1741    appearance: crate::platform::Appearance,
1742    /// The platform reports dark appearance.
1743    system_dark: bool,
1744    /// [`Core::set_max_nodes`].
1745    max_nodes: usize,
1746    /// Raw text runs may go without nodes ([`Core::runs`]).
1747    fold_runs: bool,
1748    /// What the app may reach ([`Core::set_access`]).
1749    access: Arc<crate::access::Access>,
1750    /// What media sources starting with `//` resolve against
1751    /// ([`Core::set_base_url`]).
1752    base_url: Option<Arc<str>>,
1753    /// The roots local media files are read under
1754    /// ([`Core::set_media_files`]).
1755    media_files: Arc<crate::access::MediaFiles>,
1756    /// What the check answered for the network images canvases draw, by
1757    /// source: a canvas checks its images on every draw. Only answers that
1758    /// depend on nothing but the grant and the base, which clear it when
1759    /// they change; local files are resolved on every draw.
1760    canvas_images: rustc_hash::FxHashMap<Arc<str>, Option<Arc<str>>>,
1761    /// Denials already logged (each once).
1762    denied: rustc_hash::FxHashSet<String>,
1763    /// The windows' attribute records, by root node (the main window's is
1764    /// the root's): what was sent the platform and what was set since.
1765    windows: rustc_hash::FxHashMap<NodeId, crate::desktop::window::WindowRecord>,
1766    /// The windows of the app's own, by the app's id: their root nodes,
1767    /// and whether their placement is kept.
1768    window_ids: rustc_hash::FxHashMap<String, (NodeId, bool)>,
1769    /// Explicit quit mode set by the app (`nsh.json` `application.quitMode`,
1770    /// `Application.setQuitMode`, [`Core::set_quit_mode`]); `None` until
1771    /// the app chooses one.
1772    quit_mode: Option<crate::desktop::QuitMode>,
1773    /// Fallback quit mode when the app has not set one:
1774    /// [`crate::desktop::QuitMode::Explicit`] in a bare core,
1775    /// [`crate::desktop::QuitMode::Platform`] in an engine host.
1776    default_quit_mode: crate::desktop::QuitMode,
1777    /// nsh.json's `"window"` launch defaults ([`Core::set_main_window`]):
1778    /// the first app window inherits them, since the host has no visible
1779    /// window of its own.
1780    main_window_options: Option<crate::desktop::MainWindowOptions>,
1781    /// The launch defaults were given to the first window that opened this
1782    /// run: a later window after every window closed is not the first.
1783    launch_defaults_applied: bool,
1784    /// The main window's placement is kept (nsh.json `window.restoreBounds`,
1785    /// [`Core::set_main_window`]).
1786    keep_main_placement: bool,
1787    /// The main window has been on screen, or it opens shown: its reports
1788    /// are where the user left it ([`Core::keep_window_placement`]).
1789    main_shown: bool,
1790    /// Serves the app's clipboard calls in place of the platform
1791    /// ([`Core::set_clipboard`]).
1792    clipboard: Option<Arc<dyn crate::clipboard::ClipboardBackend>>,
1793    /// Answers the app's picks in place of the platform's picker
1794    /// ([`Core::set_picker`]).
1795    picker: Option<Arc<dyn crate::picker::PickerBackend>>,
1796    /// Opens and applies the app's windows of its own in place of the
1797    /// platform ([`Core::set_window_backend`]).
1798    window_backend: Option<Arc<dyn crate::desktop::WindowBackend>>,
1799    /// Plays the app's sound in place of the platform ([`Core::set_audio`]).
1800    audio: Option<Arc<dyn crate::audio::AudioBackend>>,
1801    /// The app's login item ([`Core::set_login_item`]); without one the app
1802    /// has none.
1803    login_item: Option<crate::desktop::LoginItems>,
1804    /// Rust components and what they rendered.
1805    components: components::Components,
1806    /// Overlay nodes, those shown in the order they were shown (the last
1807    /// on top).
1808    overlays: Vec<Key>,
1809    /// What the shown overlays listen to.
1810    overlay_state: overlay::Overlays,
1811}
1812
1813impl<M: TextEngine + 'static> Core<M> {
1814    /// Creates a core whose root view (id [`ROOT_ID`]) fills `viewport`.
1815    pub fn new(text_engine: M, viewport: Size<Points>) -> Self {
1816        let mut core = Self::with_engine(text_engine, viewport);
1817        core.geometry_engine = Some(core.text_engine.clone());
1818        // Components that run once measure text with it.
1819        let engine = core.text_engine.clone();
1820        core.components
1821            .runtime
1822            .set_measure(Rc::new(move |font, text| {
1823                crate::canvas::line_metrics(&*engine, font, text)
1824            }));
1825        core
1826    }
1827}
1828
1829impl<M: TextEngine> Core<M> {
1830    fn with_engine(text_engine: M, viewport: Size<Points>) -> Self {
1831        let mut layout = LayoutTree::with_capacity(256);
1832        let root_layout = layout.new_leaf(root_style(viewport));
1833        let mut nodes = Slab::with_capacity(256);
1834        let mut root = Node::new(ROOT_ID, Kind::View);
1835        root.layout = Some(root_layout);
1836        // The platform owns the root view.
1837        root.created = true;
1838        let root = nodes.insert(root) as Key;
1839        layout.set_tag(root_layout, root);
1840        // The root's size is the viewport's, in a terminal too.
1841        layout.set_role(
1842            root_layout,
1843            terminal_layout::Role {
1844                root: true,
1845                ..terminal_layout::Role::default()
1846            },
1847        );
1848        let mut slots = crate::id_table::IdTable::new();
1849        slots.insert(ROOT_ID as usize, root);
1850        Self {
1851            nodes,
1852            admitted_id_extent: slots.extent(),
1853            slots,
1854            layout,
1855            text_engine: Rc::new(text_engine),
1856            geometry_engine: None,
1857            geometries: Default::default(),
1858            measure_cache: MeasureCache::default(),
1859            resizing_commit: 0,
1860            resize_settling: false,
1861            pending_text: Vec::new(),
1862            attachment_blocks: Vec::new(),
1863            max_nodes: usize::MAX,
1864            fold_runs: true,
1865            access: Arc::default(),
1866            base_url: None,
1867            media_files: Arc::default(),
1868            canvas_images: Default::default(),
1869            denied: Default::default(),
1870            windows: Default::default(),
1871            window_ids: Default::default(),
1872            runs: Default::default(),
1873            folded: Default::default(),
1874            // Until the host or app sets one: a bare core keeps running
1875            // (the engine sets the default `"platform"` and any explicit
1876            // `application.quitMode` before the app runs).
1877            quit_mode: None,
1878            default_quit_mode: crate::desktop::QuitMode::Explicit,
1879            main_window_options: None,
1880            launch_defaults_applied: false,
1881            keep_main_placement: false,
1882            main_shown: false,
1883            clipboard: None,
1884            picker: None,
1885            window_backend: None,
1886            audio: None,
1887            login_item: None,
1888            components: components::Components::for_viewport(viewport),
1889            lists: Vec::new(),
1890            parent_lists: Vec::new(),
1891            outer_moved: false,
1892            extent_changed: false,
1893            culls_content: true,
1894            culling: Vec::new(),
1895            cull_dirty: false,
1896            reach: crate::animation::Reach::default(),
1897            cull_made: false,
1898            cells_framed: false,
1899            cull_scratch: Vec::new(),
1900            pace: pace::Pace::default(),
1901            list_motion: list_motion::ListMotion::default(),
1902            placeholders: Vec::new(),
1903            asked_rows: Vec::new(),
1904            placeholders_resized: false,
1905            outer_asked: Vec::new(),
1906            sticky_views: Vec::new(),
1907            sticky_nodes: Vec::new(),
1908            sticky_scrollers: Vec::new(),
1909            builtin_scrollbars: None,
1910            scrollbars_pending: Vec::new(),
1911            watched_inputs: Vec::new(),
1912            fitted_pending: Vec::new(),
1913            decorated: Vec::new(),
1914            sticky_changed: false,
1915            followers: Vec::new(),
1916            relators: Vec::new(),
1917            follow_changed: false,
1918            sticky_warned: false,
1919            inset_warned: false,
1920            shaders: Default::default(),
1921            web_unchecked: Default::default(),
1922            transition_starts: Vec::new(),
1923            pictured: Default::default(),
1924            unlinked_from: Vec::new(),
1925            roots: Vec::new(),
1926            accessories: Default::default(),
1927            header_heights: (Points(44.0), Points(96.0)),
1928            safe_area: EdgeInsets::default(),
1929            overlay_bounds: None,
1930            snap_to_window_margin: crate::overlay::DEFAULT_SNAP_TO_WINDOW_MARGIN,
1931            list_binds: Vec::new(),
1932            kept_lists: Vec::new(),
1933            selection_kept: Vec::new(),
1934            kept_scratch: Vec::new(),
1935            paced_lists: Vec::new(),
1936            paced_scratch: Vec::new(),
1937            events: Vec::new(),
1938            cells_scratch: Vec::new(),
1939            awaiting_renders: Vec::new(),
1940            root,
1941            viewport,
1942            mount: Vec::new(),
1943            track_tree_order: false,
1944            tree_order_changed: false,
1945            tab_places_stale: false,
1946            key_ancestry_dirty: false,
1947            mount_projected: false,
1948            batches: 0,
1949            retags: None,
1950            commands: Vec::new(),
1951            focus_back: None,
1952            focus_origins: Vec::new(),
1953            pointer_focus_back: None,
1954            layout_animation: None,
1955            scoped_layout: Vec::new(),
1956            resized: Vec::new(),
1957            restructured: Vec::new(),
1958            env_styled: Default::default(),
1959            env_scratch: Vec::new(),
1960            keyboard_moved: false,
1961            status_bar_nodes: Vec::new(),
1962            status_bars_moved: false,
1963            orientation_pages: Vec::new(),
1964            orientations_shown: 0,
1965            pointer_none_classes: 0,
1966            pointer_pending: Vec::new(),
1967            slop_moved: Vec::new(),
1968            focus: None,
1969            focus_chain: Vec::new(),
1970            focus_scratch: Vec::new(),
1971            focus_moved: false,
1972            blur_held: false,
1973            focus_within_changed: false,
1974            modality: None,
1975            focus_visible: false,
1976            focus_by_keyboard: false,
1977            focus_by_pointer: false,
1978            pointer_keymap: None,
1979            restoring_modal_focus: false,
1980            modals_opened: Vec::new(),
1981            modal_focus_given: None,
1982            focus_visible_on: None,
1983            focus_visible_moved: false,
1984            projected_focus: Vec::new(),
1985            pressed_impulses: Vec::new(),
1986            passed_hovers: Default::default(),
1987            fixed_changed: Vec::new(),
1988            zero_advances: Default::default(),
1989            ch_styled: Vec::new(),
1990            ch_readers: 0,
1991            color_changed: Vec::new(),
1992            font_scale: 1.0,
1993            default_font: None,
1994            queue: Vec::new(),
1995            position_parents: Vec::new(),
1996            needs_layout: true,
1997            tailwind: Tailwind::new(),
1998            resolved_styles: rustc_hash::FxHashMap::default(),
1999            #[cfg(test)]
2000            resolve_uncached: false,
2001            class_env: ClassEnvironment::default(),
2002            appearance: crate::platform::Appearance::System,
2003            system_dark: false,
2004            overlays: Vec::new(),
2005            overlay_state: overlay::Overlays::default(),
2006        }
2007    }
2008
2009    /// Sets the height of the platform's screen header bar, normal and with
2010    /// a large title (status bar excluded).
2011    pub fn set_header_heights(&mut self, normal: Points, large: Points) {
2012        if self.header_heights != (normal, large) {
2013            self.header_heights = (normal, large);
2014            self.needs_layout = true;
2015        }
2016    }
2017
2018    /// Sets the surface's safe-area insets.
2019    pub fn set_safe_area(&mut self, insets: EdgeInsets) {
2020        if self.safe_area != insets {
2021            self.safe_area = insets;
2022            self.needs_layout = true;
2023        }
2024    }
2025
2026    /// Where the root view's anchored overlays may be placed, in its
2027    /// coordinates, when the platform shows them beyond the root view: the
2028    /// web's `overlays: "viewport"` draws them over the browser window, so
2029    /// this is the window's rectangle (less its safe area) relative to the
2030    /// container. They are placed and flipped within it, less their
2031    /// `margin`, rather than within the root view's safe area. `None` (the
2032    /// default) keeps them to the root view. Overlays without an anchor
2033    /// and those of modals are laid out as before.
2034    pub fn set_overlay_area(&mut self, area: Option<crate::geometry::Bounds<Points>>) {
2035        if self.overlay_bounds == area {
2036            return;
2037        }
2038        self.overlay_bounds = area;
2039        // Their room changed: laid out and placed again. With none shown
2040        // the next one is placed in it as it shows.
2041        if self.root_overlay_shown() {
2042            self.needs_layout = true;
2043        }
2044    }
2045
2046    /// The distance the overlays without a `margin` of their own (menus,
2047    /// popovers, tooltips, popups) keep from the edges of the window's
2048    /// safe area ([`crate::element::set_snap_to_window_margin`]): they are placed,
2049    /// flipped and shrunk within it, so none touches the window's edge.
2050    pub fn set_snap_to_window_margin(&mut self, margin: Points) {
2051        let margin = Points(margin.0.max(0.0));
2052        if self.snap_to_window_margin == margin {
2053            return;
2054        }
2055        self.snap_to_window_margin = margin;
2056        for (_, node) in &mut self.nodes {
2057            if let Some(root) = node.root.as_mut()
2058                && let Some(overlay) = root.overlay.as_mut()
2059                && !overlay.margin_set
2060            {
2061                overlay.placed = None;
2062                root.laid_out = None;
2063            }
2064        }
2065        self.needs_layout = true;
2066    }
2067
2068    /// The platform presents root `id` (a modal) at `size`, with `insets`
2069    /// of it covered by system UI.
2070    pub fn set_root_size(&mut self, id: NodeId, size: Size<Points>, insets: EdgeInsets) {
2071        let Ok(key) = self.key(id) else { return };
2072        if let Some(root) = self.nodes[key as usize].root.as_mut()
2073            && (root.reported != Some(size) || root.insets != insets)
2074        {
2075            root.reported = Some(size);
2076            root.insets = insets;
2077            self.needs_layout = true;
2078        }
2079    }
2080
2081    /// The platform measured where the content of screen `id` starts below
2082    /// the header it shows (`None`: estimate it from the bar's height and
2083    /// the safe area). Used for screens that lay their content out below
2084    /// the header (not large titles or transparent headers).
2085    pub fn set_screen_header(&mut self, id: NodeId, height: Option<Points>) {
2086        let Ok(key) = self.key(id) else { return };
2087        let height = height.map(|h| h.0).filter(|h| h.is_finite() && *h >= 0.0);
2088        if let Some(root) = self.nodes[key as usize].root.as_mut()
2089            && root.header != height
2090        {
2091            root.header = height;
2092            self.needs_layout = true;
2093        }
2094    }
2095
2096    /// Sets the user's preferred text size (1.0 is the default): text that
2097    /// allows font scaling is laid out again.
2098    pub fn set_font_scale(&mut self, scale: f32) {
2099        let scale = if scale.is_finite() && scale > 0.0 {
2100            scale
2101        } else {
2102            1.0
2103        };
2104        if scale == self.font_scale {
2105            return;
2106        }
2107        self.font_scale = scale;
2108        self.ch_changed(self.root);
2109        self.relayout_text();
2110    }
2111
2112    /// Sets the font text is drawn with unless it sets its own (the
2113    /// tokens' `font-sans`): text is laid out again.
2114    pub(crate) fn set_default_font(&mut self, family: Option<crate::style::FontFamily>) {
2115        if family == self.default_font {
2116            return;
2117        }
2118        self.default_font = family;
2119        self.ch_changed(self.root);
2120        self.relayout_text();
2121    }
2122
2123    /// Lays every text and input out again.
2124    fn relayout_text(&mut self) {
2125        let blocks: Vec<(Key, Kind)> = self
2126            .nodes
2127            .iter()
2128            .filter(|(_, n)| matches!(n.kind, Kind::Text | Kind::Input) && !n.inline)
2129            .map(|(k, n)| (k as Key, n.kind))
2130            .collect();
2131        for (key, kind) in blocks {
2132            if kind == Kind::Text {
2133                self.mark(key, dirty::TEXT_BUILD);
2134            } else {
2135                self.measure_input(key);
2136                self.mark(key, dirty::INPUT);
2137            }
2138        }
2139    }
2140
2141    /// The pixel ratio went from `old` to `new`: the images whose variant
2142    /// changes are sent again (their layout does not change).
2143    fn repick_images(&mut self, old: f32, new: f32) {
2144        let changes = |s: &Option<ImageSource>| {
2145            s.as_ref()
2146                .is_some_and(|s| !s.scales.is_empty() && s.variant(old) != s.variant(new))
2147        };
2148        let images: Vec<Key> = self
2149            .nodes
2150            .iter()
2151            .filter(|(_, n)| {
2152                n.image
2153                    .as_ref()
2154                    .is_some_and(|i| changes(&i.source) || changes(&i.options.placeholder))
2155            })
2156            .map(|(k, _)| k as Key)
2157            .collect();
2158        for key in images {
2159            self.mark(key, dirty::IMAGE);
2160        }
2161    }
2162
2163    /// Number of live nodes, including the root.
2164    pub fn node_count(&self) -> usize {
2165        self.nodes.len()
2166    }
2167
2168    /// How many node ids the core's id table has room for: far above
2169    /// [`Self::node_count`] when the ids of nodes that are gone still take
2170    /// room (diagnostics).
2171    pub fn node_id_room(&self) -> usize {
2172        self.slots.len()
2173    }
2174
2175    /// Sets what the app may reach: remote images, canvas images, video
2176    /// sources, web views and the status bar are checked against it.
2177    pub fn set_access(&mut self, access: Arc<crate::access::Access>) {
2178        // `open_window` checks windows as `Window.open` does.
2179        {
2180            let _entered = self.components.runtime.enter();
2181            crate::element::global::<crate::element::desktop::WindowAccess>()
2182                .set(crate::element::desktop::WindowAccess(Some(access.clone())));
2183        }
2184        self.components.runtime.set_access(access.clone());
2185        self.access = access;
2186        self.canvas_images.clear();
2187    }
2188
2189    /// Sets the URL media sources starting with `//` resolve against, whose
2190    /// scheme they take (the page's on the web, as `fetch`'s relative
2191    /// URLs). Without one such a source names no URL, and only an app
2192    /// without capabilities loads it ([`crate::access::Access::media_url`]).
2193    /// A base marks a page: with one, `/x` and relative paths are the
2194    /// page's, not local files, so only pages set one.
2195    pub fn set_base_url(&mut self, url: Option<Arc<str>>) {
2196        self.base_url = url;
2197        self.canvas_images.clear();
2198    }
2199
2200    /// Sets the `capabilities.fs.read` roots the app's local media files
2201    /// (absolute paths, `file:` URLs) are read under; without them such a
2202    /// source of an app with capabilities loads nothing
2203    /// ([`crate::access::Access::media_url`]).
2204    pub fn set_media_files(&mut self, files: Arc<crate::access::MediaFiles>) {
2205        self.media_files = files;
2206        self.canvas_images.clear();
2207    }
2208
2209    /// Sets what the core's own image loads (an [`crate::element::svg`]'s
2210    /// bytes) go through: the app's bundled files, access policy and disk
2211    /// cache. Without it they read inline bytes, files and `asset:/` URIs
2212    /// of no base only.
2213    #[cfg(not(target_arch = "wasm32"))]
2214    pub fn set_image_context(&mut self, context: crate::image::loader::Context) {
2215        crate::image::loader::set_context(context);
2216    }
2217
2218    /// Serves the app's clipboard calls from `backend` instead of the
2219    /// platform's clipboard (`None`: the platform's, the default).
2220    pub fn set_clipboard(&mut self, backend: Option<Arc<dyn crate::clipboard::ClipboardBackend>>) {
2221        self.clipboard = backend;
2222    }
2223
2224    /// Answers the app's picks (`Picker.pickImages`) with `backend`, an
2225    /// embedding app's own picker or a test's files, instead of showing the
2226    /// platform's picker (`None`: the platform's, the default).
2227    pub fn set_picker(&mut self, backend: Option<Arc<dyn crate::picker::PickerBackend>>) {
2228        self.picker = backend;
2229    }
2230
2231    /// Sets an explicit quit mode when the app's last window closes
2232    /// (`nsh.json` `application.quitMode`, `Application.setQuitMode`).
2233    /// Overrides the implicit main window's default quit-on-close behavior.
2234    pub fn set_quit_mode(&mut self, mode: crate::desktop::QuitMode) {
2235        self.quit_mode = Some(mode);
2236    }
2237
2238    /// Sets the host's default quit mode when the app has not explicitly
2239    /// configured one: explicit `<Window>` scenes follow this mode, while a
2240    /// plain root's implicit main window still quits on close. Engine
2241    /// plumbing, not app API.
2242    #[doc(hidden)]
2243    pub fn __set_default_quit_mode(&mut self, mode: crate::desktop::QuitMode) {
2244        self.default_quit_mode = mode;
2245    }
2246
2247    /// The main window's launch-time options (nsh.json `"window"`): its
2248    /// attributes go to the main window with the next commit, as
2249    /// `currentWindow().set()` sends them (capabilities apply); with
2250    /// `restoreBounds` its placement is kept from then on as the platform
2251    /// reports it (the environment's window state), for the next launch
2252    /// to open it there ([`crate::desktop::MainWindowOptions::kept_placement`]).
2253    /// Set it after the environment ([`Core::set_environment`]): a surface
2254    /// without a window, a phone's, takes no attributes.
2255    pub fn set_main_window(&mut self, options: &crate::desktop::MainWindowOptions) {
2256        self.main_window_options = Some(options.clone());
2257        self.keep_main_placement = options.restore_bounds;
2258        self.main_shown |= options.visible_at_launch();
2259        if let Some(state) = self.components.environment.window_state {
2260            self.keep_window_placement(crate::ROOT_ID, &state);
2261        }
2262        if options.attributes.is_empty() {
2263            return;
2264        }
2265        // The launch defaults are the host's, read before the app runs:
2266        // they are not the sandboxed app acting on the main window.
2267        if self.key(crate::ROOT_ID).is_ok() {
2268            self.window_command(
2269                crate::ROOT_ID,
2270                crate::desktop::DesktopCommand::SetAttributes(Box::new(options.attributes.clone())),
2271                true,
2272            );
2273        }
2274    }
2275
2276    /// Opens and applies the app's windows of its own with `backend`, an
2277    /// embedding host's windows or a test's fake, instead of the platform
2278    /// (`None`: the platform's, the default). The main window's commands
2279    /// stay with the platform.
2280    pub fn set_window_backend(&mut self, backend: Option<Arc<dyn crate::desktop::WindowBackend>>) {
2281        self.window_backend = backend;
2282    }
2283
2284    /// Plays the app's sound (`Sound`, `AudioPlayer`) with `backend`, an
2285    /// embedding app's own audio stack or a test's fake, instead of the
2286    /// platform's (`None`: the platform's, the default).
2287    pub fn set_audio(&mut self, backend: Option<Arc<dyn crate::audio::AudioBackend>>) {
2288        self.audio = backend;
2289    }
2290
2291    /// Reads and changes the app's login item (`Application.launchAtLogin`)
2292    /// with `backend`: the platform's, which a standalone app's runner gives,
2293    /// or a test's fake. `None` (the default): the app has no login item,
2294    /// it does not launch at login ([`crate::desktop::LoginItemBackend`]).
2295    pub fn set_login_item(&mut self, backend: Option<Arc<dyn crate::desktop::LoginItemBackend>>) {
2296        self.login_item = backend.map(crate::desktop::LoginItems::new);
2297    }
2298
2299    /// Keeps the app's storage (`nsh/storage`) in `backend`; `None`: in
2300    /// memory, for the core's life.
2301    pub fn set_storage(&mut self, backend: Option<Arc<dyn crate::storage::StorageBackend>>) {
2302        self.components
2303            .runtime
2304            .set_storage(crate::storage::Store::new(backend));
2305    }
2306
2307    /// The app's own data directory, what [`crate::element::data_dir`]
2308    /// gives; `None`: it has none.
2309    pub fn set_data_dir(&mut self, dir: Option<std::path::PathBuf>) {
2310        self.components.runtime.set_data_dir(dir);
2311    }
2312
2313    /// The app as it was built, what [`crate::element::app_info`] answers
2314    /// (a Rust app's root's, [`crate::element::Root::app_info`]); `None`:
2315    /// the runner has none (a TSX app's is JS's `appInfo()`).
2316    pub fn set_app_info(&mut self, info: Option<crate::platform::AppInfo>) {
2317        self.components.runtime.set_app_info(info);
2318    }
2319
2320    /// What Rust code checks for updates with
2321    /// ([`crate::runtime::prompt_for_update`]); `None`: the app does not
2322    /// update. A JS app's VM gets its own ([`crate::element::System`]).
2323    pub fn set_updater(
2324        &mut self,
2325        updater: Option<std::sync::Arc<dyn crate::runtime::UpdaterHost>>,
2326    ) {
2327        self.components.runtime.set_updater(updater);
2328    }
2329
2330    /// Logs (once) that the app was refused `what`.
2331    fn deny(&mut self, what: String) {
2332        if self.denied.len() < 256 && self.denied.insert(what.clone()) {
2333            log::warn!(target: "js", "{what}");
2334        }
2335    }
2336
2337    /// Caps the number of nodes (each may hold a native view, whose memory
2338    /// no JS heap limit covers): creating more is a fatal [`ApplyError`].
2339    pub fn set_max_nodes(&mut self, max: usize) {
2340        self.max_nodes = max.max(1);
2341    }
2342
2343    /// A burst of resizes began (`true`) or ended. Meanwhile only text near
2344    /// the screen is measured and laid out at new widths: what is far from
2345    /// it keeps its height, and catches up in the commit after the end. A
2346    /// window's drag gets its frames from what the user sees; a long page
2347    /// has far more text than the screen shows.
2348    pub fn set_resizing(&mut self, resizing: bool) {
2349        if resizing == self.measure_cache.resizing.is_some() {
2350            return;
2351        }
2352        if resizing {
2353            self.resizing_commit = self.resizing_commit.wrapping_add(1).max(1);
2354            self.measure_cache.resizing = Some(self.resizing_commit);
2355            return;
2356        }
2357        self.measure_cache.resizing = None;
2358        let keys: Vec<(Key, LayoutId)> = self
2359            .nodes
2360            .iter()
2361            .filter_map(|(key, node)| Some((key as Key, node.layout?)))
2362            .collect();
2363        for (key, layout) in keys {
2364            let Some(LeafContext::Text(cx)) = self.layout.get_node_context_mut(layout) else {
2365                continue;
2366            };
2367            if std::mem::take(&mut cx.held) {
2368                self.layout.mark_dirty(layout);
2369                self.needs_layout = true;
2370                self.resize_settling = true;
2371                self.queue_text(key);
2372            }
2373        }
2374    }
2375
2376    /// Marks the text within a screen's height of the screen, from where
2377    /// the last commit put the views, for this commit of a resize. A text
2378    /// it finds after waiting catches up now.
2379    fn mark_near_screen(&mut self) {
2380        self.resizing_commit = self.resizing_commit.wrapping_add(1).max(1);
2381        self.measure_cache.resizing = Some(self.resizing_commit);
2382        let (width, height) = (self.viewport.width.0, self.viewport.height.0);
2383        let mut stack = vec![(self.root, 0.0f32, 0.0f32)];
2384        while let Some((key, x, y)) = stack.pop() {
2385            let node = &self.nodes[key as usize];
2386            let frame = node.frame;
2387            let (mut x, mut y) = (x, y);
2388            // Not placed yet, or of no size around what overflows it: no
2389            // telling, so it counts as near.
2390            // (`Bounds::UNSET` is NaN.)
2391            if !frame.origin.x.0.is_nan() {
2392                x += frame.origin.x.0;
2393                y += frame.origin.y.0;
2394                let (w, h) = (frame.size.width.0, frame.size.height.0);
2395                let sized = w > 0.0 && h > 0.0;
2396                if sized
2397                    && (x + w < -width || x > 2.0 * width || y + h < -height || y > 2.0 * height)
2398                {
2399                    continue;
2400                }
2401            }
2402            if let Some(scroll) = node.scroll.as_deref() {
2403                x -= scroll.offset.0;
2404                y -= scroll.offset.1;
2405            }
2406            stack.extend(node.children.iter().map(|&child| (child, x, y)));
2407            if let Some(layout) = node.layout
2408                && let Some(LeafContext::Text(cx)) = self.layout.get_node_context_mut(layout)
2409            {
2410                cx.near_screen = self.resizing_commit;
2411                if std::mem::take(&mut cx.held) {
2412                    self.layout.mark_dirty(layout);
2413                    self.queue_text(key);
2414                }
2415            }
2416        }
2417    }
2418
2419    /// Changes the size of the root view.
2420    pub fn set_viewport(&mut self, viewport: Size<Points>) {
2421        if viewport != self.viewport {
2422            self.viewport = viewport;
2423            self.resize_settling = true;
2424            let root = self.nodes[self.root as usize].layout.expect("root layout");
2425            self.layout.set_style(root, root_style(viewport));
2426            self.needs_layout = true;
2427            // Restyles what follows the window's size (`apply_environment`).
2428            self.components_viewport(viewport);
2429        }
2430    }
2431
2432    /// The platform scrolled a scroll view or list to `(x, y)`, having
2433    /// applied `applied` of the scrolls the core issued to it
2434    /// (`MountItem::ScrollBy` and `Command::ScrollTo` of lists).
2435    pub fn set_scroll_offset(&mut self, id: NodeId, offset: Point<Points>, applied: u32) {
2436        let (x, y) = (offset.x.0, offset.y.0);
2437        let Ok(key) = self.key(id) else { return };
2438        let node = &mut self.nodes[key as usize];
2439        let horizontal = node.scroll.as_ref().is_some_and(|s| s.horizontal);
2440        let mut dependents = false;
2441        let mut moved = false;
2442        if let Some(scroll) = node.scroll.as_mut() {
2443            moved = scroll.offset != (x, y);
2444            // A scroll the core sent is a jump, not the user's motion.
2445            let issued = scroll.target.is_some_and(|(n, _)| n <= applied);
2446            scroll.step = match issued {
2447                true => (0.0, 0.0),
2448                false => (x - scroll.offset.0, y - scroll.offset.1),
2449            };
2450            scroll.offset = (x, y);
2451            if issued {
2452                scroll.target = None;
2453            }
2454            if !scroll.dependents.is_empty() {
2455                scroll.pending.retain(|&(n, _)| n > applied);
2456                dependents = true;
2457            }
2458        }
2459        if let Some(list) = node.list.as_mut() {
2460            list.reported(if horizontal { x } else { y }, applied);
2461        }
2462        self.cull_moved(key);
2463        if dependents {
2464            self.dependents_dirty(key);
2465        }
2466        // Views that follow an element in what it scrolls go with it
2467        // (`follow.rs`).
2468        self.follow_changed |= moved && !self.followers.is_empty();
2469        // A link's hint placed where the pointer came over it would be left
2470        // behind by the content (`Core::overlay_scrolled`).
2471        if moved && !self.overlays.is_empty() {
2472            self.overlay_scrolled(key);
2473        }
2474    }
2475
2476    /// The user moved scroll view `id` with scroll key move `key_move`, which
2477    /// the platform animates to what it knows of the content. On a list of its
2478    /// own End queues an animated `scrollToEnd`, in order with the app's
2479    /// scroll commands, so the list follows its end and rows below that
2480    /// were never rendered, sized by their estimate, do not stop it short;
2481    /// a repeat while the list follows its end changes nothing. Any other
2482    /// key takes back an End not resolved yet and ends the target the list
2483    /// followed, as the user scrolling away does. Lists in their parent's
2484    /// viewport and inverted lists are left to the platform.
2485    pub fn key_scrolled(&mut self, id: NodeId, key_move: crate::scroll::KeyMove) {
2486        let Ok(key) = self.key(id) else { return };
2487        let queued = self.commands.iter().filter(|(to, _)| *to == id).count() as u32;
2488        let Some(list) = self.nodes[key as usize].list.as_mut() else {
2489            return;
2490        };
2491        if !list.follows_end_key() {
2492            return;
2493        }
2494        if key_move == crate::scroll::KeyMove::End {
2495            // A repeat: the last scroll queued or followed is the end.
2496            let repeat = match list.key_ends.last() {
2497                Some(&n) => n + 1 == queued,
2498                None => queued == 0 && list.follows_end(),
2499            };
2500            if !repeat {
2501                list.key_ends.push(queued);
2502                self.commands
2503                    .push((id, Command::ScrollToEnd { animated: true }));
2504            }
2505            return;
2506        }
2507        list.unpin();
2508        let ends = std::mem::take(&mut list.key_ends);
2509        // The latest first, so the places of the earlier ones hold.
2510        for &n in ends.iter().rev() {
2511            let at = self
2512                .commands
2513                .iter()
2514                .enumerate()
2515                .filter(|(_, (to, _))| *to == id)
2516                .nth(n as usize)
2517                .map(|(at, _)| at);
2518            if let Some(at) = at {
2519                self.commands.remove(at);
2520            }
2521        }
2522    }
2523
2524    /// Keeps the rows of virtual lists that hold `nodes` rendered, out of
2525    /// the render window too, until the next call: the ends of a text
2526    /// selection across a list's rows, whose texts must outlive scrolling
2527    /// away (a recycled cell would show another row). Replaces the last
2528    /// call's; none releases them. The rows holding the keyboard focus or
2529    /// an open overlay are kept anyway ([`Core::sync_kept`]).
2530    pub fn set_kept(&mut self, nodes: &[NodeId]) {
2531        self.selection_kept.clear();
2532        self.selection_kept.extend_from_slice(nodes);
2533        self.sync_kept();
2534    }
2535
2536    /// Keeps the rows of lists rendered wherever they scroll while they
2537    /// hold what must outlive scrolling away: [`Core::set_kept`]'s nodes,
2538    /// the keyboard focus and open overlays (a row's menu or popover). A
2539    /// recycled cell would show another row, drop the focus and close the
2540    /// overlay. Each list's kept rows are all that hold one; in a list in
2541    /// another list's row, both rows are kept. The rows on either side of
2542    /// the focus's are kept with it, so that the platform's Tab and
2543    /// Shift+Tab, which only reach views that exist, move on to the next
2544    /// row in the list rather than past it, however far the window lags
2545    /// (the row the focus reaches then scrolls into view, which renders
2546    /// the rows around it).
2547    fn sync_kept(&mut self) {
2548        let mut holders = std::mem::take(&mut self.kept_scratch);
2549        holders.clear();
2550        holders.extend(
2551            self.selection_kept
2552                .iter()
2553                .filter_map(|&id| self.key(id).ok()),
2554        );
2555        let focus = self
2556            .focus
2557            .filter(|&(key, id)| self.nodes.get(key as usize).is_some_and(|n| n.id == id))
2558            .map(|(key, _)| key);
2559        holders.extend(focus);
2560        holders.extend(self.overlays.iter().copied().filter(|&key| {
2561            self.overlay(key)
2562                .is_some_and(|o| o.host.is_some() && o.config.hint.is_none())
2563        }));
2564        let mut kept: Vec<(Key, u32)> = Vec::new();
2565        for &holder in &holders {
2566            let mut key = holder;
2567            // Up to each cell: an ancestor whose parent is a list holding
2568            // it in a slot.
2569            loop {
2570                let parent = self.nodes[key as usize].parent;
2571                if parent == NO_KEY {
2572                    break;
2573                }
2574                if let Some(list) = self.nodes[parent as usize].list.as_ref()
2575                    && let Some(index) = list
2576                        .slots
2577                        .iter()
2578                        .find(|s| s.cell == key)
2579                        .and_then(|s| s.index)
2580                {
2581                    kept.push((parent, index));
2582                    if focus == Some(holder) {
2583                        if index > 0 {
2584                            kept.push((parent, index - 1));
2585                        }
2586                        if index + 1 < list.count {
2587                            kept.push((parent, index + 1));
2588                        }
2589                    }
2590                }
2591                key = parent;
2592            }
2593        }
2594        self.kept_scratch = holders;
2595        if kept.is_empty() && self.kept_lists.is_empty() {
2596            return;
2597        }
2598        let mut lists: Vec<Key> = kept.iter().map(|&(list, _)| list).collect();
2599        lists.sort_unstable();
2600        lists.dedup();
2601        for &list in self.kept_lists.iter().filter(|l| !lists.contains(l)) {
2602            if let Some(state) = self
2603                .nodes
2604                .get_mut(list as usize)
2605                .and_then(|n| n.list.as_mut())
2606            {
2607                state.set_kept(Vec::new());
2608            }
2609        }
2610        for &list in &lists {
2611            let items = kept
2612                .iter()
2613                .filter(|&&(l, _)| l == list)
2614                .map(|&(_, i)| i)
2615                .collect();
2616            if let Some(state) = self.nodes[list as usize].list.as_mut() {
2617                state.set_kept(items);
2618            }
2619        }
2620        self.kept_lists = lists;
2621    }
2622
2623    /// The platform scrolled the text of multiline input `id` to `offset`,
2624    /// its text `content` large in a `viewport` (reported while a built-in
2625    /// bar or a scroll watch follows it, `InputConfig::report_scroll`).
2626    pub fn set_input_scroll(
2627        &mut self,
2628        id: NodeId,
2629        offset: Point<Points>,
2630        content: Size<Points>,
2631        viewport: Size<Points>,
2632    ) {
2633        let Ok(key) = self.key(id) else { return };
2634        if let Some(input) = self.nodes[key as usize].input.as_mut() {
2635            input.scroll = Some(InputScroll {
2636                offset,
2637                content,
2638                viewport,
2639            });
2640        }
2641    }
2642
2643    /// The platform zoomed scroll view `id` to `scale`.
2644    pub fn set_zoom(&mut self, id: NodeId, scale: f32) {
2645        let Ok(key) = self.key(id) else { return };
2646        if let Some(scroll) = self.nodes[key as usize].scroll.as_mut() {
2647            scroll.zoom = scale;
2648        }
2649    }
2650
2651    /// A registered native component reported its own size: it is laid out
2652    /// at it where its style leaves a dimension open.
2653    pub fn set_component_size(&mut self, id: NodeId, size: Size<Points>) {
2654        let Ok(key) = self.key(id) else { return };
2655        let Some(layout) = self.nodes[key as usize].layout else {
2656            return;
2657        };
2658        if let Some(LeafContext::Native(own)) = self.layout.get_node_context_mut(layout)
2659            && *own != Some(size)
2660        {
2661            *own = Some(size);
2662            self.layout.mark_dirty(layout);
2663            self.needs_layout = true;
2664        }
2665    }
2666
2667    /// What `onScroll` reports for scroll view `id`, if it listens to it:
2668    /// the minimum milliseconds between events, the content size (zoomed),
2669    /// the viewport size and the zoom scale.
2670    pub fn scroll_listener(&self, id: NodeId) -> Option<(f32, Size<Points>, Size<Points>, f32)> {
2671        let node = &self.nodes[self.key(id).ok()? as usize];
2672        if !node.events.contains(EventKind::Scroll) {
2673            return None;
2674        }
2675        let scroll = node.scroll.as_ref()?;
2676        let frame = node.frame.size;
2677        let content = scroll.content.unwrap_or(frame);
2678        let z = scroll.zoom;
2679        Some((scroll.event_throttle_ms, content * z, frame, z))
2680    }
2681
2682    /// Moves list render requests produced by the last commit into `out`:
2683    /// what must bind before the frame shows (cells whose item moved, cells
2684    /// in the viewport and just ahead of it). The rest of the overscan
2685    /// waits ([`Core::take_paced_list_binds`]).
2686    pub fn take_list_binds(&mut self, out: &mut Vec<ListBind>) {
2687        out.append(&mut self.list_binds);
2688    }
2689
2690    /// Whether lists have overscan cells waiting to bind.
2691    pub fn has_paced_list_binds(&self) -> bool {
2692        !self.paced_lists.is_empty()
2693    }
2694
2695    /// Hands out up to `cells` of the overscan cells waiting to bind, one
2696    /// per list in turn (a nested list is not starved by its parent), each
2697    /// list's nearest its leading edge first. What a list assigns now is
2698    /// what waits: cells it left or whose items went are never handed out.
2699    pub fn take_paced_list_binds(&mut self, cells: usize, out: &mut Vec<ListBind>) {
2700        let mut left = cells;
2701        let mut lists = std::mem::take(&mut self.paced_lists);
2702        let mut one = std::mem::take(&mut self.paced_scratch);
2703        let start = out.len();
2704        while left > 0 && !lists.is_empty() {
2705            lists.retain(|&id| {
2706                if left == 0 {
2707                    return true;
2708                }
2709                let Some(list) = self
2710                    .key(id)
2711                    .ok()
2712                    .and_then(|key| self.nodes[key as usize].list.as_mut())
2713                else {
2714                    return false;
2715                };
2716                one.clear();
2717                left -= list.take_paced(1, &mut one);
2718                if let Some((slot, index)) = one.pop() {
2719                    match out[start..].iter_mut().find(|b| b.list == id) {
2720                        Some(bind) => bind.binds.push((slot, index)),
2721                        None => out.push(ListBind {
2722                            list: id,
2723                            binds: vec![(slot, index)],
2724                        }),
2725                    }
2726                }
2727                list.has_paced()
2728            });
2729        }
2730        self.paced_lists = lists;
2731        self.paced_scratch = one;
2732    }
2733
2734    /// Whether events wait for [`Core::take_events`].
2735    pub fn has_events(&self) -> bool {
2736        !self.events.is_empty()
2737    }
2738
2739    /// Moves what the core hands JS (events it raised, such as
2740    /// `onLoadMore` and `onLayout`, Rust components' events, calls'
2741    /// results) into `out`, in order.
2742    pub fn take_events(&mut self, out: &mut Vec<crate::element::JsEvent>) {
2743        if !self.asked_rows.is_empty() {
2744            let rows = std::mem::take(&mut self.asked_rows);
2745            self.events.push(crate::element::JsEvent::Rows(rows));
2746        }
2747        out.append(&mut self.events);
2748        // The caller hands them to JS before the next commit: what waits for
2749        // the app's answer to them runs there ([`crate::element::after_answer`]).
2750        self.components.executor.hand_answers();
2751    }
2752
2753    /// Whether the next commit runs closures that waited for the app's
2754    /// answer to events taken already ([`crate::element::after_answer`]):
2755    /// the engine commits again rather than leave them for later input.
2756    pub fn has_due_answers(&self) -> bool {
2757        self.components.executor.has_due_answers()
2758    }
2759
2760    /// Registers a custom font (TrueType, OpenType, WOFF or WOFF2 data) with
2761    /// the text engine. Text measured before is measured again.
2762    pub fn register_font(&mut self, data: &[u8]) -> Result<(), String> {
2763        self.text_engine
2764            .register_font(&crate::text::font_data(data)?)?;
2765        self.fonts_changed();
2766        Ok(())
2767    }
2768
2769    /// The text engine's fonts changed (a font the platform loads
2770    /// asynchronously became usable): text measured before is measured
2771    /// again.
2772    pub fn fonts_changed(&mut self) {
2773        self.zero_advances.clear();
2774        self.ch_changed(self.root);
2775        self.measure_cache.clear();
2776        let blocks: Vec<Key> = self
2777            .nodes
2778            .iter()
2779            .filter(|(_, n)| {
2780                matches!(n.kind, Kind::Text | Kind::Input) && !n.inline && n.layout.is_some()
2781            })
2782            .map(|(k, _)| k as Key)
2783            .collect();
2784        for key in blocks {
2785            let layout = self.nodes[key as usize].layout.expect("text layout");
2786            let cx = self.text_cx(layout);
2787            cx.prepared = None;
2788            cx.min_content = None;
2789            cx.cache = None;
2790            cx.baseline = None;
2791            cx.same_lines = None;
2792            cx.no_ahead = false;
2793            cx.laid_out = None;
2794            if let Some(field) = &mut cx.field {
2795                field.prepared = None;
2796                field.cache = None;
2797            }
2798            self.layout.mark_dirty(layout);
2799            self.needs_layout = true;
2800            if self.nodes[key as usize].kind == Kind::Text {
2801                self.queue_text(key);
2802            } else {
2803                // The platform resolves the input's font again.
2804                self.mark(key, dirty::INPUT);
2805            }
2806        }
2807    }
2808
2809    /// The platform's views must get everything again, as new views do, and
2810    /// text is measured again: the unit the platform converted the values
2811    /// with changed (Android's density). The views stay, scrolled where they
2812    /// are.
2813    pub fn remount(&mut self) {
2814        self.fonts_changed();
2815        let keys: Vec<Key> = self
2816            .nodes
2817            .iter()
2818            .filter(|(_, n)| n.created)
2819            .map(|(k, _)| k as Key)
2820            .collect();
2821        for key in keys {
2822            let flags = self.mount_state(key);
2823            self.mark(key, flags);
2824            let node = &mut self.nodes[key as usize];
2825            if let Some(root) = node.root.as_mut() {
2826                root.laid_out = None;
2827            }
2828            // A scroll view keeps where it is scrolled to: its content size
2829            // goes again as it is, not as a first one (which would put a
2830            // right to left one at its right end). A new size from the
2831            // layout below replaces it ([`Self::set_scroll_content`]).
2832            let id = node.id;
2833            if let Some(scroll) = node.scroll.as_mut()
2834                && let Some(size) = scroll.content
2835            {
2836                scroll.content_item = Some((self.batches, self.mount.len()));
2837                self.mount.push(MountItem::ScrollContent { id, size });
2838            }
2839            if let Some(layout) = node.layout {
2840                // Every frame is sent again.
2841                self.layout.mark_dirty(layout);
2842            }
2843            // Replay pixel-based sticky state without clearing the lists'
2844            // bookkeeping (which would restack their existing cells).
2845            // If layout changes the logical ranges, its later item wins.
2846            let ranges = self.sticky_ranges(key);
2847            if !ranges.is_empty() {
2848                self.mount.push(MountItem::StickyCells {
2849                    id,
2850                    cells: ranges
2851                        .into_iter()
2852                        .map(|r| StickyCell {
2853                            cell: r.cell,
2854                            start: Points(r.start),
2855                            end: Points(r.end),
2856                            offset: r.offset,
2857                        })
2858                        .collect(),
2859                });
2860            }
2861        }
2862        self.needs_layout = true;
2863    }
2864
2865    /// A paste into input `id` (`onPaste`): its files larger than the
2866    /// input's `pasteMaxSize` go to [`crate::PasteEvent::too_large`],
2867    /// whichever platform read them, so every platform gives the app the
2868    /// same files.
2869    pub fn limit_paste(&self, id: NodeId, payload: &mut EventPayload) {
2870        let EventPayload::Paste(paste) = payload else {
2871            return;
2872        };
2873        let max = self
2874            .key(id)
2875            .ok()
2876            .and_then(|key| self.nodes[key as usize].input.as_ref())
2877            .and_then(|input| input.config.paste_max_size);
2878        if let Some(max) = max {
2879            paste.limit_files(max);
2880        }
2881    }
2882
2883    /// The user edited input `id` (before JS sees the edit): keeps the text
2884    /// for layout and for stale-value detection.
2885    pub fn input_changed(&mut self, id: NodeId, text: &str, count: u32) {
2886        let Ok(key) = self.key(id) else { return };
2887        let Some(input) = self.nodes[key as usize].input.as_mut() else {
2888            return;
2889        };
2890        input.count = count;
2891        if input.value != text {
2892            input.value.clear();
2893            input.value.push_str(text);
2894            self.measure_input(key);
2895        }
2896    }
2897
2898    /// An input method composes in input `id`: `shown` is what the input
2899    /// shows meanwhile (its text with the composition at the caret), `None`
2900    /// once the composition ends. The input is measured with it, so it
2901    /// grows as the composition wraps; its value and edit count stay as
2902    /// they are (the platform reports the committed text as an edit).
2903    pub fn input_composing(&mut self, id: NodeId, shown: Option<&str>) {
2904        let Ok(key) = self.key(id) else { return };
2905        let Some(input) = self.nodes[key as usize].input.as_mut() else {
2906            return;
2907        };
2908        if input.composing.as_deref() == shown {
2909            return;
2910        }
2911        input.composing = shown.map(str::to_owned);
2912        self.measure_input(key);
2913    }
2914
2915    /// Applies one op from JS.
2916    pub fn apply(&mut self, op: Op) -> Result<(), ApplyError> {
2917        let _entered = self.components.runtime.enter();
2918        // Ops on a component's host go to its component, calls of a UI
2919        // set's modules to the module; the components learn whether JS
2920        // listens to the back button and JS's shortcuts even before one
2921        // mounts, so a component's own join them rather than replace them.
2922        if self.components.instances.is_empty()
2923            && !matches!(
2924                op,
2925                Op::Command {
2926                    command: Command::Native { .. },
2927                    ..
2928                } | Op::Listen {
2929                    id: ROOT_ID,
2930                    event: EventKind::BackPress | EventKind::BackProgress | EventKind::KeyCommand,
2931                    ..
2932                } | Op::SetProp {
2933                    id: ROOT_ID,
2934                    prop: Prop::Keymap(_),
2935                }
2936            )
2937        {
2938            return self.apply_op(op);
2939        }
2940        match self.intercept(op)? {
2941            Some(op) => self.apply_op(op),
2942            None => Ok(()),
2943        }
2944    }
2945
2946    /// Applies one op as is (also for the nodes components expand).
2947    fn apply_op(&mut self, op: Op) -> Result<(), ApplyError> {
2948        if !self.runs.is_empty()
2949            && let Op::Evaluate { id, .. }
2950            | Op::Draw { id, .. }
2951            | Op::SetStyle { id, .. }
2952            | Op::SetProp { id, .. }
2953            | Op::Listen { id, .. }
2954            | Op::Placeholder { id }
2955            | Op::Command { id, .. } = op
2956        {
2957            self.materialize_run(id)?;
2958        }
2959        match op {
2960            Op::Evaluate {
2961                id,
2962                call,
2963                script,
2964                timeout,
2965            } => {
2966                self.start_js_web_evaluation(id, call, script, timeout);
2967                Ok(())
2968            }
2969            Op::RenderCanvas { call, request } => {
2970                self.start_js_canvas_render(call, *request);
2971                Ok(())
2972            }
2973            Op::Rust(op) => {
2974                self.run_rust(op);
2975                Ok(())
2976            }
2977            Op::Create { id, tag } => self.create(id, tag),
2978            Op::CreateText { id, text } => {
2979                let idx = id as usize;
2980                if self.slots.contains(idx) || self.runs.contains_key(&id) {
2981                    return Err(ApplyError::DuplicateNode(id));
2982                }
2983                self.check_id_range(id)?;
2984                if self.fold_runs {
2985                    if self.nodes.len().saturating_add(self.runs.len()) >= self.max_nodes {
2986                        return Err(ApplyError::TooManyNodes(self.max_nodes));
2987                    }
2988                    self.runs.insert(
2989                        id,
2990                        Run {
2991                            text,
2992                            block: NO_KEY,
2993                        },
2994                    );
2995                    self.admitted_id_extent = self.admitted_id_extent.max(idx.saturating_add(1));
2996                    return Ok(());
2997                }
2998                let key = self.alloc(id, Kind::RawText)?;
2999                self.nodes[key as usize].text = text;
3000                Ok(())
3001            }
3002            Op::SetText { id, text } => {
3003                if let Some(run) = self.runs.get_mut(&id) {
3004                    if run.text != text {
3005                        run.text = text;
3006                        let block = run.block;
3007                        if block != NO_KEY {
3008                            self.mark_text_block(block);
3009                        }
3010                    }
3011                    return Ok(());
3012                }
3013                let key = self.key(id)?;
3014                let node = &mut self.nodes[key as usize];
3015                if node.text != text {
3016                    node.text = text;
3017                    if node.inline {
3018                        self.mark_text_block(key);
3019                    }
3020                }
3021                Ok(())
3022            }
3023            Op::SetStyle { id, style, patch } => self.set_inline_style(id, style, patch),
3024            Op::SetProp { id, prop } => {
3025                let role = matches!(
3026                    prop,
3027                    Prop::Accessibility(
3028                        AccessibilityProp::Role(_)
3029                            | AccessibilityProp::Label(_)
3030                            | AccessibilityProp::State(_)
3031                    ) | Prop::Scrollbar(_)
3032                        | Prop::Horizontal(_)
3033                );
3034                let result = self.set_prop(id, prop);
3035                if role && let Ok(key) = self.key(id) {
3036                    self.sync_grid_role(key);
3037                }
3038                result
3039            }
3040            Op::Listen { id, event, enabled } => {
3041                let key = self.key(id)?;
3042                let node = &mut self.nodes[key as usize];
3043                let before = node.events;
3044                node.events.set(event, enabled);
3045                if PRESSES.contains(&event) || HANDLED.contains(&event) {
3046                    self.sync_grid_role(key);
3047                }
3048                if event == EventKind::Layout && enabled && !before.contains(event) {
3049                    self.report_frame(key);
3050                }
3051                let node = &self.nodes[key as usize];
3052                let key_events = matches!(event, EventKind::KeyDown | EventKind::KeyUp);
3053                if node.events != before {
3054                    let relink = node.inline && (pressable(before) || pressable(node.events));
3055                    self.mark(key, dirty::EVENTS);
3056                    if key_events {
3057                        self.key_ancestry_dirty = true;
3058                    }
3059                    // Pressable spans are part of their block's text.
3060                    if relink {
3061                        self.mark_text_block(key);
3062                    }
3063                }
3064                // A list in its parent's viewport scrolls with the view
3065                // around it: its own scroll events never come.
3066                if enabled
3067                    && matches!(
3068                        event,
3069                        EventKind::Scroll
3070                            | EventKind::Refresh
3071                            | EventKind::ScrollEnd
3072                            | EventKind::ScrollDragStart
3073                            | EventKind::ScrollDragEnd
3074                            | EventKind::MomentumStart
3075                            | EventKind::MomentumEnd
3076                    )
3077                    && self.nodes[key as usize]
3078                        .list
3079                        .as_ref()
3080                        .is_some_and(|l| l.parent)
3081                {
3082                    self.warn_ignored(key);
3083                }
3084                Ok(())
3085            }
3086            Op::Insert {
3087                parent,
3088                child,
3089                before,
3090            } => self.insert(parent, child, before),
3091            Op::Remove { parent, child } => {
3092                let parent = self.key(parent)?;
3093                if let Some(run) = self.runs.get(&child) {
3094                    if run.block != parent {
3095                        return Err(ApplyError::NotAChild(child));
3096                    }
3097                    self.unfold_run(child);
3098                    return Ok(());
3099                }
3100                let child = self.key(child)?;
3101                if self.nodes[child as usize].parent != parent {
3102                    return Err(ApplyError::NotAChild(self.nodes[child as usize].id));
3103                }
3104                self.detach(child);
3105                Ok(())
3106            }
3107            Op::Release { id } => self.release(id),
3108            Op::Placeholder { id } => {
3109                let key = self.key(id)?;
3110                self.placeholder(key);
3111                Ok(())
3112            }
3113            Op::Animation(op) => {
3114                // A view culled for where its transform may take it may
3115                // reach further now (`cull.rs`).
3116                if self.reach.apply(&op) && !self.culling.is_empty() {
3117                    self.cull_dirty = true;
3118                }
3119                self.mount.push(MountItem::Animation(op));
3120                Ok(())
3121            }
3122            Op::Draw { id, mut drawing } => {
3123                let key = self.key(id)?;
3124                if self.nodes[key as usize].kind != Kind::Canvas {
3125                    return Ok(());
3126                }
3127                self.check_canvas_images(&mut drawing);
3128                let node = &mut self.nodes[key as usize];
3129                let slots_changed = node
3130                    .drawing
3131                    .as_ref()
3132                    .map_or(!drawing.slots.is_empty(), |d| d.slots != drawing.slots);
3133                if node.drawing.as_deref() == Some(&*drawing) {
3134                    return Ok(());
3135                }
3136                // An empty drawing on a canvas that has drawn nothing shows
3137                // nothing new (a component's canvas before its first layout).
3138                if node.drawing.is_none() && drawing.ops.is_empty() && drawing.nodes.is_empty() {
3139                    return Ok(());
3140                }
3141                // Whether the view draws its background (it does not where
3142                // the drawing fills with it).
3143                let background_moved = node.drawing.as_ref().is_some_and(|d| d.paints_background())
3144                    != drawing.paints_background();
3145                // A drawing fitting a view box lays its canvas out at its
3146                // natural size, as an image.
3147                let natural = drawing.fit().map(|fit| fit.size);
3148                if node
3149                    .drawing
3150                    .as_ref()
3151                    .and_then(|d| d.fit())
3152                    .map(|fit| fit.size)
3153                    != natural
3154                    && let Some(layout) = node.layout
3155                {
3156                    self.layout
3157                        .set_node_context(layout, natural.map(|n| LeafContext::Image(Some(n))));
3158                    self.layout.mark_dirty(layout);
3159                    self.needs_layout = true;
3160                }
3161                let node = &mut self.nodes[key as usize];
3162                node.drawing = Some(Arc::from(drawing));
3163                let flags = dirty::CANVAS
3164                    | if slots_changed { dirty::ANIMATION } else { 0 }
3165                    | if background_moved { dirty::VIEW } else { 0 };
3166                self.mark(key, flags);
3167                Ok(())
3168            }
3169            Op::Command {
3170                id: crate::ROOT_ID,
3171                command: Command::LayoutAnimation(animation),
3172            } => {
3173                self.layout_animation = Some(animation);
3174                Ok(())
3175            }
3176            // Sent to a node: the frames its change moves.
3177            Op::Command {
3178                id,
3179                command: Command::LayoutAnimation(animation),
3180            } => {
3181                self.key(id)?;
3182                if let Some(transition) = animation.update {
3183                    self.scope_layout_animation(id, transition);
3184                }
3185                Ok(())
3186            }
3187            Op::Command {
3188                id: crate::ROOT_ID,
3189                command: Command::SetStatusBar(patch),
3190            } => {
3191                self.components.status_bars.set_base(patch);
3192                Ok(())
3193            }
3194            // JS's responder blocks native scroll views as the components'
3195            // does: the core sends both sides' blocks.
3196            Op::Command {
3197                id,
3198                command: Command::SetJsResponder { block },
3199            } => {
3200                self.key(id)?;
3201                self.block_native(touch::Side::Js, block.then_some(id));
3202                Ok(())
3203            }
3204            Op::Command {
3205                id,
3206                command: Command::CancelPress,
3207            } => {
3208                self.key(id)?;
3209                self.cancel_press(id);
3210                Ok(())
3211            }
3212            Op::Command {
3213                command: Command::ClearJsResponder,
3214                ..
3215            } => {
3216                self.block_native(touch::Side::Js, None);
3217                Ok(())
3218            }
3219            // A released node: no layout, but the call is answered.
3220            Op::Command {
3221                id,
3222                command: Command::Measure { call },
3223            } if self.key(id).is_err() => {
3224                self.answer_measure(id, call);
3225                Ok(())
3226            }
3227            Op::Command {
3228                id,
3229                command: Command::MeasureScrollPosition { call },
3230            } if self.key(id).is_err() => {
3231                self.answer_scroll_position(id, call);
3232                Ok(())
3233            }
3234            // A window's attributes go into its record, sent once per
3235            // commit; opening one is checked and resolved here.
3236            Op::Command {
3237                id,
3238                command: Command::Desktop(desktop),
3239            } if desktop.is_core_handled() => {
3240                self.key(id)?;
3241                self.window_command(id, *desktop, false);
3242                Ok(())
3243            }
3244            Op::Command { id, command } => {
3245                self.key(id)?;
3246                self.commands.push((id, command));
3247                Ok(())
3248            }
3249        }
3250    }
3251
3252    /// A command about window `id` (its root node): attributes join its
3253    /// record ([`Core::flush_windows`] sends what changed), opening one is
3254    /// checked against the capabilities and resolved, a placement is fitted
3255    /// on the displays there are.
3256    fn window_command(
3257        &mut self,
3258        id: NodeId,
3259        command: crate::desktop::DesktopCommand,
3260        launch: bool,
3261    ) {
3262        use crate::desktop::{
3263            DesktopCommand, WindowPlacement, WindowRequest,
3264            window::{WindowRecord, placement_key},
3265        };
3266        match command {
3267            // The quit mode reaches past the app's view, as quitting does:
3268            // a sandboxed app without `application` keeps the platform's.
3269            DesktopCommand::SetQuitMode(_) if !self.access.allows_application() => {
3270                self.deny(
3271                    "the application (its main window, menu, tray, global shortcuts, quitting and restarting) is not granted: add `\"application\": true` to capabilities in nsh.json".into(),
3272                );
3273            }
3274            // nsh.json's launch attributes are the host's, applied before
3275            // the app runs; the app's own sets still need `application`.
3276            DesktopCommand::SetAttributes(_)
3277                if id == crate::ROOT_ID && !launch && !self.access.allows_application() =>
3278            {
3279                self.deny(
3280                    "the application (its main window, menu, tray, global shortcuts, quitting and restarting) is not granted: add `\"application\": true` to capabilities in nsh.json".into(),
3281                );
3282            }
3283            DesktopCommand::Request(WindowRequest::SetPlacement(_))
3284                if id == crate::ROOT_ID && !self.access.allows_application() =>
3285            {
3286                self.deny(
3287                    "the application (its main window, menu, tray, global shortcuts, quitting and restarting) is not granted: add `\"application\": true` to capabilities in nsh.json".into(),
3288                );
3289            }
3290            DesktopCommand::SetAttributes(_) if !self.has_window() => {
3291                log::debug!("window attributes of view {id}: the surface has no window");
3292            }
3293            DesktopCommand::SetAttributes(mut attributes) => {
3294                attributes.sanitize();
3295                let denied = self.access.deny_window_attributes(&mut attributes);
3296                if !denied.is_empty() {
3297                    self.deny(format!(
3298                        "nsh/desktop: the window attributes {} are not granted by capabilities.windows: left as they are",
3299                        denied.join(", ")
3300                    ));
3301                }
3302                // Fitting the content or not lays the window's root out
3303                // again ([`Core::fit_window`]).
3304                if attributes.size_to_content.is_some()
3305                    && let Ok(key) = self.key(id)
3306                    && let Some(layout) = self.nodes[key as usize].layout
3307                {
3308                    self.layout.mark_dirty(layout);
3309                    self.needs_layout = true;
3310                }
3311                self.windows
3312                    .entry(id)
3313                    .or_default()
3314                    .pending
3315                    .merge(&attributes);
3316            }
3317            DesktopCommand::SetQuitMode(mode) => {
3318                self.quit_mode = Some(mode);
3319            }
3320            DesktopCommand::OpenWindow(mut open) => {
3321                let options = &mut open.options;
3322                // `Window.open` checked it already and threw; this guards
3323                // every other way in.
3324                let open_now = self
3325                    .window_ids
3326                    .values()
3327                    .filter(|(node, _)| *node != id && self.key(*node).is_ok())
3328                    .count();
3329                // The first app window of the run inherits nsh.json's
3330                // `"window"` launch defaults and the host's size: the host is
3331                // invisible, so those defaults describe the window the app
3332                // shows first. A later window after every one closed opens
3333                // as it asked, not as the launch defaults say.
3334                if !self.launch_defaults_applied {
3335                    if let Some(defaults) = self.main_window_options.clone() {
3336                        if options.default_size.is_none() {
3337                            options.default_size = defaults.default_size;
3338                        }
3339                        if options.default_position.is_none() {
3340                            options.default_position = defaults.default_position;
3341                        }
3342                        if options.display.is_none() {
3343                            options.display = defaults.display;
3344                        }
3345                        if options.default_mode.is_none() {
3346                            options.default_mode = defaults.default_mode;
3347                        }
3348                        if !options.restore_bounds {
3349                            options.restore_bounds = defaults.restore_bounds;
3350                        }
3351                        let mut attributes = defaults.attributes;
3352                        attributes.merge(&options.attributes);
3353                        options.attributes = attributes;
3354                    }
3355                    if let Some(state) = self.components.environment.window_state {
3356                        if options.default_size.is_none() {
3357                            options.default_size = Some(state.content_bounds.size);
3358                        }
3359                        if options.default_position.is_none() {
3360                            options.default_position =
3361                                Some(crate::desktop::WindowPosition::At(state.bounds.origin));
3362                        }
3363                    }
3364                }
3365                // A released app's implicit first window is the main window
3366                // it always had, not one of its own: no grant to check.
3367                if !open.implicit
3368                    && let Err(message) =
3369                        self.access
3370                            .check_window(options.kind, &options.attributes, open_now)
3371                {
3372                    self.deny(format!("nsh/desktop: {message}: the window does not open"));
3373                    return;
3374                }
3375                // A refused first window does not consume the launch
3376                // defaults: the next admitted window still gets them.
3377                self.launch_defaults_applied = true;
3378                options.attributes.sanitize();
3379                options.attributes =
3380                    crate::desktop::WindowAttributes::resolve(options.kind, &options.attributes);
3381                // `"main"` is a window id like any other: a parent is the
3382                // window the registry has open under that id.
3383                open.parent = options
3384                    .parent
3385                    .as_deref()
3386                    .and_then(|parent| self.window_ids.get(parent).map(|(node, _)| *node));
3387                if options.restore_bounds {
3388                    let _entered = self.components.runtime.enter();
3389                    open.placement = crate::storage::Storage::get_item(&placement_key(&options.id))
3390                        .and_then(|json| serde_json::from_str::<WindowPlacement>(&json).ok())
3391                        .map(|p| self.components.runtime.fit_window_placement(p));
3392                }
3393                let size = open
3394                    .placement
3395                    .map(|p| p.bounds.size)
3396                    .or(options.default_size);
3397                self.windows.insert(
3398                    id,
3399                    WindowRecord::opened(options.attributes.clone(), size, open.implicit),
3400                );
3401                self.window_ids
3402                    .insert(options.id.clone(), (id, options.restore_bounds));
3403                self.key_ancestry_dirty = true;
3404                self.commands.push((
3405                    id,
3406                    Command::Desktop(Box::new(DesktopCommand::OpenWindow(open))),
3407                ));
3408            }
3409            // Saved placements go onto the displays there are now, whichever
3410            // side (Rust or JS) restores them.
3411            DesktopCommand::Request(WindowRequest::SetPlacement(placement)) => {
3412                let placement = self.components.runtime.fit_window_placement(placement);
3413                self.commands.push((
3414                    id,
3415                    Command::Desktop(Box::new(DesktopCommand::Request(
3416                        WindowRequest::SetPlacement(placement),
3417                    ))),
3418                ));
3419            }
3420            other => self.commands.push((id, Command::Desktop(Box::new(other)))),
3421        }
3422    }
3423
3424    /// Sends each window's attributes that changed since the last commit,
3425    /// one command per window; forgets the windows whose root is gone.
3426    fn flush_windows(&mut self) {
3427        if self.windows.is_empty() {
3428            return;
3429        }
3430        let had_windows = !self.window_ids.is_empty();
3431        let gone: Vec<NodeId> = self
3432            .windows
3433            .keys()
3434            .copied()
3435            // Released, or out of the tree: a closed window's root that
3436            // something still holds (a development host keeps the mounted
3437            // app for hot updates) is not released yet, but it is gone.
3438            .filter(|&id| {
3439                !self
3440                    .key(id)
3441                    .is_ok_and(|k| id == crate::ROOT_ID || self.nodes[k as usize].parent != NO_KEY)
3442            })
3443            .collect();
3444        let mut closed_implicit = false;
3445        for id in gone {
3446            if let Some(record) = self.windows.remove(&id) {
3447                closed_implicit |= record.implicit;
3448            }
3449            self.window_ids.retain(|_, (node, _)| *node != id);
3450        }
3451        // The last window went: the quit mode decides whether that ends the
3452        // app. The app's own close path has run by now (its root is gone),
3453        // and the core's listeners had their turn (a Rust listener turning
3454        // the mode to `"explicit"` keeps the app running). A JS listener
3455        // runs in a later commit, after this decision: an app that keeps
3456        // running with no windows sets `quitMode: "explicit"` before the
3457        // last close, not from `lastWindowClosed`. A listener that opens a
3458        // window again does so in the next commit, which by then is not the
3459        // last window (with the mode `"explicit"`).
3460        //
3461        // A plain root's implicit main window has no `<Window>` scenes or
3462        // reopen flow of its own: unless the app explicitly chose a quit
3463        // mode, closing it quits on every platform instead of leaving a
3464        // windowless Dock process on macOS.
3465        if had_windows && self.window_ids.is_empty() {
3466            self.last_window_closed();
3467            let mode = self.quit_mode.unwrap_or(if closed_implicit {
3468                crate::desktop::QuitMode::LastWindowClosed
3469            } else {
3470                self.default_quit_mode
3471            });
3472            if mode.quits(self.components.environment.os) {
3473                self.commands.push((
3474                    ROOT_ID,
3475                    Command::Desktop(Box::new(crate::desktop::DesktopCommand::Quit)),
3476                ));
3477            }
3478        }
3479        let mut ids: Vec<NodeId> = self.windows.keys().copied().collect();
3480        ids.sort_unstable();
3481        for id in ids {
3482            let Some(diff) = self.windows.get_mut(&id).and_then(|r| r.take_diff()) else {
3483                continue;
3484            };
3485            // Before the commit's first request to the window, so a window
3486            // shown in the commit that set `activate: false` is not activated.
3487            let at = self
3488                .commands
3489                .iter()
3490                .position(|(to, c)| {
3491                    *to == id
3492                        && matches!(c, Command::Desktop(d)
3493                            if matches!(**d, crate::desktop::DesktopCommand::Request(_)))
3494                })
3495                .unwrap_or(self.commands.len());
3496            self.commands.insert(
3497                at,
3498                (
3499                    id,
3500                    Command::Desktop(Box::new(crate::desktop::DesktopCommand::SetAttributes(
3501                        Box::new(diff),
3502                    ))),
3503                ),
3504            );
3505        }
3506    }
3507
3508    /// A window that fits its content (`sizeToContent`), the main one or
3509    /// one of the app's own: its root was laid out at its content's size on
3510    /// those sides; the window is sized to it when it changes. The platforms do nothing for
3511    /// it but carry out the request.
3512    fn fit_window(&mut self, key: Key, layout: LayoutId) {
3513        let id = self.nodes[key as usize].id;
3514        let Some(record) = self.windows.get_mut(&id) else {
3515            return;
3516        };
3517        let (width, height) = record.fits();
3518        if !width && !height {
3519            record.fitted = None;
3520            return;
3521        }
3522        let laid_out = self.layout.unrounded_layout(layout).size;
3523        let size = crate::geometry::size(
3524            Points(laid_out.width.ceil()),
3525            Points(laid_out.height.ceil()),
3526        );
3527        if record.fitted == Some(size) {
3528            return;
3529        }
3530        record.fitted = Some(size);
3531        self.commands.push((
3532            id,
3533            Command::Desktop(Box::new(crate::desktop::DesktopCommand::Request(
3534                crate::desktop::WindowRequest::SetContentSize {
3535                    width: width.then_some(size.width),
3536                    height: height.then_some(size.height),
3537                },
3538            ))),
3539        ));
3540    }
3541
3542    /// The size of modal `key`'s root view: what the platform reported
3543    /// (`set_root_size`), else, for the root of a window of the app's own,
3544    /// the window's size as the core knows it (its content's with
3545    /// `sizeToContent`, the placement's or `defaultSize`), else a dialog's
3546    /// main window's. `None`: a window whose size only its platform knows,
3547    /// laid out at its content's size until the platform reports it, never
3548    /// at the main window's.
3549    pub(crate) fn root_view_size(&self, key: Key) -> Option<Size<Points>> {
3550        let node = &self.nodes[key as usize];
3551        if let Some(size) = node.root.as_ref().and_then(|r| r.reported) {
3552            return Some(size);
3553        }
3554        if self.window_ids.values().any(|(id, _)| *id == node.id) {
3555            return self.windows.get(&node.id).and_then(|r| r.fitted.or(r.size));
3556        }
3557        Some(self.viewport)
3558    }
3559
3560    /// The window node `key` shows in: the root of the nearest window of
3561    /// the app's own around it, else the main window ([`ROOT_ID`]).
3562    pub(crate) fn window_of(&self, key: Key) -> NodeId {
3563        if self.window_ids.is_empty() {
3564            return crate::ROOT_ID;
3565        }
3566        let mut k = self.nodes[key as usize].parent;
3567        while k != NO_KEY {
3568            let n = &self.nodes[k as usize];
3569            if n.kind == Kind::Modal && self.window_ids.values().any(|(node, _)| *node == n.id) {
3570                return n.id;
3571            }
3572            k = n.parent;
3573        }
3574        crate::ROOT_ID
3575    }
3576
3577    /// The surface is in a window whose attributes its platform applies: a
3578    /// desktop's (the OSes `nsh/desktop`'s `isAvailable` answers for), or
3579    /// a browser's page, whose title is the main window's. A mobile surface
3580    /// is a view in its app's screen: window attributes have nothing to
3581    /// apply to there, so none are kept or sent.
3582    fn has_window(&self) -> bool {
3583        let os = self.components.environment.os;
3584        os.is_desktop() || os == crate::platform::Os::Web
3585    }
3586
3587    /// Keeps the placement of window `id` (its root node) a platform
3588    /// reported, when the app asked to restore its bounds. A main window
3589    /// hidden since launch (`defaultVisible: false`) is not where the user
3590    /// left it until it first shows: it has yet to take the mode it opens
3591    /// in, and GTK has yet to size it. Once it has shown, its reports are,
3592    /// hidden ones too: one hidden right after a move or resize reports
3593    /// where it was left only then. (A development host's reload starts a
3594    /// new core: there such a window shown before the reload counts as
3595    /// hidden since launch until it shows again.)
3596    pub(crate) fn keep_window_placement(
3597        &mut self,
3598        id: NodeId,
3599        state: &crate::desktop::WindowState,
3600    ) {
3601        if id == crate::ROOT_ID {
3602            self.main_shown |= state.visible;
3603            if !self.main_shown {
3604                return;
3605            }
3606        }
3607        let key = if id == crate::ROOT_ID {
3608            self.keep_main_placement
3609                .then(|| crate::desktop::window::placement_key("main"))
3610        } else {
3611            self.window_ids
3612                .iter()
3613                .find(|(_, (node, keep))| *node == id && *keep)
3614                .map(|(key, _)| crate::desktop::window::placement_key(key))
3615        };
3616        let Some(key) = key else {
3617            return;
3618        };
3619        if let Ok(json) = serde_json::to_string(&state.placement) {
3620            let _entered = self.components.runtime.enter();
3621            if crate::storage::Storage::get_item(&key).as_deref() != Some(json.as_str()) {
3622                let _ = crate::storage::Storage::set_item(key, json);
3623            }
3624        }
3625    }
3626
3627    /// The bottom edge of the logical root's in-flow children, in surface points.
3628    ///
3629    /// Read after [`Self::commit`] for settled geometry, from the same frames
3630    /// reported to layout listeners. Detached layout roots (such as overlays
3631    /// and modals) and fixed or absolutely positioned children do not contribute.
3632    /// `None` means there is no laid-out in-flow content. This does not run an
3633    /// intrinsic-size pass or change the viewport.
3634    pub fn content_height(&self) -> Option<Points> {
3635        self.nodes[self.root as usize]
3636            .children
3637            .iter()
3638            .filter_map(|&key| {
3639                let node = &self.nodes[key as usize];
3640                let layout = node.layout?;
3641                if node.is_layout_root()
3642                    || self.layout.displays_none(layout)
3643                    || matches!(
3644                        self.layout.style(layout).position,
3645                        Position::Absolute | Position::Fixed
3646                    )
3647                    || node.frame.origin.y.0.is_nan()
3648                {
3649                    return None;
3650                }
3651                Some(node.frame.origin.y.0 + node.frame.size.height.0)
3652            })
3653            .reduce(f32::max)
3654            .map(Points)
3655    }
3656
3657    /// Finishes a turn: rebuilds text, runs layout, updates lists and
3658    /// returns the mount items, or `None` when nothing changed.
3659    pub fn commit(&mut self) -> Option<MountBatch> {
3660        // The last round's events were dispatched: a geometry no one took
3661        // is stale (its node went).
3662        self.geometries.clear();
3663        // The downloads' file work and deadlines: their events and
3664        // commands go out with this commit.
3665        self.poll_downloads();
3666        // JS has handled the events taken before this commit and its ops
3667        // are applied: what waited for that sees the app's props, and what
3668        // it changes renders with them.
3669        if self.components.executor.has_due_answers() {
3670            self.run_answers();
3671        }
3672        self.pace_commit();
3673        self.sync_quit_requests();
3674        self.commit_round();
3675        // The components' own lists bind the cells the layout asked for
3676        // here, and lay out again (JS's lists ask JS, through the engine);
3677        // a list in its parent's viewport that changed length lays the
3678        // page out again, so it settles in this batch.
3679        // Views watching scroll views they did not make hear what this
3680        // round moved, and what they change goes out in this batch too.
3681        for _ in 0..MAX_VIRTUAL_ROUNDS {
3682            let watched = self.sync_watches();
3683            // A built-in bar asked for while this round rendered (the app
3684            // set its theme) is made in this batch too.
3685            if !self.bind_virtual_lists()
3686                && !std::mem::take(&mut self.extent_changed)
3687                && !watched
3688                && !std::mem::take(&mut self.cull_made)
3689                && !std::mem::take(&mut self.placeholders_resized)
3690                && self.scrollbars_pending.is_empty()
3691            {
3692                break;
3693            }
3694            self.commit_round();
3695        }
3696        if !self.outer_asked.is_empty() {
3697            self.send_outer_scrolls();
3698        }
3699        // What mounted in the rounds listens already.
3700        if self.sync_quit_requests() {
3701            self.commit_round();
3702        }
3703        self.split_scoped_frames();
3704        self.mark_shader_inputs();
3705        if !self.transition_starts.is_empty() {
3706            // Before the changes they are about: the platform pictures what
3707            // showed before them.
3708            let starts = std::mem::take(&mut self.transition_starts);
3709            self.mount.splice(0..0, starts);
3710        }
3711        if std::mem::take(&mut self.tab_places_stale) && !self.overlays.is_empty() {
3712            self.order_overlays_for_tab();
3713        }
3714        if std::mem::take(&mut self.tree_order_changed) {
3715            let mut order = Vec::new();
3716            let mut pending = vec![self.root];
3717            let mut cells = Vec::new();
3718            while let Some(key) = pending.pop() {
3719                let node = &self.nodes[key as usize];
3720                if node.created {
3721                    order.push(node.id);
3722                }
3723                match &node.list {
3724                    // A list recycles its cells, so they are not in their
3725                    // rows' order among its children: they go as they are
3726                    // on screen, along the list's axis, then across it.
3727                    Some(list) if node.children.len() > 1 => {
3728                        cells.clear();
3729                        cells.extend_from_slice(&node.children);
3730                        let start = |k: &Key| {
3731                            let at = self.nodes[*k as usize].frame.origin;
3732                            if list.horizontal {
3733                                (at.x.0, at.y.0)
3734                            } else {
3735                                (at.y.0, at.x.0)
3736                            }
3737                        };
3738                        cells.sort_by(|a, b| {
3739                            let (a, b) = (start(a), start(b));
3740                            a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1))
3741                        });
3742                        pending.extend(cells.iter().rev().copied());
3743                    }
3744                    _ => pending.extend(node.children.iter().rev().copied()),
3745                }
3746            }
3747            self.mount.push(MountItem::TreeOrder(order));
3748        }
3749        if self.mount.is_empty() || matches!(self.mount[..], [MountItem::LayoutAnimation(_)]) {
3750            self.mount.clear();
3751            None
3752        } else {
3753            self.batches += 1;
3754            Some(MountBatch {
3755                items: std::mem::take(&mut self.mount),
3756            })
3757        }
3758    }
3759
3760    /// Include logical document order in mount batches for a platform's focus traversal.
3761    /// Native sibling insertions describe paint order and can differ because of `zIndex`.
3762    pub fn set_tree_order_tracking(&mut self, enabled: bool) {
3763        self.track_tree_order = enabled;
3764        self.tree_order_changed = enabled;
3765    }
3766
3767    /// Mount the states views show as parts of a control
3768    /// ([`MountItem::ProjectStates`]: a list's highlighted option, the
3769    /// code input's next cell) for a platform that marks them itself, as
3770    /// a terminal does: elsewhere the app's classes alone show them. Set
3771    /// before the first commit.
3772    pub fn set_projected_state_mounting(&mut self, enabled: bool) {
3773        self.mount_projected = enabled;
3774    }
3775
3776    /// One round of a commit: views, layout, lists, commands, into the
3777    /// mount items.
3778    fn commit_round(&mut self) {
3779        // Pointers components pass on, onto the layout they were over.
3780        if !self.components.hovers.is_empty() {
3781            self.pass_hovers();
3782        }
3783        // The built-in scroll bars that come, rendered with the rest.
3784        if !self.scrollbars_pending.is_empty() {
3785            self.sync_scrollbars();
3786        }
3787        // The views' patches and the views to make first.
3788        self.render_components();
3789        // The children that moved, the app's and those the components just
3790        // placed, styled at their places before anything reads their styles
3791        // (`position: fixed`, the color they pass on).
3792        self.flush_positions();
3793        self.prepare_reveals();
3794        // The focus reported since, after the components made and released
3795        // what they did: one change of the chain, the views both chains
3796        // share untouched.
3797        let visible_moved = std::mem::take(&mut self.focus_visible_moved);
3798        // A blur no focus followed yet waits for the frame (`blur_held`).
3799        let held = self.blur_held && self.focus.is_none() && !self.focus_chain.is_empty();
3800        if self.focus_moved && !held {
3801            self.update_focus_within();
3802            self.update_focus_visible();
3803            // The hints the focus came to or left.
3804            if !self.overlays.is_empty() {
3805                self.focus_hints();
3806            }
3807        } else if visible_moved {
3808            // A key typed with the focus where it is shows its ring, and no
3809            // hint: a hint shows only for a focus the keyboard moved.
3810            self.update_focus_visible();
3811        }
3812        self.sync_pointer_keymap();
3813        self.sync_colors();
3814        self.sync_ch();
3815        self.sync_fixed();
3816        self.sync_overlays();
3817        if std::mem::take(&mut self.key_ancestry_dirty) {
3818            self.sync_key_parents();
3819            self.sync_key_contents();
3820        }
3821        // The rows holding the focus or an open overlay stay rendered,
3822        // before the lists update their windows.
3823        if self.focus.is_some() || !self.overlays.is_empty() || !self.kept_lists.is_empty() {
3824            self.sync_kept();
3825        }
3826        self.sync_back();
3827        self.sync_back_progress();
3828        self.sync_keys();
3829        // Platforms animate the frames, insertions and removals that follow
3830        // in the batch; ops may already have queued some.
3831        self.sync_env();
3832        if let Some(animation) = self.layout_animation.take() {
3833            self.note_list_motion(animation);
3834            self.mount.insert(0, MountItem::LayoutAnimation(animation));
3835        }
3836        self.flush_pointer_events();
3837        if !self.relators.is_empty() {
3838            self.sync_relations();
3839        }
3840        self.flush_dirty();
3841        let relayout = self.needs_layout;
3842        if relayout {
3843            self.needs_layout = false;
3844            let settling = std::mem::take(&mut self.resize_settling);
3845            let anchors = if settling || self.measure_cache.resizing.is_some() {
3846                self.resize_anchors()
3847            } else {
3848                Vec::new()
3849            };
3850            if self.measure_cache.resizing.is_some() {
3851                self.mark_near_screen();
3852            }
3853            // Boundaries first: what they give back may dirty what is
3854            // around them, laid out next.
3855            let relaid = self.relayout_boundaries();
3856            // Only walk the main tree when it was laid out again (a change
3857            // inside a list cell leaves it untouched).
3858            if self.layout_main() {
3859                let root = self.root;
3860                let children = std::mem::take(&mut self.nodes[root as usize].children);
3861                for &child in &children {
3862                    if !self.nodes[child as usize].is_layout_root() {
3863                        self.emit_frames(child);
3864                    }
3865                }
3866                self.nodes[root as usize].children = children;
3867            }
3868            // Screens and modals, then list cells (lists may live in them).
3869            self.layout_roots();
3870            self.layout_cells();
3871            for key in relaid {
3872                self.emit_frames(key);
3873            }
3874            self.keep_resize_anchors(anchors);
3875        }
3876        // Placeholders sized again are laid out again, in another round,
3877        // before culling looks at them.
3878        let sized = relayout && !self.placeholders.is_empty() && self.size_placeholders();
3879        if sized {
3880            self.cull_dirty = true;
3881        } else if self.cull_dirty || (relayout && !self.culling.is_empty()) {
3882            // The views a scroll view culls that came within its window.
3883            self.sync_culled();
3884        }
3885        self.update_lists(relayout);
3886        // A list gives the views in a cell their frames as it places the
3887        // cell, after culling looked: a scroll view made in a cell in this
3888        // round had no frame then, so what it culls waited, and nothing
3889        // would look at it again before the next layout or scroll (a row
3890        // bound as a scroll came to rest kept its scroll views empty).
3891        // Not while placeholders wait for their layout, as above.
3892        if std::mem::take(&mut self.cells_framed) && !sized && !self.culling.is_empty() {
3893            self.sync_culled();
3894        }
3895        if !self.slop_moved.is_empty() {
3896            self.update_slop_overflow();
3897        }
3898        // Views that waited for the budget, once lists placed their cells
3899        // (`pace.rs`).
3900        if !self.pace.waiting.is_empty() {
3901            self.sync_paced();
3902        }
3903        // After every frame of the round: what followers follow is placed.
3904        self.place_followers(relayout);
3905        if !self.decorated.is_empty() {
3906            self.layout_scrollbars();
3907        }
3908        if !self.overlays.is_empty() {
3909            self.place_overlays();
3910        }
3911        if !self.fitted_pending.is_empty() {
3912            self.send_fitted();
3913        }
3914        self.flush_text();
3915        // What this turn's status bar settings add up to, once.
3916        self.sync_status_bars();
3917        if let Some(config) = self.components.status_bars.take_changed() {
3918            self.commands
3919                .push((crate::ROOT_ID, Command::StatusBar(config)));
3920        }
3921        self.sync_orientations();
3922        // Each window's attributes, once per commit.
3923        self.flush_windows();
3924        // The components' measurements, with this commit's layout as JS's.
3925        for (id, answer) in std::mem::take(&mut self.components.measures) {
3926            answer.borrow_mut().deliver(self.measure(id));
3927        }
3928        for (id, answer) in std::mem::take(&mut self.components.scroll_positions) {
3929            answer.borrow_mut().deliver(self.list_scroll_position(id));
3930        }
3931        // And their transitions' time, with this commit's styles.
3932        for (id, answer) in std::mem::take(&mut self.components.transition_times) {
3933            answer.borrow_mut().deliver(self.transition_time(id));
3934        }
3935        // And their texts, with this commit's.
3936        for (id, answer) in std::mem::take(&mut self.components.text_contents) {
3937            answer.borrow_mut().deliver(self.text_content(id));
3938        }
3939        // Into the scroll commands of the scroll views around, in place,
3940        // with this commit's layout and the scrolls of the commands before.
3941        if self
3942            .commands
3943            .iter()
3944            .any(|(_, c)| matches!(c, Command::Reveal(_)))
3945        {
3946            let mut projected = Vec::new();
3947            for (id, command) in std::mem::take(&mut self.commands) {
3948                let commands = match command {
3949                    Command::Reveal(options) => self.reveal_scrolls(id, options, &projected),
3950                    command => vec![(id, command)],
3951                };
3952                for (id, command) in commands {
3953                    if let Some(to) = self.scrolled_to(id, &command) {
3954                        projected.push((id, to));
3955                    }
3956                    self.commands.push((id, command));
3957                }
3958            }
3959        }
3960        // Presses a component passes on, onto this commit's layout.
3961        for (id, press, answer) in std::mem::take(&mut self.components.presses) {
3962            let target = self.press_target(id, press.page_position);
3963            if let Some((node, position)) = target {
3964                self.events.push(crate::element::JsEvent::Event(
3965                    node,
3966                    EventKind::Press,
3967                    EventPayload::Press(crate::PressEvent { position, ..press }),
3968                ));
3969            }
3970            answer.borrow_mut().deliver(target.is_some());
3971        }
3972        // The downloads' listeners as this round's final masks leave them:
3973        // a web view left with neither of them cancels what it holds, and
3974        // the cancel commands go out with this batch.
3975        self.sync_download_listeners();
3976        self.focus_opened_modals();
3977        // A focus given back yields to one moved out of the popup anywhere
3978        // in this commit (in this round, or an earlier one's items),
3979        // whichever came first: the app's choice outranks a popup's
3980        // closing. A move inside the popup (its items' keys typed ahead of
3981        // the choice) or to a view that is gone does not.
3982        if let Some((id, from)) = self.focus_back.take() {
3983            let origin = self
3984                .focus_origins
3985                .iter()
3986                .position(|&(to, _)| to == id)
3987                .map(|i| self.focus_origins.swap_remove(i).1);
3988            let from = from.and_then(|from| self.key(from).ok());
3989            let moved_out = |to: NodeId| {
3990                self.key(to)
3991                    .is_ok_and(|key| from.is_none_or(|from| !self.is_ancestor(from, key)))
3992            };
3993            let moved = self
3994                .commands
3995                .iter()
3996                .any(|(to, c)| matches!(c, Command::Focus) && moved_out(*to))
3997                || self.mount.iter().any(|m| {
3998                    matches!(
3999                        m,
4000                        MountItem::Command {
4001                            id: to,
4002                            command: Command::Focus,
4003                        } if moved_out(*to)
4004                    )
4005                });
4006            if !moved {
4007                match origin {
4008                    // Opened by the keyboard (or the app after a key): back
4009                    // to the trigger the keyboard opened it from.
4010                    None => self.commands.push((id, Command::Focus)),
4011                    Some(before) if self.press_leaves_focus() => {
4012                        self.focus_back_to_origin(before, from);
4013                    }
4014                    // Elsewhere a press focused the trigger: it takes the
4015                    // focus back, still the pointer's (Escape closing the
4016                    // list a click opened leaves the app's Space to it).
4017                    Some(_) => {
4018                        self.commands.push((id, Command::Focus));
4019                        self.pointer_focus_back = Some(id);
4020                    }
4021                }
4022            }
4023        }
4024        // On laid out views; dropped for views that were never shown.
4025        let mut kept = Vec::new();
4026        for (id, mut command) in std::mem::take(&mut self.commands) {
4027            // Answered here, with this commit's layout (null for views that
4028            // are gone or not shown).
4029            if let Command::Measure { call } = command {
4030                self.answer_measure(id, call);
4031                continue;
4032            }
4033            if let Command::MeasureScrollPosition { call } = command {
4034                self.answer_scroll_position(id, call);
4035                continue;
4036            }
4037            let Ok(key) = self.key(id) else {
4038                // A download command to a node that is gone is dropped; its
4039                // reply timeout settles the session without ever treating
4040                // silence as the writer having stopped.
4041                continue;
4042            };
4043            // A culled view is made for it.
4044            if !self.nodes[key as usize].created && !self.uncull(key) {
4045                continue;
4046            }
4047            let node = &self.nodes[key as usize];
4048            if id != crate::ROOT_ID
4049                && let Some(backend) = &self.window_backend
4050                && let Command::Desktop(desktop) = &command
4051                && desktop.is_window_command()
4052            {
4053                backend.command(id, desktop);
4054                continue;
4055            }
4056            // A list in its parent's viewport not placed in its view yet
4057            // keeps its scroll commands for the update that places it.
4058            if node.list.as_ref().is_some_and(|l| l.parent)
4059                && matches!(
4060                    command,
4061                    Command::ScrollTo { .. }
4062                        | Command::ScrollToIndex { .. }
4063                        | Command::ScrollToEnd { .. }
4064                )
4065            {
4066                kept.push((id, command));
4067                continue;
4068            }
4069            // `Image.getSize` / `prefetch` load what the check granted
4070            // (`Access::media_url`).
4071            if let Command::ImageInfo { id: request, uri } = &mut command {
4072                match self.media_source(uri) {
4073                    Some(granted) => {
4074                        if let Some(url) = granted {
4075                            *uri = url.to_string();
4076                        }
4077                    }
4078                    None => {
4079                        let message = media_not_granted(
4080                            "Image.getSize / prefetch of",
4081                            uri,
4082                            self.base_url.as_deref(),
4083                        );
4084                        self.answer_image_info(*request, Err(message.clone()));
4085                        self.deny(message);
4086                        continue;
4087                    }
4088                }
4089            }
4090            // Menu and tray icons load what the check granted
4091            // (`Access::media_url`), as an `<Image>` does.
4092            if let Command::Desktop(desktop) = &mut command {
4093                self.check_menu_icons(desktop);
4094                if id == crate::ROOT_ID {
4095                    self.remember_app_menu(desktop);
4096                }
4097            }
4098            // Lists resolved theirs in `update_lists`; a scroll view can
4099            // still scroll to its end.
4100            match &command {
4101                Command::SetClipboard(_)
4102                | Command::SetClipboardItem(_)
4103                | Command::ReadClipboard { .. }
4104                | Command::SetClipboardImage(_)
4105                | Command::ReadClipboardImage { .. }
4106                | Command::ReadClipboardFiles { .. }
4107                    if !self.access.allows_clipboard() =>
4108                {
4109                    if let Command::ReadClipboard { id: request, .. }
4110                    | Command::ReadClipboardImage { id: request, .. }
4111                    | Command::ReadClipboardFiles { id: request } = &command
4112                    {
4113                        self.answer_clipboard(*request, components::ClipboardAnswer::default());
4114                    }
4115                    if matches!(
4116                        command,
4117                        Command::SetClipboard(_) | Command::SetClipboardItem(_)
4118                    ) {
4119                        self.answer_clipboard_write(crate::element::ClipboardWrite::Failed);
4120                    }
4121                    self.deny("the clipboard is not granted: add `\"clipboard\": true` to capabilities in nsh.json".into());
4122                    continue;
4123                }
4124                // A clipboard of the embedder's own answers in place of
4125                // the platform's.
4126                Command::SetClipboard(_)
4127                | Command::SetClipboardItem(_)
4128                | Command::ReadClipboard { .. }
4129                | Command::SetClipboardImage(_)
4130                | Command::ReadClipboardImage { .. }
4131                | Command::ReadClipboardFiles { .. }
4132                    if self.clipboard.is_some() =>
4133                {
4134                    let clipboard = self.clipboard.clone().expect("a clipboard");
4135                    match &command {
4136                        Command::SetClipboard(text) => {
4137                            clipboard.set_text(Some(text.clone()));
4138                            self.answer_clipboard_write(crate::element::ClipboardWrite::Written);
4139                        }
4140                        Command::SetClipboardItem(item) => {
4141                            clipboard.set_item(Some(item.clone()));
4142                            self.answer_clipboard_write(crate::element::ClipboardWrite::Written);
4143                        }
4144                        Command::SetClipboardImage(_) => clipboard.set_item(None),
4145                        Command::ReadClipboard {
4146                            id: request,
4147                            has_only,
4148                        } => {
4149                            let text = clipboard.text();
4150                            let answer = components::ClipboardAnswer {
4151                                has: text.is_some(),
4152                                text: text.filter(|_| !has_only),
4153                                ..Default::default()
4154                            };
4155                            self.answer_clipboard(*request, answer);
4156                        }
4157                        Command::ReadClipboardImage { id: request, .. }
4158                        | Command::ReadClipboardFiles { id: request } => {
4159                            self.answer_clipboard(*request, components::ClipboardAnswer::default());
4160                        }
4161                        _ => {}
4162                    }
4163                    continue;
4164                }
4165                // A platform that cannot tell whether the system took a
4166                // write answers it now; the others report it.
4167                Command::SetClipboard(_) | Command::SetClipboardItem(_)
4168                    if !self.components.environment.clipboard_write_result =>
4169                {
4170                    self.answer_clipboard_write(crate::element::ClipboardWrite::Requested);
4171                }
4172                // Checked before the grants: a host may put the name in a
4173                // path or a URL, where `user.x/../admin` leaves `user.*`.
4174                Command::HostCall { name, .. } | Command::HostPost { name, .. } => {
4175                    if let Some(error) = crate::host_channel::refusal(&self.access, name) {
4176                        self.deny(error.to_string());
4177                        if let Command::HostCall { id: call, .. } = command {
4178                            self.answer_host(call, Err(error));
4179                        }
4180                        continue;
4181                    }
4182                }
4183                Command::SendInput(_) if !self.access.allows_web_input() => {
4184                    self.deny("trusted web view input is not granted: add `\"input\": true` to capabilities.webview in nsh.json".into());
4185                    continue;
4186                }
4187                // As a `src` the capability does not allow: the page is
4188                // not loaded, so its headers go nowhere.
4189                Command::Load(load)
4190                    if !self
4191                        .access
4192                        .allows_webview_with(&load.src, self.web_origin(key)) =>
4193                {
4194                    self.deny(not_granted("the web page", &load.src, "webview.hosts"));
4195                    continue;
4196                }
4197                Command::StatusBar(_) if !self.access.allows_status_bar() => {
4198                    self.deny("the status bar is not granted: add `\"statusBar\": true` to capabilities in nsh.json".into());
4199                    continue;
4200                }
4201                // A context menu shows in the app's own view, and the
4202                // windows the app opens are `capabilities.windows`'
4203                // (`Access::check_window`): neither needs `application`. The
4204                // main window, the application menu, the tray, global
4205                // shortcuts and quitting reach past the app's view and do.
4206                // The core-handled window commands (a window's attributes, a
4207                // placement, opening one) are checked where they are applied,
4208                // so that nsh.json's launch attributes reach the main window
4209                // while the app's own sets need `application`. Fitting a
4210                // window's content is the core's own follow-up.
4211                Command::Desktop(desktop)
4212                    if !self.access.allows_application()
4213                        && !desktop.is_core_handled()
4214                        && !matches!(
4215                            **desktop,
4216                            crate::desktop::DesktopCommand::PopupMenu { .. }
4217                                | crate::desktop::DesktopCommand::Request(
4218                                    crate::desktop::WindowRequest::SetContentSize { .. }
4219                                )
4220                        )
4221                        && (id == crate::ROOT_ID || !desktop.is_window_command()) =>
4222                {
4223                    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());
4224                    continue;
4225                }
4226                _ => {}
4227            }
4228            let node = &self.nodes[key as usize];
4229            let id = node.id;
4230            match command {
4231                Command::ScrollToEnd { animated } => {
4232                    let Some(content) = node.scroll.as_ref().and_then(|s| s.content) else {
4233                        continue;
4234                    };
4235                    let horizontal = node.scroll.as_ref().is_some_and(|s| s.horizontal);
4236                    let frame = node.frame;
4237                    let (x, y) = if horizontal {
4238                        (
4239                            (content.width - frame.size.width).max(Points::ZERO),
4240                            Points::ZERO,
4241                        )
4242                    } else {
4243                        (
4244                            Points::ZERO,
4245                            (content.height - frame.size.height).max(Points::ZERO),
4246                        )
4247                    };
4248                    command = Command::ScrollTo { x, y, animated };
4249                }
4250                Command::ScrollToIndex { .. } => continue,
4251                _ => {}
4252            }
4253            // Platforms count the scrolls they applied; lists count theirs.
4254            if let Command::ScrollTo { x, y, animated } = command
4255                && self.nodes[key as usize].kind == Kind::Scroll
4256            {
4257                let horizontal = self.nodes[key as usize]
4258                    .scroll
4259                    .as_ref()
4260                    .is_some_and(|s| s.horizontal);
4261                let to = if horizontal { x.0 } else { y.0 };
4262                self.scroll_issued(
4263                    key,
4264                    PendingScroll::To {
4265                        offset: to,
4266                        animated,
4267                    },
4268                );
4269                if let Some(scroll) = self.nodes[key as usize].scroll.as_mut() {
4270                    scroll.target = Some((scroll.issued, (x.0, y.0)));
4271                }
4272            }
4273            self.mount.push(MountItem::Command { id, command });
4274        }
4275        self.commands.append(&mut kept);
4276    }
4277
4278    #[inline]
4279    fn key(&self, id: NodeId) -> Result<Key, ApplyError> {
4280        match self.slots.get(id as usize) {
4281            Some(&k) => Ok(k),
4282            None => Err(ApplyError::UnknownNode(id)),
4283        }
4284    }
4285
4286    fn check_id_range(&self, id: NodeId) -> Result<(), ApplyError> {
4287        if id as usize > self.admitted_id_extent.saturating_add(self.max_nodes) {
4288            return Err(ApplyError::IdOutOfRange(id));
4289        }
4290        Ok(())
4291    }
4292
4293    fn insert_key(&mut self, idx: usize, key: Key) {
4294        self.slots.insert(idx, key);
4295        self.admitted_id_extent = self.admitted_id_extent.max(self.slots.extent());
4296    }
4297
4298    fn alloc(&mut self, id: NodeId, kind: Kind) -> Result<Key, ApplyError> {
4299        let idx = id as usize;
4300        if self.nodes.len().saturating_add(self.runs.len()) >= self.max_nodes {
4301            return Err(ApplyError::TooManyNodes(self.max_nodes));
4302        }
4303        self.check_id_range(id)?;
4304        if self.slots.contains(idx) || self.runs.contains_key(&id) {
4305            return Err(ApplyError::DuplicateNode(id));
4306        }
4307        let key = self.nodes.insert(Node::new(id, kind)) as Key;
4308        self.insert_key(idx, key);
4309        Ok(key)
4310    }
4311
4312    /// Makes `alias` another name of node `id`: a component whose view's
4313    /// root is another component makes that one on its own host, under a
4314    /// name of its own (the nested component's host), with no node of its
4315    /// own. What the core sends names the node by its own id.
4316    pub(super) fn alias(&mut self, alias: NodeId, id: NodeId) -> Result<(), ApplyError> {
4317        let key = self.key(id)?;
4318        let idx = alias as usize;
4319        self.check_id_range(alias)?;
4320        if self.slots.contains(idx) {
4321            return Err(ApplyError::DuplicateNode(alias));
4322        }
4323        self.insert_key(idx, key);
4324        Ok(())
4325    }
4326
4327    /// Whether `id` is another name of a node ([`Self::alias`]).
4328    pub(super) fn is_alias(&self, id: NodeId) -> bool {
4329        self.key(id).is_ok_and(|k| self.nodes[k as usize].id != id)
4330    }
4331
4332    /// Forgets alias `id` (its node stays).
4333    pub(super) fn unalias(&mut self, id: NodeId) {
4334        if self.is_alias(id) {
4335            self.slots.remove(id as usize);
4336        }
4337    }
4338
4339    /// The id node `id` has natively (another for an alias).
4340    pub(super) fn native_id(&self, id: NodeId) -> NodeId {
4341        self.key(id).map_or(id, |k| self.nodes[k as usize].id)
4342    }
4343
4344    fn create(&mut self, id: NodeId, tag: Tag) -> Result<(), ApplyError> {
4345        let kind = Kind::of(tag);
4346        let key = self.alloc(id, kind)?;
4347        let mut custom_layout = None;
4348        if let Some(role) = shader_role(tag) {
4349            self.nodes[key as usize]
4350                .shader
4351                .as_mut()
4352                .expect("a shader node")
4353                .role = role;
4354            if matches!(
4355                role,
4356                crate::shader::ShaderRole::Screen | crate::shader::ShaderRole::ScreenTransition
4357            ) {
4358                // A screen's effect takes no space: the surface is its box.
4359                let mut style = crate::style::unstyled_layout();
4360                style.position = taffy::Position::Absolute;
4361                style.size = taffy::Size {
4362                    width: taffy::Dimension::length(0.0),
4363                    height: taffy::Dimension::length(0.0),
4364                };
4365                custom_layout = Some(style);
4366            }
4367        }
4368        let context = leaf_context(kind);
4369        let layout = match custom_layout {
4370            Some(style) => match context {
4371                Some(context) => self.layout.new_leaf_with_context(style, context),
4372                None => self.layout.new_leaf(style),
4373            },
4374            None => self.layout.new_default_leaf(context),
4375        };
4376        self.layout.set_tag(layout, key);
4377        self.nodes[key as usize].layout = Some(layout);
4378        self.sync_grid_role(key);
4379        self.became(key);
4380        if kind == Kind::WebView && !self.components.environment.web_views {
4381            self.web_view_unavailable(id);
4382        }
4383        Ok(())
4384    }
4385
4386    /// A web view on a platform that shows none fails at once (`onError`
4387    /// with `code` `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`). Always reported:
4388    /// the `onError` listener is set after the node is made.
4389    fn web_view_unavailable(&mut self, id: NodeId) {
4390        self.events.push(crate::element::JsEvent::Event(
4391            id,
4392            EventKind::Error,
4393            EventPayload::Map(vec![
4394                (
4395                    "message",
4396                    PayloadValue::Str("web views are not available on this platform".into()),
4397                ),
4398                (
4399                    "code",
4400                    PayloadValue::Str(crate::element::codes::UNAVAILABLE.into()),
4401                ),
4402            ]),
4403        ));
4404    }
4405
4406    /// Whether node `key` is a control: a view with a control's
4407    /// accessibility role, one that takes presses, or a text input. On a
4408    /// grid surface a control is laid out one line of its content high
4409    /// ([`grid`]).
4410    fn is_control(&self, key: Key) -> bool {
4411        use crate::AccessibilityRole as R;
4412        let node = &self.nodes[key as usize];
4413        node.kind == Kind::Input
4414            || (!node.inline && pressable(node.events))
4415            || node.props.as_ref().is_some_and(|p| {
4416                matches!(
4417                    p.accessibility.role,
4418                    R::Button
4419                        | R::ImageButton
4420                        | R::Link
4421                        | R::Search
4422                        | R::Textbox
4423                        | R::Checkbox
4424                        | R::Radio
4425                        | R::Switch
4426                        | R::Tab
4427                        | R::Menuitem
4428                        | R::MenuItemCheckbox
4429                        | R::MenuItemRadio
4430                        | R::Option
4431                        | R::Combobox
4432                        | R::Adjustable
4433                        | R::Spinbutton
4434                )
4435            })
4436    }
4437
4438    /// What a terminal's layout takes from node `key` besides its style
4439    /// ([`terminal_layout::Role`]): whether it is a control
4440    /// ([`Self::is_control`]), a text, a scroll view, and whether a
4441    /// terminal leaves it out: what it cannot show at an icon's size is
4442    /// left out, never emulated (icon-sized videos, web views, shaders and
4443    /// canvases) and glyph-sized images; larger, they keep their box.
4444    fn grid_role(&self, key: Key) -> terminal_layout::Role {
4445        let kind = self.nodes[key as usize].kind;
4446        let left_out = match kind {
4447            // A native component draws itself where the platform
4448            // registered one, and is blank where it did not.
4449            Kind::Image => terminal_layout::LeftOut::Picture,
4450            Kind::Video | Kind::WebView | Kind::Shader | Kind::GpuView | Kind::Canvas => {
4451                terminal_layout::LeftOut::IfIcon
4452            }
4453            _ => terminal_layout::LeftOut::No,
4454        };
4455        let control = self.is_control(key);
4456        // A control's label in columns (a wide character takes two): what it shows
4457        // when all its content is left out (an icon button).
4458        let popup = control
4459            && self.nodes[key as usize].props.as_ref().is_some_and(|p| {
4460                p.accessibility.state.expanded.is_some() && p.accessibility.state.has_popup
4461            });
4462        let (label, word) = control
4463            .then(|| self.nodes[key as usize].props.as_ref())
4464            .flatten()
4465            .map_or((0, 0), |p| {
4466                let cols = |t: &str| terminal_layout::columns(t).min(u16::MAX as usize) as u16;
4467                let name = p
4468                    .accessibility
4469                    .label
4470                    .as_deref()
4471                    .map(str::trim)
4472                    .filter(|l| !l.is_empty());
4473                match (p.accessibility.state.expanded, name) {
4474                    // A disclosure shows whether it is open, `â–¸` or `â–¾`,
4475                    // and a popup's trigger with no name which way it
4476                    // opens, `â–¾` or `â–´`, in place of its label.
4477                    (Some(_), _) if !popup => (1, 1),
4478                    (Some(_), None) => (1, 1),
4479                    // Another popup's trigger shows its name, then the
4480                    // arrow (`Merge options â–¾`), or the arrow alone where
4481                    // words beside it name it (`terminal_layout`'s
4482                    // `arrow_only`).
4483                    (Some(_), Some(l)) => {
4484                        let first = l.split_whitespace().next().unwrap_or("");
4485                        (cols(l).saturating_add(2), cols(first).saturating_add(2))
4486                    }
4487                    (None, l) => l.map_or((0, 0), |l| {
4488                        (cols(l), cols(l.split_whitespace().next().unwrap_or("")))
4489                    }),
4490                }
4491            });
4492        let node = &self.nodes[key as usize];
4493        let view = &node.view_style;
4494        let c = view.corner_radius;
4495        let radius = [c.top_left, c.top_right, c.bottom_right, c.bottom_left]
4496            .into_iter()
4497            .map(|r| r.unwrap_or(view.border_radius).0)
4498            .fold(0.0, f32::max);
4499        let w = view.borders.widths;
4500        let border_color = [w.top, w.right, w.bottom, w.left]
4501            .iter()
4502            .position(|&v| v > Points::ZERO)
4503            .map_or(crate::Color::TRANSPARENT, |i| view.borders.colors[i]);
4504        // A text's characters other than white space, which an absolute
4505        // box pinned over it would hide.
4506        let glyphs = kind == Kind::Text
4507            && node
4508                .layout
4509                .and_then(|l| self.layout.get_node_context(l))
4510                .is_some_and(|cx| match cx {
4511                    LeafContext::Text(cx) => cx.text.text.chars().any(|ch| !ch.is_whitespace()),
4512                    _ => false,
4513                });
4514        // A text with a letter or a digit: a word, not a mark.
4515        let worded = kind == Kind::Text
4516            && node
4517                .layout
4518                .and_then(|l| self.layout.get_node_context(l))
4519                .is_some_and(|cx| match cx {
4520                    LeafContext::Text(cx) => cx.text.text.chars().any(char::is_alphanumeric),
4521                    _ => false,
4522                });
4523        // A text of limited lines, cut short with `…` when it has no room.
4524        let clamped = kind == Kind::Text
4525            && node
4526                .layout
4527                .and_then(|l| self.layout.get_node_context(l))
4528                .is_some_and(|cx| match cx {
4529                    LeafContext::Text(cx) => cx.text.max_lines > 0,
4530                    _ => false,
4531                });
4532        let disclosure = control
4533            && self.nodes[key as usize].props.as_ref().is_some_and(|p| {
4534                p.accessibility.state.expanded.is_some() && !p.accessibility.state.has_popup
4535            });
4536        // A text that shows a disclosure's mark itself (`â–¸ Storage`).
4537        let marked = kind == Kind::Text
4538            && node
4539                .layout
4540                .and_then(|l| self.layout.get_node_context(l))
4541                .is_some_and(|cx| match cx {
4542                    LeafContext::Text(cx) => {
4543                        cx.text.text.trim_start().starts_with(['â–¸', 'â–¾', 'â–¹', 'â–¿'])
4544                    }
4545                    _ => false,
4546                });
4547        terminal_layout::Role {
4548            control,
4549            label,
4550            word,
4551            popup,
4552            disclosure,
4553            marked,
4554            text: matches!(kind, Kind::Text | Kind::Input),
4555            scroll: matches!(kind, Kind::Scroll | Kind::List),
4556            root: key == self.root,
4557            fills: matches!(kind, Kind::Screen | Kind::Modal),
4558            sized: matches!(
4559                kind,
4560                Kind::Native
4561                    | Kind::List
4562                    | Kind::Image
4563                    | Kind::Video
4564                    | Kind::WebView
4565                    | Kind::Shader
4566                    | Kind::GpuView
4567            ),
4568            input: kind == Kind::Input,
4569            glyphs,
4570            worded,
4571            clamped,
4572            radius,
4573            fill: node.resting_fill.unwrap_or(view.background_color),
4574            interactive: {
4575                let events = self.nodes[key as usize].events;
4576                pressable(events) || HANDLED.iter().any(|&e| events.contains(e))
4577            },
4578            animated_fill: self.nodes[key as usize]
4579                .animated
4580                .iter()
4581                .any(|(p, _)| matches!(p, AnimationProp::BackgroundColor)),
4582            border_color,
4583            splitter: match view.cursor {
4584                crate::Cursor::ColResize => terminal_layout::Splitter::Columns,
4585                crate::Cursor::RowResize => terminal_layout::Splitter::Rows,
4586                _ => terminal_layout::Splitter::No,
4587            },
4588            left_out,
4589            overlay: kind == Kind::Overlay,
4590            meter: node.props.as_ref().is_some_and(|p| {
4591                p.accessibility.role == crate::element::AccessibilityRole::Progressbar
4592            }),
4593            // The platform's indicator: none where the app hides it or
4594            // its own built-in bar takes its place.
4595            indicator: match node.scroll.as_deref() {
4596                Some(scroll)
4597                    if scroll.scrollbar != crate::ScrollbarSetting::Hidden
4598                        && scroll.bar.is_none() =>
4599                {
4600                    if scroll.horizontal {
4601                        terminal_layout::Indicator::Horizontal
4602                    } else {
4603                        terminal_layout::Indicator::Vertical
4604                    }
4605                }
4606                _ => terminal_layout::Indicator::No,
4607            },
4608        }
4609    }
4610
4611    /// Tells the layout what its grid takes from node `key`
4612    /// ([`Self::grid_role`]).
4613    fn sync_grid_role(&mut self, key: Key) {
4614        if let Some(layout) = self.nodes[key as usize].layout {
4615            let role = self.grid_role(key);
4616            if self.layout.set_role(layout, role) {
4617                self.needs_layout = true;
4618            }
4619        }
4620    }
4621
4622    /// What a node of its kind needs once made.
4623    fn became(&mut self, key: Key) {
4624        let kind = self.nodes[key as usize].kind;
4625        if kind.derives_layout() {
4626            let style = self.nodes[key as usize]
4627                .layout
4628                .map(|l| self.layout.style(l).clone())
4629                .unwrap_or_else(crate::style::unstyled_layout);
4630            self.nodes[key as usize].base_layout = Some(Box::new(style));
4631        }
4632        let node = &mut self.nodes[key as usize];
4633        if kind == Kind::Text {
4634            node.dirty |= dirty::TEXT_BUILD;
4635        }
4636        if kind == Kind::List {
4637            self.lists.push(key);
4638        }
4639        if matches!(kind, Kind::Scroll | Kind::List | Kind::Input)
4640            && self.builtin_scrollbars.is_some()
4641        {
4642            self.scrollbars_pending.push(key);
4643        }
4644        if kind.is_root() {
4645            self.roots.push(key);
4646        }
4647        if kind == Kind::Input {
4648            self.measure_input(key);
4649        }
4650        if kind == Kind::Overlay
4651            && let Some(layout) = self.nodes[key as usize].layout
4652        {
4653            self.overlay_made(key, layout);
4654        }
4655        self.sync_layout_style(key);
4656    }
4657
4658    /// Node `id`, a view no child is in yet, becomes a `tag` (a component's
4659    /// root of another kind on its host): as if it had been made one. Only
4660    /// while its native view is not sent yet (it was made in this batch);
4661    /// whether it did.
4662    pub(super) fn retag(&mut self, id: NodeId, tag: Tag) -> bool {
4663        let Ok(key) = self.key(id) else {
4664            return false;
4665        };
4666        let kind = Kind::of(tag);
4667        let node = &self.nodes[key as usize];
4668        if node.kind == kind {
4669            return true;
4670        }
4671        let id = node.id;
4672        if node.kind != Kind::View || !node.children.is_empty() {
4673            return false;
4674        }
4675        if node.created && !self.made_in_this_batch(id) {
4676            return false;
4677        }
4678        let node = &self.nodes[key as usize];
4679        // Out of its parent, its native view never made.
4680        let parent = node.parent;
4681        let at = (parent != NO_KEY).then(|| {
4682            let siblings = &self.nodes[parent as usize].children;
4683            let i = siblings.iter().position(|&c| c == key).expect("child");
4684            let next = siblings.get(i + 1).map(|&c| self.nodes[c as usize].id);
4685            (self.nodes[parent as usize].id, next)
4686        });
4687        if parent != NO_KEY {
4688            self.unlink(key, false);
4689        }
4690        // Its `Create` and `Insert` so far go, with the other retagged
4691        // views' in one pass ([`Self::drop_retagged`]).
4692        let retags = self.retags.get_or_insert_default();
4693        retags.made.remove(&id);
4694        retags.retagged.insert(id, self.mount.len());
4695        // The kind's own state and layout.
4696        let fresh = Node::new(id, kind);
4697        let node = &mut self.nodes[key as usize];
4698        node.created = false;
4699        node.kind = kind;
4700        node.image = fresh.image;
4701        node.scroll = fresh.scroll;
4702        node.list = fresh.list;
4703        node.input = fresh.input;
4704        node.root = fresh.root;
4705        node.control = fresh.control;
4706        node.component = fresh.component;
4707        let layout = node.layout.expect("a view has a layout");
4708        self.layout.set_node_context(layout, leaf_context(kind));
4709        self.became(key);
4710        // A native component made in its place reads its style's accent.
4711        self.sync_accent(key);
4712        // What a terminal's layout takes from its kind (a scroll view's
4713        // unbounded content), as if it had been made one.
4714        self.sync_grid_role(key);
4715        if let Some((parent, before)) = at {
4716            let _ = self.insert(parent, id, before);
4717        }
4718        true
4719    }
4720
4721    /// Whether made view `id`'s `Create` is still in the mount items (it was
4722    /// made in this batch). Each item is looked at once a round of renders,
4723    /// not once a view.
4724    fn made_in_this_batch(&mut self, id: NodeId) -> bool {
4725        let retags = self.retags.get_or_insert_default();
4726        let from = retags.seen;
4727        retags
4728            .made
4729            .extend(self.mount[from..].iter().filter_map(|m| match m {
4730                MountItem::Create { id, .. } => Some(*id),
4731                _ => None,
4732            }));
4733        retags.seen = self.mount.len();
4734        let made = retags.made.contains(&id);
4735        self.retagging(self.mount.len() - from);
4736        made
4737    }
4738
4739    /// Drops the `Create` and `Insert` items the retagged views had before
4740    /// they took their kind ([`Self::retag`]), in one pass.
4741    pub(super) fn drop_retagged(&mut self) {
4742        let Some(retags) = self.retags.as_deref_mut() else {
4743            return;
4744        };
4745        if retags.retagged.is_empty() {
4746            return;
4747        }
4748        let retagged = std::mem::take(&mut retags.retagged);
4749        let (seen, made) = (retags.seen, &mut retags.made);
4750        let mut at = 0;
4751        self.mount.retain(|m| {
4752            let i = at;
4753            at += 1;
4754            let (MountItem::Create { id, .. } | MountItem::Insert { child: id, .. }) = m else {
4755                return true;
4756            };
4757            if retagged.get(id).is_some_and(|&then| i < then) {
4758                return false;
4759            }
4760            if i >= seen && matches!(m, MountItem::Create { .. }) {
4761                made.insert(*id);
4762            }
4763            true
4764        });
4765        retags.seen = self.mount.len();
4766        self.retagging(at);
4767    }
4768
4769    /// The round of renders is over: what [`Self::retag`] did goes into
4770    /// the mount items, and its record of them goes (other steps insert
4771    /// items among them).
4772    pub(super) fn end_retags(&mut self) {
4773        self.drop_retagged();
4774        #[cfg(test)]
4775        if self.retags.is_some() {
4776            let rounds = &self.components.retag_rounds;
4777            rounds.set(rounds.get() + 1);
4778        }
4779        self.retags = None;
4780    }
4781
4782    /// Rebuilds the text an input is measured with: what it shows while an
4783    /// input method composes, else its value, else its placeholder, else an
4784    /// empty line.
4785    fn measure_input(&mut self, key: Key) {
4786        let node = &self.nodes[key as usize];
4787        let (Some(input), Some(layout)) = (&node.input, node.layout) else {
4788            return;
4789        };
4790        let shown = input.composing.as_deref().unwrap_or(&input.value);
4791        let placeholder = shown.is_empty() && !input.config.placeholder.is_empty();
4792        let text = self.input_text(
4793            key,
4794            if placeholder {
4795                &input.config.placeholder
4796            } else {
4797                shown
4798            },
4799        );
4800        let field = self.input_text(key, FIELD_SAMPLE);
4801        let cx = self.text_cx(layout);
4802        let same = cx.text.layout_eq(&text);
4803        let same_field = cx.field.as_ref().is_some_and(|f| f.text.layout_eq(&field));
4804        let input = self.nodes[key as usize]
4805            .input
4806            .as_mut()
4807            .expect("input state");
4808        // A value that reads as the placeholder measures the same, but
4809        // its content size is the value's: laid out again to report it.
4810        if same && same_field && input.placeholder_measured == placeholder {
4811            return;
4812        }
4813        input.placeholder_measured = placeholder;
4814        let cx = self.text_cx(layout);
4815        if !same {
4816            let kept = cx.field.take();
4817            *cx = TextContext::new(Arc::new(text));
4818            cx.field = kept;
4819        }
4820        if !same_field {
4821            cx.field = Some(Box::new(TextContext::new(Arc::new(field))));
4822        }
4823        self.layout.mark_dirty(layout);
4824        self.needs_layout = true;
4825    }
4826
4827    /// `content` in the text style of input `key`, as it is measured.
4828    fn input_text(&self, key: Key, content: &str) -> AttributedText {
4829        let node = &self.nodes[key as usize];
4830        let multiline = node.input.as_ref().is_some_and(|i| i.config.multiline);
4831        let mut text = AttributedText {
4832            max_lines: if multiline { 0 } else { 1 },
4833            ..AttributedText::default()
4834        };
4835        let style = scaled(
4836            self.inherited_text_style(key).inherit(&node.text_style),
4837            node.paragraph.font_multiplier(self.font_scale),
4838        );
4839        text.paragraph_strut = Some(style);
4840        if multiline {
4841            text.push(&broken_runs(content), style);
4842        } else {
4843            text.push(content, style);
4844        }
4845        // An empty last line still takes space (a trailing line break, or no
4846        // text at all).
4847        if content.is_empty() || (multiline && content.ends_with('\n')) {
4848            text.push("\u{200b}", style);
4849        }
4850        text
4851    }
4852
4853    /// `key` holds a slot's content in a Rust component's tree (JS's holder
4854    /// of a slot or a render, or the node a view wraps its fill in): while
4855    /// nothing styles its layout and it holds one node, that node is laid
4856    /// out in its place, as the component's own child (`layout_tree`'s
4857    /// "holders laid out through"). A list's holder (an `Items` slot) is a
4858    /// list, laid out as one.
4859    pub(super) fn lay_out_through(&mut self, key: Key) {
4860        let node = &self.nodes[key as usize];
4861        if node.kind == Kind::View
4862            && let Some(layout) = node.layout
4863        {
4864            self.layout.set_holder(layout);
4865            self.needs_layout = true;
4866        }
4867    }
4868
4869    /// Pushes the effective taffy style of `key`: the JS style, adjusted
4870    /// for scroll containers and list cells.
4871    fn sync_layout_style(&mut self, key: Key) {
4872        let node = &self.nodes[key as usize];
4873        let (Some(layout), Some(base)) = (node.layout, node.base_layout.as_deref()) else {
4874            return;
4875        };
4876        let mut style = base.clone();
4877        let kind = node.kind;
4878        if let Some(root) = self.nodes[key as usize].root.as_mut() {
4879            // Laid out again with its size by `layout_roots`.
4880            root.laid_out = None;
4881        }
4882        let node = &self.nodes[key as usize];
4883        match kind {
4884            Kind::Scroll => {
4885                // Children may overflow along the scroll axis; a horizontal
4886                // scroll lays its content out in a row.
4887                let horizontal = node.scroll.as_ref().is_some_and(|s| s.horizontal);
4888                if horizontal {
4889                    style.flex_direction = taffy::FlexDirection::Row;
4890                    style.overflow.x = Overflow::Scroll;
4891                    if node.rtl {
4892                        // Laid out left to right (with the authored sides)
4893                        // and mirrored by `emit_frames`: right to left, a
4894                        // row would overflow to negative offsets.
4895                        std::mem::swap(&mut style.padding.left, &mut style.padding.right);
4896                        std::mem::swap(&mut style.border.left, &mut style.border.right);
4897                        style.direction = taffy::Direction::Ltr;
4898                    }
4899                } else {
4900                    style.overflow.y = Overflow::Scroll;
4901                }
4902            }
4903            Kind::List => {
4904                style.overflow = taffy::Point {
4905                    x: Overflow::Hidden,
4906                    y: Overflow::Hidden,
4907                }
4908            }
4909            Kind::Cell => {
4910                // Cells are their own layout roots (the list gives them a
4911                // definite cross size to stretch, or max-content to align,
4912                // and positions them): a change in one row never relayouts
4913                // the rest of the tree.
4914                let horizontal = self
4915                    .nodes
4916                    .get(node.parent as usize)
4917                    .and_then(|p| p.scroll.as_ref())
4918                    .is_some_and(|s| s.horizontal);
4919                style.position = Position::Relative;
4920                if horizontal {
4921                    style.size.height = taffy::Dimension::percent(1.0);
4922                } else {
4923                    style.size.width = taffy::Dimension::percent(1.0);
4924                }
4925            }
4926            // `position: fixed` in its root view's box.
4927            Kind::Overlay => style.position = Position::Absolute,
4928            _ => {}
4929        }
4930        if node.fixed_view {
4931            style.position = Position::Fixed;
4932        }
4933        if self.layout.set_style(layout, style) {
4934            self.needs_layout = true;
4935        }
4936    }
4937
4938    fn set_inline_style(
4939        &mut self,
4940        id: NodeId,
4941        style: Box<Style>,
4942        patch: StylePatch,
4943    ) -> Result<(), ApplyError> {
4944        let key = self.key(id)?;
4945        let node = &mut self.nodes[key as usize];
4946        node.inline_style = patch;
4947        if node.classes.is_some() || node.spaced || node.inline_style.reads_current_color() {
4948            self.restyle(key);
4949            return Ok(());
4950        }
4951        let mut props = node.class_props.as_deref().cloned().unwrap_or_default();
4952        style.node_props(&mut props);
4953        self.set_class_props(key, props);
4954        self.set_style(id, *style)
4955    }
4956
4957    fn set_style(&mut self, id: NodeId, style: Style) -> Result<(), ApplyError> {
4958        let key = self.key(id)?;
4959        let Style {
4960            mut layout,
4961            mut view,
4962            text,
4963            paint,
4964            animated,
4965            z_index,
4966            vertical_align,
4967            direction,
4968            logical,
4969            pending,
4970            perspective,
4971        } = style;
4972        if animated
4973            .iter()
4974            .any(|(p, _)| matches!(p, AnimationProp::BackgroundColor))
4975        {
4976            // The animated color must show: a gradient drawn over it would
4977            // hide it.
4978            view.clear_background_images();
4979        }
4980        if key != self.root {
4981            self.nodes[key as usize].direction = direction;
4982        }
4983        let rtl = self.resolved_rtl(key);
4984        let sticky = prepare_layout(
4985            &mut layout,
4986            &mut view,
4987            &logical,
4988            rtl,
4989            pending.sticky_position,
4990        );
4991        // An input always clips: it scrolls its own text, so text taller than
4992        // its box (a fixed height, a `maxHeight`) stays in it and must not
4993        // grow the content size of a scroll view around it.
4994        let input = self.nodes[key as usize].kind == Kind::Input;
4995        clip_overflow(&mut layout, view.overflow_hidden || input);
4996        self.install_style(
4997            key,
4998            StyleRecord {
4999                layout,
5000                view,
5001                text,
5002                paint: (paint != PaintStyle::default()).then(|| Rc::new(paint)),
5003                animated,
5004                sticky,
5005                perspective,
5006                object_fit: pending.object_fit,
5007                wants_fixed: pending.fixed_position,
5008                env: pending.env,
5009                z_index,
5010                vertical_align,
5011                has_logical: !logical.is_empty(),
5012                rtl,
5013            },
5014        );
5015        Ok(())
5016    }
5017
5018    /// Installs a cached [`classes::ResolvedClassStyle`] on `key`, sharing
5019    /// its records with the other nodes styled alike.
5020    fn apply_resolved_style(&mut self, key: Key, resolved: &classes::ResolvedClassStyle) {
5021        self.set_class_props_shared(key, resolved.props.as_ref());
5022        self.install_style(
5023            key,
5024            StyleRecord {
5025                layout: resolved.layout.clone(),
5026                view: resolved.view.clone(),
5027                text: resolved.text.clone(),
5028                paint: resolved.paint.clone(),
5029                animated: Vec::new(),
5030                sticky: resolved.sticky,
5031                perspective: resolved.perspective,
5032                object_fit: resolved.object_fit,
5033                wants_fixed: resolved.wants_fixed,
5034                env: crate::style::EnvEdges::default(),
5035                z_index: resolved.z_index,
5036                vertical_align: resolved.vertical_align,
5037                has_logical: resolved.has_logical,
5038                rtl: resolved.rtl,
5039            },
5040        );
5041    }
5042
5043    /// Makes `record` `key`'s style and marks what changed: the one path of
5044    /// a node resolved alone ([`Self::set_style`]) and of a cached class
5045    /// style ([`Self::apply_resolved_style`]).
5046    fn install_style(
5047        &mut self,
5048        key: Key,
5049        record: StyleRecord<impl LayoutSlot, impl StyleSlot<ViewStyle>, impl StyleSlot<TextStyle>>,
5050    ) {
5051        let StyleRecord {
5052            mut layout,
5053            view,
5054            text,
5055            paint,
5056            animated,
5057            sticky,
5058            perspective,
5059            object_fit,
5060            wants_fixed,
5061            env,
5062            z_index,
5063            vertical_align,
5064            has_logical,
5065            rtl,
5066        } = record;
5067        let node = &mut self.nodes[key as usize];
5068        node.has_logical = has_logical;
5069        if node.sticky.as_deref() != sticky.as_ref() {
5070            self.set_sticky(key, sticky.map(Box::new));
5071        }
5072        let node = &mut self.nodes[key as usize];
5073        if node.child_perspective != perspective {
5074            node.child_perspective = perspective;
5075            // Its children's transforms compose it (their animated steps
5076            // move by its steps).
5077            let children = node.children.clone();
5078            for c in children {
5079                self.mark(c, dirty::VIEW | dirty::ANIMATION);
5080            }
5081        }
5082        let node = &mut self.nodes[key as usize];
5083        if node.object_fit != object_fit {
5084            node.object_fit = object_fit;
5085            if node.image.is_some() {
5086                self.mark(key, dirty::IMAGE);
5087            } else if let Some(control) = node.control.as_mut() {
5088                // A video is contained by default.
5089                let fit = object_fit.unwrap_or(ResizeMode::Contain);
5090                apply_native(control, NativeProp::VideoResizeMode(fit));
5091                self.mark(key, dirty::NATIVE);
5092            }
5093        }
5094        let node = &mut self.nodes[key as usize];
5095        if node.wants_fixed != wants_fixed {
5096            // Made an overlay, or a view again: at once while it is in no
5097            // parent (classes are set before the node is inserted), else as
5098            // the commit starts.
5099            node.wants_fixed = wants_fixed;
5100            let id = node.id;
5101            if node.parent == NO_KEY {
5102                self.fix_or_unfix(key);
5103            } else {
5104                self.fixed_changed.push((key, id));
5105            }
5106        }
5107        // `env()`'s terms, on the edges their declarations name (left and
5108        // right are physical, right to left too).
5109        let env = (!env.is_empty()).then(|| (env, self.env_insets(key, &env)));
5110        let node = &mut self.nodes[key as usize];
5111        let id = node.id;
5112        match env {
5113            Some(env) => {
5114                node.env = Some(Box::new(env));
5115                self.env_styled.insert(id);
5116            }
5117            None => {
5118                if node.env.take().is_some() {
5119                    self.env_styled.remove(&id);
5120                }
5121            }
5122        }
5123        let node = &mut self.nodes[key as usize];
5124        let mut extra = node.insets.as_deref().copied();
5125        if let Some((_, applied)) = node.env.as_deref() {
5126            let sum = |a: EdgeInsets, b: EdgeInsets| EdgeInsets {
5127                top: a.top + b.top,
5128                right: a.right + b.right,
5129                bottom: a.bottom + b.bottom,
5130                left: a.left + b.left,
5131            };
5132            let [p, m] = extra.unwrap_or_default();
5133            extra = Some([sum(p, applied[0]), sum(m, applied[1])]);
5134        }
5135        if let Some([padding, margin]) = extra.as_ref() {
5136            let layout = layout.to_mut();
5137            // On top of points; percentages cannot take an addition.
5138            let add = |p: &mut taffy::LengthPercentage, d: f32| {
5139                if let taffy::style::ExpandedLengthPercentage::Length(v) = p.expand() {
5140                    *p = taffy::LengthPercentage::length(v + d);
5141                }
5142            };
5143            add(&mut layout.padding.top, padding.top.0);
5144            add(&mut layout.padding.right, padding.right.0);
5145            add(&mut layout.padding.bottom, padding.bottom.0);
5146            add(&mut layout.padding.left, padding.left.0);
5147            // `auto` margins stay automatic.
5148            let add = |m: &mut taffy::LengthPercentageAuto, d: f32| {
5149                if let taffy::style::ExpandedLengthPercentageAuto::Length(v) = m.expand() {
5150                    *m = taffy::LengthPercentageAuto::length(v + d);
5151                }
5152            };
5153            add(&mut layout.margin.top, margin.top.0);
5154            add(&mut layout.margin.right, margin.right.0);
5155            add(&mut layout.margin.bottom, margin.bottom.0);
5156            add(&mut layout.margin.left, margin.left.0);
5157        }
5158        let node = &mut self.nodes[key as usize];
5159        let flipped = node.rtl != rtl;
5160        node.rtl = rtl;
5161        // A shared record installed already (or an equal one) changes
5162        // nothing visual: the comparisons below are skipped.
5163        let view_same = view.same(&node.view_style);
5164        let new_view = view.get();
5165        // `objectPosition` is the image's (`MountItem::Image`), not the view's.
5166        let position_changed =
5167            !view_same && node.view_style.object_position != new_view.object_position;
5168        let view_changed = !view_same
5169            && (!position_changed
5170                || node.view_style
5171                    != ViewStyle {
5172                        object_position: node.view_style.object_position,
5173                        ..new_view.clone()
5174                    });
5175        // A span's background and visibility are part of its block's text.
5176        let span_drawing_changed = !view_same
5177            && node.inline
5178            && node.kind == Kind::Text
5179            && (span_background(&node.view_style, node.id) != span_background(new_view, node.id)
5180                || node.view_style.hidden != new_view.hidden);
5181        let text_same = text.same(&node.text_style);
5182        let text_changed = !text_same || span_drawing_changed;
5183        // What its children inherit as `currentColor`.
5184        let passed_color = |node: &Node, text: &TextStyle| text.color.or(node.inherited_color);
5185        let color_passed =
5186            !text_same && passed_color(node, &node.text_style) != passed_color(node, text.get());
5187        let animation_changed = node.animated != animated;
5188        let paint_changed = !opt_rc_eq(node.paint.as_ref(), paint.as_ref());
5189        let z_changed = node.z_index != z_index;
5190        // An attachment's place in its line is part of its block's text.
5191        let align_changed =
5192            node.vertical_align != vertical_align && node.inline && node.kind != Kind::Text;
5193        // ... and so is the content's of a render placed there.
5194        let content_align_changed = node.vertical_align != vertical_align && !node.inline;
5195        let accent_changed = !view_same && node.view_style.accent_color != new_view.accent_color;
5196        view.install(&mut node.view_style);
5197        text.install(&mut node.text_style);
5198        if paint_changed {
5199            node.paint = paint;
5200        }
5201        node.animated = animated;
5202        node.z_index = z_index;
5203        node.vertical_align = vertical_align;
5204        // Its fill, border and corners (`terminal_layout::Role`).
5205        self.sync_grid_role(key);
5206        if align_changed {
5207            self.mark_text_block(key);
5208        } else if content_align_changed && let Some(place) = self.placed_in_text(key) {
5209            self.mark_text_block(place);
5210        }
5211        if z_changed {
5212            self.restack(key);
5213        }
5214        let node = &mut self.nodes[key as usize];
5215        fn keep_base(slot: &mut Option<Box<taffy::Style>>, layout: impl LayoutSlot) {
5216            match slot {
5217                Some(base) => **base = layout.into_owned(),
5218                None => *slot = Some(Box::new(layout.into_owned())),
5219            }
5220        }
5221        if node.kind.derives_layout() || node.fixed_view {
5222            keep_base(&mut node.base_layout, layout);
5223            self.sync_layout_style(key);
5224        } else if let Some(l) = node.layout {
5225            // A style that only changed what is painted lays nothing out.
5226            if layout.set_on(&mut self.layout, l) {
5227                self.needs_layout = true;
5228            }
5229        } else if node.kind == Kind::Text {
5230            // A span: kept for when it is a block again. Its padding is
5231            // part of its block's text (horizontal: room in the line;
5232            // vertical: its background's).
5233            let padding = |l: &taffy::Style| l.padding;
5234            let padded = node.base_layout.as_deref().map(padding) != Some(padding(layout.get()));
5235            keep_base(&mut node.base_layout, layout);
5236            if padded && node.inline {
5237                self.mark_text_block(key);
5238            }
5239        }
5240        let mut flags = 0;
5241        if view_changed {
5242            flags |= dirty::VIEW;
5243            // A drawing filling with the view's background paints the new
5244            // one.
5245            if self.nodes[key as usize]
5246                .drawing
5247                .as_ref()
5248                .is_some_and(|d| d.paints_background())
5249            {
5250                flags |= dirty::CANVAS;
5251            }
5252        }
5253        if position_changed && self.nodes[key as usize].image.is_some() {
5254            flags |= dirty::IMAGE;
5255        }
5256        if accent_changed {
5257            self.sync_accent(key);
5258        }
5259        // A sticky view's animated inset is part of its range.
5260        self.sticky_changed |= animation_changed && self.nodes[key as usize].sticky.is_some();
5261        let parent = self.nodes[key as usize].parent;
5262        let in_perspective =
5263            parent != NO_KEY && self.nodes[parent as usize].child_perspective.is_some();
5264        if animation_changed
5265            || view_changed && in_perspective && !self.nodes[key as usize].animated.is_empty()
5266        {
5267            // Its animated steps move with its parent's perspective.
5268            flags |= dirty::ANIMATION;
5269        }
5270        if flags != 0 {
5271            self.mark(key, flags);
5272        }
5273        if text_changed || flipped {
5274            match self.nodes[key as usize].kind {
5275                Kind::Text => {
5276                    self.mark_text_block(key);
5277                    // Texts inside its attachments take its color.
5278                    if color_passed {
5279                        self.mark_inheriting_text(key);
5280                    }
5281                }
5282                Kind::Input => {
5283                    self.measure_input(key);
5284                    self.mark(key, dirty::INPUT);
5285                }
5286                // Text inside inherits it (CSS).
5287                _ if text_changed => self.mark_inheriting_text(key),
5288                _ => {}
5289            }
5290        }
5291        if color_passed {
5292            let node = &self.nodes[key as usize];
5293            let color = node.text_style.color.or(node.inherited_color);
5294            self.inherit_color(key, color);
5295        }
5296        // A canvas painting with its view's style (`currentColor` too) sees
5297        // the change, and so do the ones inside it, which inherit it.
5298        if paint_changed || text_changed {
5299            self.mark_view_painted(key);
5300        }
5301        if flipped {
5302            self.update_children_direction(key);
5303            // Its own `direction` turned it: classes resolved for the other
5304            // direction (`pl-*`, `rtl:`) resolve again.
5305            if self.reads_direction(key) {
5306                self.restyle(key);
5307            }
5308        }
5309    }
5310
5311    /// Marks the canvases at and inside `key` that paint with their view's
5312    /// style ([`crate::canvas::Drawing::view_paints`]) to be sent again.
5313    fn mark_view_painted(&mut self, key: Key) {
5314        let mut stack = vec![key];
5315        while let Some(k) = stack.pop() {
5316            let node = &self.nodes[k as usize];
5317            match node.kind {
5318                Kind::Canvas => {
5319                    if node
5320                        .drawing
5321                        .as_ref()
5322                        .is_some_and(|d| !d.view_paints.is_empty())
5323                    {
5324                        self.mark(k, dirty::CANVAS);
5325                    }
5326                }
5327                Kind::Text | Kind::RawText | Kind::Input => {}
5328                // An `svg()` drawn as an image paints `currentColor` too.
5329                _ if node.image.as_ref().is_some_and(|i| i.svg_current_color) => {
5330                    self.mark(k, dirty::IMAGE);
5331                }
5332                _ => stack.extend_from_slice(&self.nodes[k as usize].children),
5333            }
5334        }
5335    }
5336
5337    /// Canvas `key`'s `drawing` as its platform gets it: its
5338    /// [`crate::canvas::Drawing::view_paints`] resolved with its style and
5339    /// its box.
5340    fn mounted_drawing(
5341        &self,
5342        key: Key,
5343        drawing: &Arc<crate::canvas::Drawing>,
5344    ) -> Arc<crate::canvas::Drawing> {
5345        if drawing.view_paints.is_empty() {
5346            return drawing.clone();
5347        }
5348        let node = &self.nodes[key as usize];
5349        let (paint, current) = self.resolved_paint(key);
5350        let style = &node.view_style;
5351        let images = style
5352            .effects
5353            .as_deref()
5354            .map_or(&[][..], |e| &e.background_images[..]);
5355        let size = if node.frame == Bounds::UNSET {
5356            Size::default()
5357        } else {
5358            node.frame.size
5359        };
5360        Arc::new(drawing.painted(&paint, current, style.background_color, images, size))
5361    }
5362
5363    /// Sends the canvases fitting a view box that changed or were given
5364    /// another size this round, with the size the layout gave them.
5365    fn send_fitted(&mut self) {
5366        let mut pending = std::mem::take(&mut self.fitted_pending);
5367        pending.sort_unstable();
5368        pending.dedup();
5369        for &key in &pending {
5370            let Some(node) = self.nodes.get(key as usize) else {
5371                continue;
5372            };
5373            if !node.created {
5374                continue;
5375            }
5376            let Some(drawing) = &node.drawing else {
5377                continue;
5378            };
5379            let (id, drawing) = (node.id, self.mounted_drawing(key, drawing));
5380            self.mount.push(MountItem::Canvas { id, drawing });
5381        }
5382        pending.clear();
5383        self.fitted_pending = pending;
5384    }
5385
5386    /// The paint properties canvas `key` paints with (its own over those
5387    /// of the views around it, as CSS inherits them) and its text color,
5388    /// for `currentColor`.
5389    fn resolved_paint(&self, key: Key) -> (PaintStyle, crate::style::Color) {
5390        let node = &self.nodes[key as usize];
5391        let mut paint = node.paint.as_deref().cloned().unwrap_or_default();
5392        let mut k = node.parent;
5393        while k != NO_KEY {
5394            if let Some(p) = self.nodes[k as usize].paint.as_deref() {
5395                paint = paint.inherit(p);
5396            }
5397            k = self.nodes[k as usize].parent;
5398        }
5399        let color = node
5400            .text_style
5401            .color
5402            .unwrap_or_else(|| self.inherited_text_style(key).color);
5403        (paint, color)
5404    }
5405
5406    /// The direction `key` lays out in: its own, else its parent's (the
5407    /// root's while detached).
5408    pub(super) fn resolved_rtl(&self, key: Key) -> bool {
5409        let node = &self.nodes[key as usize];
5410        if let Some(rtl) = node.direction {
5411            return rtl;
5412        }
5413        match node.parent {
5414            NO_KEY => key != self.root && self.nodes[self.root as usize].rtl,
5415            parent => self.nodes[parent as usize].rtl,
5416        }
5417    }
5418
5419    /// Re-resolves the direction of `key` (moved, or its parent's changed)
5420    /// and of the nodes inheriting it.
5421    fn update_direction(&mut self, key: Key) {
5422        let rtl = self.resolved_rtl(key);
5423        if self.nodes[key as usize].rtl == rtl {
5424            return;
5425        }
5426        self.flip_direction(key, rtl);
5427        self.update_children_direction(key);
5428    }
5429
5430    fn update_children_direction(&mut self, key: Key) {
5431        let children = self.nodes[key as usize].children.clone();
5432        for child in children {
5433            self.update_direction(child);
5434        }
5435    }
5436
5437    /// Lays `key` out in the other direction. Its left and right properties
5438    /// keep their sides, as in CSS; its start / end ones move with the
5439    /// direction, so it is styled again when it has some.
5440    fn flip_direction(&mut self, key: Key, rtl: bool) {
5441        let direction = if rtl {
5442            taffy::Direction::Rtl
5443        } else {
5444            taffy::Direction::Ltr
5445        };
5446        let node = &mut self.nodes[key as usize];
5447        node.rtl = rtl;
5448        if let Some(list) = node.list.as_mut() {
5449            let mirrored = rtl && list.horizontal;
5450            list.set_mirrored(mirrored);
5451        }
5452        // A spaced child's margin is on its end side.
5453        let logical = node.has_logical || node.spaced;
5454        let kind = node.kind;
5455        if let Some(base) = node.base_layout.as_deref_mut() {
5456            base.direction = direction;
5457            self.sync_layout_style(key);
5458        } else if let Some(l) = node.layout {
5459            let mut layout = self.layout.style(l).clone();
5460            layout.direction = direction;
5461            self.layout.set_style(l, layout);
5462            self.needs_layout = true;
5463        }
5464        self.mark(key, dirty::VIEW);
5465        if logical || self.reads_direction(key) {
5466            self.restyle(key);
5467        }
5468        let node = &mut self.nodes[key as usize];
5469        let id = node.id;
5470        if let Some(scroll) = node.scroll.as_mut()
5471            && scroll.horizontal
5472            && node.list.as_ref().is_none_or(|l| !l.parent)
5473        {
5474            // Back to the start side: the right end right to left (once the
5475            // content is known again).
5476            scroll.content = None;
5477            if !rtl {
5478                self.commands.push((
5479                    id,
5480                    Command::ScrollTo {
5481                        x: Points::ZERO,
5482                        y: Points::ZERO,
5483                        animated: false,
5484                    },
5485                ));
5486            }
5487            self.mark(key, dirty::SCROLL);
5488        }
5489        match kind {
5490            Kind::Text => self.mark_text_block(key),
5491            Kind::Input => {
5492                self.measure_input(key);
5493                self.mark(key, dirty::INPUT);
5494            }
5495            _ => {}
5496        }
5497    }
5498
5499    /// Media source `uri` as the app may load it ([`crate::access::Access::media_url`]
5500    /// against [`Core::set_base_url`]'s URL): `Some(None)` as written,
5501    /// `Some(Some(url))` the URL to load in its place, `None` refused.
5502    fn media_source(&self, uri: &str) -> Option<Option<Arc<str>>> {
5503        match self
5504            .access
5505            .media_url(uri, self.base_url.as_deref(), Some(&self.media_files))?
5506        {
5507            std::borrow::Cow::Borrowed(_) => Some(None),
5508            std::borrow::Cow::Owned(url) => Some(Some(url.into())),
5509        }
5510    }
5511
5512    /// The images `drawing` draws as the app may load them
5513    /// ([`crate::access::Access::media_url`] against [`Core::set_base_url`]'s
5514    /// URL and the `capabilities.fs.read` roots): one the check grants is
5515    /// rewritten to what it granted (a file's canonical path, a URL's
5516    /// serialization); one it refuses is dropped and reported. A network
5517    /// answer is remembered for the session; a file's changes with the
5518    /// disk and is never remembered. On-screen canvases check every
5519    /// drawing (`Op::Draw`); offscreen renders check the same way before
5520    /// the platform draws (`canvas_render.rs`).
5521    fn check_canvas_images(&mut self, drawing: &mut crate::canvas::Drawing) {
5522        if self.access.is_unrestricted() {
5523            return;
5524        }
5525        let access = self.access.clone();
5526        let base = self.base_url.clone();
5527        let files = self.media_files.clone();
5528        let mut refused = Vec::new();
5529        let checked = &mut self.canvas_images;
5530        // Each file's answer for this drawing: a drawing names the same
5531        // image many times (a game's map draws thousands of tiles from a
5532        // few sheets), and resolving a file is disk work, once per image.
5533        let mut files_here: rustc_hash::FxHashMap<Arc<str>, Option<Arc<str>>> =
5534            rustc_hash::FxHashMap::default();
5535        drawing.ops.retain_mut(|op| match op {
5536            crate::canvas::CanvasOp::DrawImage { image, .. } => {
5537                let granted = match checked
5538                    .get(&image.uri)
5539                    .or_else(|| files_here.get(&image.uri))
5540                {
5541                    Some(granted) => granted.clone(),
5542                    None => {
5543                        let granted = access
5544                            .media_url(&image.uri, base.as_deref(), Some(&files))
5545                            .map(|url| match url {
5546                                std::borrow::Cow::Owned(url) => Arc::from(url),
5547                                std::borrow::Cow::Borrowed(_) => image.uri.clone(),
5548                            });
5549                        if crate::access::media_capability(&image.uri, base.as_deref()) == "network"
5550                        {
5551                            if checked.len() >= CANVAS_IMAGES {
5552                                checked.clear();
5553                            }
5554                            checked.insert(image.uri.clone(), granted.clone());
5555                        } else {
5556                            files_here.insert(image.uri.clone(), granted.clone());
5557                        }
5558                        granted
5559                    }
5560                };
5561                match granted {
5562                    Some(url) => {
5563                        image.uri = url;
5564                        true
5565                    }
5566                    None => {
5567                        refused.push(image.uri.clone());
5568                        false
5569                    }
5570                }
5571            }
5572            _ => true,
5573        });
5574        // Reported once per drawing, not per draw.
5575        refused.sort_unstable();
5576        refused.dedup();
5577        for uri in refused {
5578            self.deny(media_not_granted(
5579                "a canvas image",
5580                &uri,
5581                self.base_url.as_deref(),
5582            ));
5583        }
5584    }
5585
5586    /// `desktop`'s menu and tray icons as the app may load them
5587    /// ([`Self::media_source`]): a refused icon is dropped (the item shows
5588    /// none) and reported.
5589    /// Keeps the application menu and its labels where `MenuBar` reads them
5590    /// ([`crate::element::desktop::application_menu`]).
5591    fn remember_app_menu(&mut self, desktop: &crate::desktop::DesktopCommand) {
5592        use crate::desktop::DesktopCommand;
5593        let change: Box<dyn FnOnce(&mut crate::element::menus::AppMenu)> = match desktop {
5594            DesktopCommand::SetMenu(items) => {
5595                let items = items.clone();
5596                Box::new(move |m| m.items = items)
5597            }
5598            DesktopCommand::SetMenuLabels(labels) => {
5599                let labels = (**labels).clone();
5600                Box::new(move |m| m.labels = labels)
5601            }
5602            _ => return,
5603        };
5604        let _entered = self.components.runtime.enter();
5605        let signal = crate::element::menus::app_menu(&self.components.executor.menus);
5606        signal.update(change);
5607    }
5608
5609    fn check_menu_icons(&mut self, desktop: &mut crate::desktop::DesktopCommand) {
5610        use crate::{
5611            ImageSource,
5612            desktop::{DesktopCommand, MenuItem},
5613        };
5614        if self.access.is_unrestricted() {
5615            return;
5616        }
5617        let mut check = |icon: &mut Option<ImageSource>| {
5618            let Some(source) = icon else { return };
5619            match self.media_source(&source.uri) {
5620                Some(Some(url)) => source.uri = url,
5621                Some(None) => {}
5622                None => {
5623                    let message =
5624                        media_not_granted("the menu icon", &source.uri, self.base_url.as_deref());
5625                    *icon = None;
5626                    self.deny(message);
5627                }
5628            }
5629        };
5630        fn each(items: &mut [MenuItem], check: &mut impl FnMut(&mut Option<ImageSource>)) {
5631            for item in items {
5632                match item {
5633                    MenuItem::Action(action) => check(&mut action.icon),
5634                    MenuItem::Submenu { items, icon, .. } => {
5635                        check(icon);
5636                        each(items, check);
5637                    }
5638                    MenuItem::Separator => {}
5639                }
5640            }
5641        }
5642        let checked = |items: &Arc<[MenuItem]>, check: &mut dyn FnMut(&mut Option<ImageSource>)| {
5643            let mut items = items.to_vec();
5644            each(&mut items, &mut |icon| check(icon));
5645            Arc::<[MenuItem]>::from(items)
5646        };
5647        match desktop {
5648            DesktopCommand::SetMenu(Some(items)) | DesktopCommand::PopupMenu { items, .. } => {
5649                *items = checked(items, &mut check);
5650            }
5651            DesktopCommand::SetTray(Some(tray)) => {
5652                check(&mut tray.icon);
5653                tray.menu = checked(&tray.menu, &mut check);
5654            }
5655            _ => {}
5656        }
5657    }
5658
5659    /// `prop` with what the app may not reach removed: a refused image,
5660    /// video or web view source shows nothing and fails (`onError` with
5661    /// `code` `ERR_ACCESS_DENIED`).
5662    fn check_prop(&mut self, key: Key, prop: Prop) -> Prop {
5663        let prop = match prop {
5664            Prop::Native(NativeProp::AllowOrigin(Some(origin))) => {
5665                Prop::Native(NativeProp::AllowOrigin(self.check_allow_origin(&origin)))
5666            }
5667            Prop::Native(NativeProp::AllowNavigation(Some(hosts))) => {
5668                match crate::access::WebHosts::parse(&hosts) {
5669                    Ok(_) => Prop::Native(NativeProp::AllowNavigation(Some(hosts))),
5670                    Err(e) => {
5671                        self.deny(format!("`allowNavigation`: {e}"));
5672                        Prop::Native(NativeProp::AllowNavigation(None))
5673                    }
5674                }
5675            }
5676            prop => prop,
5677        };
5678        if self.access.is_unrestricted() {
5679            return prop;
5680        }
5681        let node = &self.nodes[key as usize];
5682        let (id, kind) = (node.id, node.kind);
5683        // With `webview.runtimeOrigin`, a URL `webview.hosts` does not
5684        // grant waits for the web view's `allowOrigin`, which may come
5685        // after it in this render: it is checked when the props go out.
5686        if kind == Kind::WebView
5687            && self.access.allows_runtime_origin()
5688            && let Some(url) = web_url(&prop)
5689            && !url.is_empty()
5690            && !self.access.allows_webview_with(url, self.web_origin(key))
5691        {
5692            self.web_unchecked.insert((key, id));
5693            return prop;
5694        }
5695        // Always reported: the `onError` listener may be set after the
5696        // source (JS finds the handler when the event is delivered).
5697        let report = |core: &mut Self, message: String| core.report_access_denied(id, message);
5698        let refuse = |core: &mut Self, what: &str, uri: &str, capability: &str| {
5699            report(core, not_granted(what, uri, capability));
5700        };
5701        let refuse_media = |core: &mut Self, what: &str, uri: &str| {
5702            let message = media_not_granted(what, uri, core.base_url.as_deref());
5703            report(core, message);
5704        };
5705        let no_webviews = |core: &mut Self| {
5706            report(
5707                core,
5708                "web views are not granted: add `webview` to capabilities in nsh.json".into(),
5709            );
5710        };
5711        match prop {
5712            // A loader loads what the check granted (`Access::media_url`).
5713            Prop::Source(Some(mut source)) => match self.media_source(&source.uri) {
5714                Some(granted) => {
5715                    source.uri = granted.unwrap_or(source.uri);
5716                    Prop::Source(Some(source))
5717                }
5718                None => {
5719                    refuse_media(self, "the image", &source.uri);
5720                    Prop::Source(None)
5721                }
5722            },
5723            Prop::Image(ImageProp::Placeholder(Some(mut source))) => {
5724                match self.media_source(&source.uri) {
5725                    Some(granted) => {
5726                        source.uri = granted.unwrap_or(source.uri);
5727                        Prop::Image(ImageProp::Placeholder(Some(source)))
5728                    }
5729                    None => {
5730                        refuse_media(self, "the placeholder", &source.uri);
5731                        Prop::Image(ImageProp::Placeholder(None))
5732                    }
5733                }
5734            }
5735            Prop::Native(NativeProp::Src(Some(url))) if kind == Kind::Video => {
5736                match self.media_source(&url) {
5737                    Some(granted) => Prop::Native(NativeProp::Src(Some(granted.unwrap_or(url)))),
5738                    None => {
5739                        refuse_media(self, "the video", &url);
5740                        Prop::Native(NativeProp::Src(None))
5741                    }
5742                }
5743            }
5744            Prop::Native(NativeProp::Poster(Some(url))) if kind == Kind::Video => {
5745                match self.media_source(&url) {
5746                    Some(granted) => Prop::Native(NativeProp::Poster(Some(granted.unwrap_or(url)))),
5747                    None => {
5748                        refuse_media(self, "the poster", &url);
5749                        Prop::Native(NativeProp::Poster(None))
5750                    }
5751                }
5752            }
5753            Prop::Native(NativeProp::Src(Some(url)))
5754                if kind == Kind::WebView
5755                    && !self.access.allows_webview_with(&url, self.web_origin(key)) =>
5756            {
5757                refuse(self, "the web page", &url, "webview.hosts");
5758                Prop::Native(NativeProp::Src(None))
5759            }
5760            Prop::Native(NativeProp::Html(Some(_)))
5761                if kind == Kind::WebView && !self.access.allows_webviews() =>
5762            {
5763                no_webviews(self);
5764                Prop::Native(NativeProp::Html(None))
5765            }
5766            Prop::Native(NativeProp::Source(crate::WebSource::Uri(uri))) if kind == Kind::Video => {
5767                match self.media_source(&uri) {
5768                    Some(granted) => Prop::Native(NativeProp::Source(crate::WebSource::Uri(
5769                        granted.unwrap_or(uri),
5770                    ))),
5771                    None => {
5772                        refuse_media(self, "the video", &uri);
5773                        Prop::Native(NativeProp::Source(crate::WebSource::None))
5774                    }
5775                }
5776            }
5777            Prop::Native(NativeProp::Source(crate::WebSource::Uri(uri)))
5778                if kind == Kind::WebView
5779                    && !self.access.allows_webview_with(&uri, self.web_origin(key)) =>
5780            {
5781                refuse(self, "the web page", &uri, "webview.hosts");
5782                Prop::Native(NativeProp::Source(crate::WebSource::None))
5783            }
5784            Prop::Native(NativeProp::Source(crate::WebSource::Html { .. }))
5785                if kind == Kind::WebView && !self.access.allows_webviews() =>
5786            {
5787                no_webviews(self);
5788                Prop::Native(NativeProp::Source(crate::WebSource::None))
5789            }
5790            // Inline HTML with a base URL runs at that URL's origin (WebKit's
5791            // `loadHTMLString:baseURL:`, Android's `loadDataWithBaseURL`,
5792            // Windows answering the base URL's request with it): the base
5793            // URL takes the grant a page there would, and without it the
5794            // HTML loads with no base. Without web views at all, the arms
5795            // above refuse the HTML itself, and that is the one error.
5796            Prop::Native(NativeProp::BaseUrl(Some(url)))
5797                if kind == Kind::WebView
5798                    && !url.is_empty()
5799                    && self.access.allows_webviews()
5800                    && !self.access.allows_webview_with(&url, self.web_origin(key)) =>
5801            {
5802                refuse(self, "the base URL", &url, "webview.hosts");
5803                Prop::Native(NativeProp::BaseUrl(None))
5804            }
5805            Prop::Native(NativeProp::Source(crate::WebSource::Html {
5806                html,
5807                base_url: Some(url),
5808            })) if kind == Kind::WebView
5809                && !url.is_empty()
5810                && !self.access.allows_webview_with(&url, self.web_origin(key)) =>
5811            {
5812                refuse(self, "the base URL", &url, "webview.hosts");
5813                Prop::Native(NativeProp::Source(crate::WebSource::Html {
5814                    html,
5815                    base_url: None,
5816                }))
5817            }
5818            prop => prop,
5819        }
5820    }
5821
5822    /// `allowOrigin` as the web view keeps it: the origin in its one
5823    /// written form, or none (with a message) when it is not an origin or
5824    /// the app may not add one (`webview.runtimeOrigin`).
5825    fn check_allow_origin(&mut self, origin: &str) -> Option<Arc<str>> {
5826        match crate::access::WebOrigin::parse(origin) {
5827            Err(e) => {
5828                self.deny(format!("`allowOrigin`: {e}"));
5829                None
5830            }
5831            Ok(_) if !self.access.is_unrestricted() && !self.access.allows_runtime_origin() => {
5832                self.deny(
5833                    "`allowOrigin` is not granted: add `\"runtimeOrigin\": true` to capabilities.webview in nsh.json"
5834                        .into(),
5835                );
5836                None
5837            }
5838            Ok(o) => Some(o.to_string().into()),
5839        }
5840    }
5841
5842    /// The `allowOrigin` of the web view `key`, when it has one.
5843    fn web_origin(&self, key: Key) -> Option<&crate::access::WebOrigin> {
5844        match self.nodes[key as usize].control.as_deref() {
5845            Some(NativeProps::WebView(p)) => p.allow_origin.as_ref(),
5846            _ => None,
5847        }
5848    }
5849
5850    /// Checks the URLs of web view `key` that waited for its `allowOrigin`
5851    /// ([`Self::web_unchecked`]) as its props go out: what neither
5852    /// `webview.hosts` nor its origin grants is refused as a prop would be
5853    /// (`onError` with `ERR_ACCESS_DENIED`, and nothing loaded).
5854    fn settle_web_urls(&mut self, key: Key) {
5855        let id = self.nodes[key as usize].id;
5856        if !self.web_unchecked.remove(&(key, id)) {
5857            return;
5858        }
5859        let access = &self.access;
5860        let Some(NativeProps::WebView(p)) = self.nodes[key as usize].control.as_deref_mut() else {
5861            return;
5862        };
5863        let origin = p.allow_origin.clone();
5864        let refuses =
5865            |url: &str| !url.is_empty() && !access.allows_webview_with(url, origin.as_ref());
5866        let mut messages = Vec::new();
5867        // `src`, also while `html` shows instead: clearing `html` loads it.
5868        let src = p.src.take_if(|url| refuses(url));
5869        if let Some(url) = &src {
5870            messages.push(not_granted("the web page", url, "webview.hosts"));
5871        }
5872        // What loads: `src`, or a URL Rust set as the source.
5873        if let crate::WebSource::Uri(url) = &p.source
5874            && refuses(url)
5875        {
5876            if src.as_ref() != Some(url) {
5877                messages.push(not_granted("the web page", url, "webview.hosts"));
5878            }
5879            p.source = crate::WebSource::None;
5880        }
5881        let base = p.base_url.take_if(|url| refuses(url));
5882        if let Some(url) = &base {
5883            messages.push(not_granted("the base URL", url, "webview.hosts"));
5884        }
5885        if let crate::WebSource::Html { base_url, .. } = &mut p.source
5886            && let Some(url) = base_url.take_if(|url| refuses(url))
5887            && base.as_ref() != Some(&url)
5888        {
5889            messages.push(not_granted("the base URL", &url, "webview.hosts"));
5890        }
5891        for message in messages {
5892            self.report_access_denied(id, message);
5893        }
5894    }
5895
5896    /// A refused source of node `id`: its `onError` (`ERR_ACCESS_DENIED`)
5897    /// and the app's console.
5898    fn report_access_denied(&mut self, id: NodeId, message: String) {
5899        self.events.push(crate::element::JsEvent::Event(
5900            id,
5901            EventKind::Error,
5902            EventPayload::Map(vec![
5903                ("message", PayloadValue::Str(message.clone())),
5904                (
5905                    "code",
5906                    PayloadValue::Str(crate::element::codes::ACCESS_DENIED.into()),
5907                ),
5908            ]),
5909        ));
5910        self.deny(message);
5911    }
5912
5913    /// `source` compiled, once per source while the cache keeps it (its
5914    /// error too): views that share a source, a source set again and the
5915    /// pages and dialogs that come through it use the compiled shader.
5916    fn compile(
5917        &mut self,
5918        source: &str,
5919    ) -> Result<crate::shader::Shader, crate::shader::ShaderError> {
5920        let hash = crate::shader::source_hash(source);
5921        let cached = self.shaders.get(&hash).filter(|c| match c {
5922            Ok(shader) => shader.source() == source,
5923            Err(_) => true,
5924        });
5925        if let Some(compiled) = cached {
5926            return compiled.clone();
5927        }
5928        let compiled = crate::shader::compile_source(source);
5929        // Bounded: an app making sources on the fly does not keep them all.
5930        if self.shaders.len() >= 64 {
5931            self.shaders.clear();
5932        }
5933        self.shaders.insert(hash, compiled.clone());
5934        compiled
5935    }
5936
5937    /// A page's or a dialog's `transitionShader`: compiled (once per source)
5938    /// into the layer the platform draws its coming and going through.
5939    fn set_nav_shader(&mut self, key: Key, spec: Option<crate::shader::NavShaderSpec>) {
5940        let id = self.nodes[key as usize].id;
5941        if self.nodes[key as usize].root.is_none() {
5942            log::warn!(target: "js", "`transitionShader` is a page's or a dialog's; node {id} is neither");
5943            return;
5944        }
5945        let shader = spec.and_then(|spec| {
5946            let shader = self
5947                .compile(&spec.source)
5948                .map_err(|e| log::warn!(target: "js", "the transitionShader of node {id}: {e}"))
5949                .ok()?;
5950            let mut warnings = Vec::new();
5951            let layer = crate::shader::ShaderLayer::new(shader, &spec.uniforms.0, &mut warnings)
5952                .with_role(crate::shader::ShaderRole::Transition);
5953            for warning in warnings {
5954                log::warn!(target: "js", "the transitionShader of node {id}: {warning}");
5955            }
5956            let ms = spec.duration.unwrap_or(DEFAULT_NAV_SHADER_MS).max(0.0);
5957            Some(crate::NavShader {
5958                layer: Arc::new(layer),
5959                duration: std::time::Duration::from_micros((f64::from(ms) * 1000.0).round() as u64),
5960            })
5961        });
5962        let root = self.nodes[key as usize]
5963            .root
5964            .as_mut()
5965            .expect("checked above");
5966        if root.nav_shader != shader {
5967            root.nav_shader = shader;
5968            self.mark(key, dirty::NAV_SHADER);
5969        }
5970    }
5971
5972    /// Tells the platform which shaders' pictures this commit changed
5973    /// ([`MountItem::ShaderInput`]): the effects and transitions with a
5974    /// changed view in their subtree (themselves included) or one that left
5975    /// it; every shader that reads what is behind it once a view drawn
5976    /// before it changed ([`Core::draws_before`]: not the view, what it holds
5977    /// or what draws over it), or anything that shows everywhere (the
5978    /// appearance, the tree's order); and every screen effect or
5979    /// transition, once anything changed.
5980    fn mark_shader_inputs(&mut self) {
5981        let unlinked_from = std::mem::take(&mut self.unlinked_from);
5982        // A batch that is only a layout animation is dropped (`commit`):
5983        // nothing in it changed what the pictures show.
5984        if self.pictured.is_empty()
5985            || self
5986                .mount
5987                .iter()
5988                .all(|item| matches!(item, MountItem::LayoutAnimation(_)))
5989        {
5990            return;
5991        }
5992        use crate::shader::{ShaderInput as I, ShaderRole as R};
5993        let ids: Vec<NodeId> = self.pictured.iter().copied().collect();
5994        let mut marked: Vec<NodeId> = Vec::new();
5995        let mut subtrees: Vec<(NodeId, Key)> = Vec::new();
5996        let mut backdrops: Vec<(NodeId, Key)> = Vec::new();
5997        for id in ids {
5998            let Ok(key) = self.key(id) else {
5999                self.pictured.remove(&id);
6000                continue;
6001            };
6002            let Some(layer) = self.nodes[key as usize]
6003                .shader
6004                .as_ref()
6005                .and_then(|s| s.layer.as_ref())
6006            else {
6007                continue;
6008            };
6009            let inputs = layer.shader.inputs();
6010            if matches!(layer.role, R::Screen | R::ScreenTransition) {
6011                marked.push(id);
6012                continue;
6013            }
6014            if inputs.contains(I::Backdrop) {
6015                backdrops.push((id, key));
6016            }
6017            if matches!(layer.role, R::Effect | R::Transition) {
6018                subtrees.push((id, key));
6019            }
6020        }
6021        if !backdrops.is_empty() {
6022            // What changed: the views of the items, and the parents of the
6023            // views that left (`Remove`, `Delete`), which stand in for them.
6024            let mut everywhere = false;
6025            let mut changed: Vec<Key> = Vec::new();
6026            let mut seen = rustc_hash::FxHashSet::default();
6027            for item in &self.mount {
6028                match shown_by(item) {
6029                    Shown::Nothing => {}
6030                    Shown::Everywhere => {
6031                        everywhere = true;
6032                        break;
6033                    }
6034                    Shown::View(id) => {
6035                        if seen.insert(id)
6036                            && let Ok(key) = self.key(id)
6037                        {
6038                            changed.push(key);
6039                        }
6040                    }
6041                }
6042            }
6043            for &id in &unlinked_from {
6044                if seen.insert(id)
6045                    && let Ok(key) = self.key(id)
6046                {
6047                    changed.push(key);
6048                }
6049            }
6050            for &(id, key) in &backdrops {
6051                if everywhere || self.draws_before(&changed, key) {
6052                    marked.push(id);
6053                }
6054            }
6055        }
6056        if !subtrees.is_empty() {
6057            let mut seen = rustc_hash::FxHashSet::default();
6058            // A view that left (`Remove`, `Delete`) has no parent to walk
6059            // up from any more: its old parent stands in for it.
6060            let views = self.mount.iter().filter_map(MountItem::view);
6061            for view in views.chain(unlinked_from) {
6062                if !seen.insert(view) {
6063                    continue;
6064                }
6065                let Ok(mut key) = self.key(view) else {
6066                    continue;
6067                };
6068                loop {
6069                    if let Some(&(id, _)) = subtrees.iter().find(|(_, k)| *k == key)
6070                        && !marked.contains(&id)
6071                    {
6072                        marked.push(id);
6073                    }
6074                    let parent = self.nodes[key as usize].parent;
6075                    if parent == NO_KEY {
6076                        break;
6077                    }
6078                    key = parent;
6079                }
6080            }
6081        }
6082        for id in marked {
6083            self.mount.push(MountItem::ShaderInput { id });
6084        }
6085    }
6086
6087    /// Whether one of `views` draws before `reader` (under it): an ancestor
6088    /// of it (its own box is behind it), or a view that comes before it in
6089    /// the order the views draw in, siblings by [`Node::stack_rank`] then in
6090    /// order. The reader, what it holds and what draws over it do not: they
6091    /// are not in its backdrop. A view whose way up does not meet the
6092    /// reader's (another root, an overlay's) is taken to draw before it.
6093    fn draws_before(&self, views: &[Key], reader: Key) -> bool {
6094        if views.is_empty() {
6095            return false;
6096        }
6097        // The reader's way up, the reader first: where each ancestor is on it.
6098        let mut up: Vec<Key> = Vec::new();
6099        let mut key = reader;
6100        while key != NO_KEY {
6101            up.push(key);
6102            key = self.nodes[key as usize].parent;
6103        }
6104        let at: rustc_hash::FxHashMap<Key, usize> =
6105            up.iter().enumerate().map(|(i, &k)| (k, i)).collect();
6106        views.iter().any(|&view| {
6107            let mut below = NO_KEY;
6108            let mut key = view;
6109            while key != NO_KEY {
6110                if let Some(&i) = at.get(&key) {
6111                    if i == 0 {
6112                        // The reader, or a view in it.
6113                        return false;
6114                    }
6115                    if below == NO_KEY {
6116                        // An ancestor of the reader.
6117                        return true;
6118                    }
6119                    // `key` holds both: the side of the view and the
6120                    // reader's.
6121                    return self.stacks_before(key, below, up[i - 1]);
6122                }
6123                below = key;
6124                key = self.nodes[key as usize].parent;
6125            }
6126            true
6127        })
6128    }
6129
6130    /// Whether `parent`'s child `a` draws before (under) its child `b`.
6131    fn stacks_before(&self, parent: Key, a: Key, b: Key) -> bool {
6132        let children = &self.nodes[parent as usize].children;
6133        let rank = |k: Key| {
6134            let index = children.iter().position(|&c| c == k).unwrap_or(usize::MAX);
6135            (self.nodes[k as usize].stack_rank(), index)
6136        };
6137        rank(a) < rank(b)
6138    }
6139
6140    /// A shader's `source`, program, `uniforms` or `paused`, or an effect's
6141    /// or transition's props: the layer is made again, and sent when it
6142    /// changed; a transition whose `value` changed starts.
6143    fn set_shader_prop(&mut self, key: Key, prop: Prop) {
6144        let id = self.nodes[key as usize].id;
6145        let Some(state) = self.nodes[key as usize].shader.as_mut() else {
6146            log::warn!(target: "js", "shader props are a `<Shader>`'s; node {id} is not one");
6147            return;
6148        };
6149        match prop {
6150            Prop::ShaderSource(source) => {
6151                if state.source == source {
6152                    return;
6153                }
6154                state.source = source.clone();
6155                state.shader = None;
6156                if let Some(source) = source {
6157                    let compiled = self.compile(&source);
6158                    let state = self.nodes[key as usize]
6159                        .shader
6160                        .as_mut()
6161                        .expect("shader node");
6162                    match compiled {
6163                        Ok(shader) => state.shader = Some(shader),
6164                        Err(error) => log::warn!(target: "js", "the shader of node {id}: {error}"),
6165                    }
6166                }
6167            }
6168            Prop::Shader(shader) => {
6169                state.source = None;
6170                state.shader = shader;
6171            }
6172            Prop::Uniforms(uniforms) => state.uniforms = uniforms,
6173            Prop::ShaderPaused(paused) => state.paused = paused,
6174            Prop::ShaderProgress(progress) => state.progress = progress,
6175            Prop::MaxSampleOffset(overflow) => state.overflow = overflow.max(Points::ZERO),
6176            Prop::TransitionValue(value) => state.value = value,
6177            Prop::TransitionDuration(duration) => state.duration = duration,
6178            Prop::TransitionFallback(fallback) => state.fallback = fallback,
6179            _ => return,
6180        }
6181        let state = self.nodes[key as usize]
6182            .shader
6183            .as_mut()
6184            .expect("shader node");
6185        use crate::shader::ShaderRole as R;
6186        let transition = matches!(state.role, R::Transition | R::ScreenTransition);
6187        // A transition without a shader of its own runs its fallback.
6188        let program = state.shader.clone().or_else(|| {
6189            (transition && state.fallback == crate::TransitionFallback::Fade)
6190                .then(crate::shader::crossfade)
6191                .flatten()
6192        });
6193        let layer = program.map(|shader| {
6194            let mut warnings = Vec::new();
6195            let (progress, animated) = match state.progress {
6196                crate::shader::ShaderProgress::Number(n) => (n, None),
6197                crate::shader::ShaderProgress::Animated(node) => (Percentage(0.0), Some(node)),
6198            };
6199            let layer = crate::shader::ShaderLayer::new(shader, &state.uniforms.0, &mut warnings)
6200                .with_paused(state.paused)
6201                .with_role(state.role)
6202                .with_overflow(state.overflow)
6203                .with_progress(progress, animated);
6204            for warning in warnings {
6205                log::warn!(target: "js", "the shader of node {id}: {warning}");
6206            }
6207            Arc::new(layer)
6208        });
6209        if transition && state.value != state.shown {
6210            let before = std::mem::replace(&mut state.shown, state.value.clone());
6211            let ms = state.duration.unwrap_or(DEFAULT_TRANSITION_MS).max(0.0);
6212            if before.is_some() && layer.is_some() && ms > 0.0 {
6213                self.transition_starts.push(MountItem::ShaderTransition {
6214                    id,
6215                    duration: std::time::Duration::from_micros(
6216                        (f64::from(ms) * 1000.0).round() as u64
6217                    ),
6218                });
6219            }
6220        }
6221        let state = self.nodes[key as usize]
6222            .shader
6223            .as_mut()
6224            .expect("shader node");
6225        if layer.as_ref().is_some_and(|l| {
6226            !l.shader.inputs().is_empty() || matches!(l.role, R::Screen | R::ScreenTransition)
6227        }) {
6228            self.pictured.insert(id);
6229        } else {
6230            self.pictured.remove(&id);
6231        }
6232        if layer == state.layer {
6233            return;
6234        }
6235        let nodes_of = |l: &Option<Arc<crate::shader::ShaderLayer>>| {
6236            l.as_ref().map_or(&[][..], |l| &l.nodes[..]).to_vec()
6237        };
6238        let slots_changed = nodes_of(&layer) != nodes_of(&state.layer);
6239        state.layer = layer;
6240        self.mark(
6241            key,
6242            dirty::SHADER | if slots_changed { dirty::ANIMATION } else { 0 },
6243        );
6244    }
6245
6246    fn set_prop(&mut self, id: NodeId, prop: Prop) -> Result<(), ApplyError> {
6247        let key = self.key(id)?;
6248        // Rust components: `component` makes a view a host, its props
6249        // arrive decoded (`RustProp`; platform components keep JSON).
6250        let prop = match prop {
6251            Prop::Component(name) if self.nodes[key as usize].kind == Kind::View => {
6252                self.create_instance(id, name);
6253                return Ok(());
6254            }
6255            // A GPU view names a renderer a UI set registered.
6256            Prop::Component(name) if self.nodes[key as usize].kind == Kind::GpuView => {
6257                let source = self.components.gpu_renderer(&name);
6258                if source.is_none() {
6259                    log::warn!(target: "js", "no GPU renderer is registered as `{name}`; the view draws nothing");
6260                }
6261                self.set_gpu_source(key, id, source);
6262                return Ok(());
6263            }
6264            Prop::GpuRenderer(source) => {
6265                if self.nodes[key as usize].kind == Kind::GpuView {
6266                    self.set_gpu_source(key, id, source);
6267                } else {
6268                    log::warn!("a GPU renderer on node {id}, which is no GPU view");
6269                }
6270                return Ok(());
6271            }
6272            Prop::ComponentSlot(name) => {
6273                self.set_slot_name(id, name);
6274                self.lay_out_through(key);
6275                return Ok(());
6276            }
6277            Prop::ComponentRender(slot) => {
6278                self.set_render_holder(id, slot);
6279                self.lay_out_through(key);
6280                return Ok(());
6281            }
6282            Prop::RustProp(name, value) => {
6283                if !self.set_component_prop(id, name, value) {
6284                    log::warn!(target: "js", "a Rust component's prop on node {id}, which hosts none");
6285                }
6286                return Ok(());
6287            }
6288            Prop::Follow(target) => {
6289                self.set_follow_target(key, target);
6290                return Ok(());
6291            }
6292            Prop::PassPosition(pass) => {
6293                self.set_pass_position(key, pass);
6294                return Ok(());
6295            }
6296            Prop::FollowTransition(transition) => {
6297                self.set_follow_transition(key, transition);
6298                return Ok(());
6299            }
6300            Prop::Accessibility(AccessibilityProp::ActiveDescendant(target)) => {
6301                self.set_relation(key, relations::Relation::ActiveDescendant, target);
6302                return Ok(());
6303            }
6304            Prop::Accessibility(AccessibilityProp::Controls(target)) => {
6305                self.set_relation(key, relations::Relation::Controls, target);
6306                return Ok(());
6307            }
6308            Prop::Accessibility(AccessibilityProp::DescribedBy(target)) => {
6309                self.set_relation(key, relations::Relation::DescribedBy, target);
6310                return Ok(());
6311            }
6312            Prop::ScrollEdgeElement(target) => {
6313                self.set_scroll_edge(key, target);
6314                return Ok(());
6315            }
6316            // A described view's own description waits for the element
6317            // describing it to go.
6318            Prop::Accessibility(AccessibilityProp::Description(description))
6319                if !self.relators.is_empty() && self.set_own_description(key, &description) =>
6320            {
6321                return Ok(());
6322            }
6323            prop => prop,
6324        };
6325        let prop = self.check_prop(key, prop);
6326        if let Prop::ShaderSource(_)
6327        | Prop::Shader(_)
6328        | Prop::Uniforms(_)
6329        | Prop::ShaderPaused(_)
6330        | Prop::ShaderProgress(_)
6331        | Prop::MaxSampleOffset(_)
6332        | Prop::TransitionValue(_)
6333        | Prop::TransitionDuration(_)
6334        | Prop::TransitionFallback(_) = prop
6335        {
6336            self.set_shader_prop(key, prop);
6337            return Ok(());
6338        }
6339        if let Prop::TransitionShader(spec) = prop {
6340            self.set_nav_shader(key, spec);
6341            return Ok(());
6342        }
6343        if let Prop::Screen(ScreenProp::StatusBar(setting)) = prop {
6344            self.set_status_bar(key, setting);
6345            return Ok(());
6346        }
6347        if let Prop::Screen(ScreenProp::Orientations(bits)) = prop {
6348            self.set_page_orientations(key, bits);
6349            return Ok(());
6350        }
6351        if let Prop::ListViewport(mode) = prop {
6352            self.set_list_viewport(key, mode);
6353            return Ok(());
6354        }
6355        // How a list in its parent's viewport scrolls is the scroll view's
6356        // around it.
6357        if matches!(
6358            prop,
6359            Prop::Scroll(_)
6360                | Prop::KeyboardDismissMode(_)
6361                | Prop::Scrollbar(_)
6362                | Prop::Refreshing(_)
6363                | Prop::ScrollValue(_)
6364                | Prop::PullValue(_)
6365                | Prop::Native(NativeProp::Scrollable(_))
6366        ) && let Some(list) = self.nodes[key as usize].list.as_mut().filter(|l| l.parent)
6367        {
6368            list.ignored |= match prop {
6369                Prop::Scroll(ScrollProp::RefreshIndicator(None)) => 0,
6370                Prop::Scroll(ScrollProp::RefreshIndicator(Some(_))) | Prop::PullValue(Some(_)) => {
6371                    list::ignored::REFRESH
6372                }
6373                Prop::Scroll(_)
6374                | Prop::KeyboardDismissMode(
6375                    KeyboardDismissMode::OnDrag | KeyboardDismissMode::Interactive,
6376                )
6377                | Prop::Native(NativeProp::Scrollable(false)) => list::ignored::BEHAVIOR,
6378                Prop::Scrollbar(
6379                    crate::ScrollbarSetting::Hidden
6380                    | crate::ScrollbarSetting::Themed(_)
6381                    | crate::ScrollbarSetting::ThemeValue(_),
6382                ) => list::ignored::SCROLLBAR,
6383                Prop::Refreshing(true) => list::ignored::REFRESH,
6384                Prop::ScrollValue(Some(_)) => list::ignored::SCROLL_VALUE,
6385                _ => 0,
6386            };
6387            self.warn_ignored(key);
6388            return Ok(());
6389        }
6390        let node = &mut self.nodes[key as usize];
6391        let mut flags = 0;
6392        let mut key_ancestry = false;
6393        let mut rebuild_span = false;
6394        let mut copy_text_changed = false;
6395        let mut slop_moved = false;
6396        match prop {
6397            Prop::Source(source) => {
6398                if let Some(image) = node.image.as_mut() {
6399                    // A `data:` URI is decoded here, once, not by every
6400                    // platform at every load.
6401                    let source = source.map(ImageSource::inline);
6402                    let size = source.as_ref().and_then(ImageSource::natural_size);
6403                    image.source = source;
6404                    flags |= dirty::IMAGE;
6405                    let layout = node.layout.expect("image layout");
6406                    if let Some(LeafContext::Image(natural)) =
6407                        self.layout.get_node_context_mut(layout)
6408                        && *natural != size
6409                    {
6410                        *natural = size;
6411                        self.layout.mark_dirty(layout);
6412                        self.needs_layout = true;
6413                    }
6414                }
6415            }
6416            Prop::Image(option) => {
6417                if let Some(image) = node.image.as_mut() {
6418                    match option {
6419                        ImageProp::Placeholder(source) => {
6420                            image.options.placeholder = source.map(ImageSource::inline)
6421                        }
6422                        ImageProp::BlurRadius(r) => image.options.blur_radius = r.max(Points::ZERO),
6423                        ImageProp::FadeDuration(ms) => image.options.fade_ms = ms,
6424                        ImageProp::SvgCurrentColor(on) => image.svg_current_color = on,
6425                    }
6426                    flags |= dirty::IMAGE;
6427                }
6428            }
6429            Prop::Horizontal(horizontal) => {
6430                if let Some(scroll) = node.scroll.as_mut()
6431                    && scroll.horizontal != horizontal
6432                {
6433                    scroll.horizontal = horizontal;
6434                    flags |= dirty::SCROLL;
6435                    let rtl = node.rtl;
6436                    if let Some(list) = node.list.as_mut() {
6437                        list.set_mirrored(horizontal && rtl);
6438                        list.set_horizontal(horizontal);
6439                    }
6440                    let children = node.children.clone();
6441                    self.sync_layout_style(key);
6442                    for child in children {
6443                        self.sync_layout_style(child);
6444                    }
6445                    if self.nodes[key as usize]
6446                        .list
6447                        .as_ref()
6448                        .is_some_and(|l| l.parent)
6449                    {
6450                        self.sync_spacer(key, true);
6451                        self.outer_moved = true;
6452                        // Its children are read along the new axis.
6453                        flags |= dirty::VIEW_PROPS;
6454                    }
6455                }
6456            }
6457            Prop::Scrollbar(setting) => {
6458                if let Some(scroll) = node.scroll.as_mut() {
6459                    scroll.scrollbar = setting;
6460                    flags |= dirty::SCROLL;
6461                    self.scrollbars_pending.push(key);
6462                } else if let Some(input) = node.input.as_mut() {
6463                    input.scrollbar = setting;
6464                    flags |= dirty::INPUT;
6465                    self.scrollbars_pending.push(key);
6466                }
6467            }
6468            Prop::Scroll(prop) => {
6469                if let Some(scroll) = node.scroll.as_mut() {
6470                    let b = &mut scroll.behavior;
6471                    match prop {
6472                        ScrollProp::Paging(on) => b.paging = on,
6473                        ScrollProp::SnapInterval(v) => b.snap_interval = v.max(Points::ZERO),
6474                        ScrollProp::SnapOffsets(v) => b.snap_offsets = v,
6475                        ScrollProp::SnapAlignment(a) => b.snap_alignment = a,
6476                        ScrollProp::Deceleration(r) => b.deceleration = r,
6477                        ScrollProp::Bounces(on) => b.bounces = on,
6478                        ScrollProp::ScrollsToTop(on) => b.scrolls_to_top = on,
6479                        ScrollProp::SmoothWheel(on) => b.smooth_wheel = on,
6480                        ScrollProp::WheelLineHeight(h) => b.wheel_line_height = h.max(Points::ZERO),
6481                        ScrollProp::ContentInset(i) => b.content_inset = i,
6482                        ScrollProp::ScrollbarInset(i) => {
6483                            // Negative insets count as none.
6484                            b.scrollbar_inset = i.map(|v| Points(v.0.max(0.0)));
6485                            // A built-in bar is laid out within the insets.
6486                            if scroll.bar.is_some() {
6487                                self.needs_layout = true;
6488                            }
6489                        }
6490                        ScrollProp::KeyboardTaps(t) => b.keyboard_taps = t,
6491                        ScrollProp::DisableIntervalMomentum(on) => b.one_step = on,
6492                        ScrollProp::MinZoom(v) => b.min_zoom = v.max(0.01),
6493                        ScrollProp::MaxZoom(v) => b.max_zoom = v.max(0.01),
6494                        ScrollProp::BouncesZoom(on) => b.bounces_zoom = on,
6495                        ScrollProp::Pinch(on) => b.pinch = on,
6496                        ScrollProp::CenterContent(on) => b.center_content = on,
6497                        ScrollProp::RefreshIndicator(h) => {
6498                            // No height, no indicator: every release would refresh.
6499                            b.refresh_indicator = h.filter(|h| h.0 > 0.0);
6500                        }
6501                        ScrollProp::Zoom(scale) => {
6502                            // After the limits (sent with this commit's
6503                            // behavior) are applied.
6504                            let id = node.id;
6505                            self.commands.push((
6506                                id,
6507                                Command::ZoomTo {
6508                                    scale,
6509                                    center: None,
6510                                    animated: false,
6511                                },
6512                            ));
6513                        }
6514                        ScrollProp::EventThrottle(ms) => scroll.event_throttle_ms = ms.max(0.0),
6515                        ScrollProp::ContentOffset(offset) => {
6516                            // Where it starts: scrolled there after layout.
6517                            let id = node.id;
6518                            self.commands.push((
6519                                id,
6520                                Command::ScrollTo {
6521                                    x: offset.x,
6522                                    y: offset.y,
6523                                    animated: false,
6524                                },
6525                            ));
6526                        }
6527                    }
6528                    flags |= dirty::SCROLL_BEHAVIOR;
6529                }
6530            }
6531            Prop::Refreshing(refreshing) => {
6532                if let Some(scroll) = node.scroll.as_mut() {
6533                    scroll.refreshing = refreshing;
6534                    flags |= dirty::REFRESHING;
6535                }
6536            }
6537            Prop::ScrollValue(value) => {
6538                if let Some(value) = value {
6539                    self.reach.drive(value);
6540                }
6541                if let Some(scroll) = node.scroll.as_mut() {
6542                    scroll.scroll_value = value;
6543                    flags |= dirty::SCROLL;
6544                }
6545            }
6546            Prop::PullValue(value) => {
6547                if let Some(value) = value {
6548                    self.reach.drive(value);
6549                }
6550                if let Some(scroll) = node.scroll.as_mut() {
6551                    scroll.pull_value = value;
6552                    flags |= dirty::SCROLL;
6553                }
6554            }
6555            Prop::Count(count) => {
6556                if let Some(list) = node.list.as_mut()
6557                    && list.count != count
6558                {
6559                    list.unrequest(&take_queued_binds(&mut self.list_binds, node.id));
6560                    list.set_count(count);
6561                }
6562            }
6563            Prop::EstimatedItemSize(size) => {
6564                if let Some(list) = node.list.as_mut() {
6565                    list.set_estimated(size.0);
6566                }
6567            }
6568            Prop::Slot(slot) => {
6569                node.slot = Some(slot);
6570                let parent = node.parent;
6571                if let Some(list) = self
6572                    .nodes
6573                    .get_mut(parent as usize)
6574                    .and_then(|p| p.list.as_mut())
6575                {
6576                    list.add_slot_cell(slot, key);
6577                }
6578            }
6579            Prop::Splice(at, removed, inserted) => {
6580                let loads_at_start = node.events.contains(EventKind::LoadMoreAtStart);
6581                if let Some(list) = node.list.as_mut() {
6582                    list.loads_at_start = loads_at_start;
6583                    list.unrequest(&take_queued_binds(&mut self.list_binds, node.id));
6584                    list.splice(at, removed, inserted);
6585                }
6586            }
6587            Prop::ListDiff(diff) => {
6588                let loads_at_start = node.events.contains(EventKind::LoadMoreAtStart);
6589                if let Some(list) = node.list.as_mut() {
6590                    list.loads_at_start = loads_at_start;
6591                    list.unrequest(&take_queued_binds(&mut self.list_binds, node.id));
6592                    list.reorder(&diff);
6593                }
6594            }
6595            Prop::Columns(columns) => {
6596                if let Some(list) = node.list.as_mut()
6597                    && list.set_columns(columns)
6598                {
6599                    // Its cells are laid out again at the new width, even
6600                    // when nothing else in the turn lays anything out.
6601                    self.needs_layout = true;
6602                }
6603            }
6604            Prop::Inverted(inverted) => {
6605                if let Some(list) = node.list.as_mut() {
6606                    list.set_inverted(inverted);
6607                    if list.parent {
6608                        self.warn_ignored(key);
6609                    }
6610                }
6611            }
6612            Prop::FollowEnd(threshold, animated) => {
6613                if let Some(list) = node.list.as_mut() {
6614                    list.set_follow_end(threshold.map(|t| t.0), animated);
6615                    if list.parent {
6616                        self.warn_ignored(key);
6617                    }
6618                }
6619            }
6620            Prop::ListAlignment(alignment) => {
6621                if let Some(list) = node.list.as_mut() {
6622                    list.set_alignment(alignment);
6623                    if list.parent {
6624                        self.warn_ignored(key);
6625                    }
6626                }
6627            }
6628            Prop::StickyIndices(indices) => {
6629                if let Some(list) = node.list.as_mut() {
6630                    list.set_sticky(indices);
6631                    if list.parent {
6632                        self.warn_ignored(key);
6633                    }
6634                }
6635            }
6636            Prop::StickyOffset(offset) => {
6637                if let Some(list) = node.list.as_mut() {
6638                    list.set_sticky_node(None);
6639                    list.set_sticky_offset(offset.0);
6640                    if list.parent {
6641                        self.warn_ignored(key);
6642                    }
6643                }
6644            }
6645            Prop::StickyOffsetNode(node_id) => {
6646                if let Some(list) = node.list.as_mut() {
6647                    list.set_sticky_offset(0.0);
6648                    list.set_sticky_node(node_id);
6649                }
6650            }
6651            Prop::ListContent(content) => {
6652                if let Some(list) = node.list.as_mut()
6653                    && list.set_content(content)
6654                {
6655                    self.needs_layout = true;
6656                }
6657            }
6658            Prop::Viewability(config) => {
6659                if let Some(list) = node.list.as_mut()
6660                    && list.viewability != config
6661                {
6662                    list.viewability = config;
6663                    list.dirty = true;
6664                }
6665            }
6666            Prop::LoadMoreThreshold(threshold) => {
6667                if let Some(list) = node.list.as_mut() {
6668                    list.end_threshold = threshold.max(0.0);
6669                }
6670            }
6671            Prop::LoadMoreAtStartThreshold(threshold) => {
6672                if let Some(list) = node.list.as_mut() {
6673                    list.start_threshold = threshold.max(0.0);
6674                }
6675            }
6676            Prop::CellIndex(index) => {
6677                let parent = node.parent;
6678                if let Some(list) = self
6679                    .nodes
6680                    .get_mut(parent as usize)
6681                    .and_then(|p| p.list.as_mut())
6682                {
6683                    list.rendered(key, index);
6684                }
6685            }
6686            Prop::PanValues(x, y) => {
6687                // A gesture drives them: no bound on where they take a view.
6688                for value in [x, y].into_iter().flatten() {
6689                    self.reach.drive(value);
6690                }
6691                (node.gestures.pan_x, node.gestures.pan_y) = (x, y);
6692                flags |= dirty::PAN;
6693            }
6694            Prop::PanEnabled(enabled) => {
6695                if node.pan_enabled != enabled {
6696                    node.pan_enabled = enabled;
6697                    flags |= dirty::PAN | dirty::EVENTS;
6698                }
6699            }
6700            Prop::PanScrollHandoff(value) => {
6701                let props = node.props.get_or_insert_default();
6702                if props.pan_scroll_handoff != value {
6703                    props.pan_scroll_handoff = value;
6704                    flags |= dirty::VIEW_PROPS;
6705                }
6706            }
6707            Prop::PinchValue(value) => {
6708                if let Some(value) = value {
6709                    self.reach.drive(value);
6710                }
6711                node.gestures.pinch = value;
6712                flags |= dirty::PAN;
6713            }
6714            Prop::RotationValue(value) => {
6715                if let Some(value) = value {
6716                    self.reach.drive(value);
6717                }
6718                node.gestures.rotation = value;
6719                flags |= dirty::PAN;
6720            }
6721            Prop::AllowFontScaling(allow) => {
6722                if node.paragraph.allow_font_scaling != allow {
6723                    node.paragraph.allow_font_scaling = allow;
6724                    self.font_settings_changed(key);
6725                }
6726            }
6727            Prop::SelectionColor(color) if node.input.is_none() => {
6728                if node.paragraph.selection_color != color {
6729                    node.paragraph.selection_color = color;
6730                    if node.kind == Kind::Text {
6731                        self.mark_text_block(key);
6732                    } else {
6733                        // A view's: the texts and inputs inside take it
6734                        // (`inherited_text_props`).
6735                        self.mark_inheriting_text(key);
6736                    }
6737                }
6738            }
6739            Prop::AdjustsFontSizeToFit(_) | Prop::MinimumFontScale(_) => {
6740                let before = (node.paragraph.fit, node.paragraph.min_font_scale);
6741                match prop {
6742                    Prop::AdjustsFontSizeToFit(on) => node.paragraph.fit = on,
6743                    Prop::MinimumFontScale(min) => node.paragraph.min_font_scale = min,
6744                    _ => {}
6745                }
6746                if (node.paragraph.fit, node.paragraph.min_font_scale) != before {
6747                    self.queue_text(key);
6748                    if let Some(layout) = self.nodes[key as usize].layout
6749                        && let Some(LeafContext::Text(cx)) =
6750                            self.layout.get_node_context_mut(layout)
6751                    {
6752                        cx.laid_out = None;
6753                    }
6754                }
6755            }
6756            Prop::MaxFontSizeMultiplier(max) => {
6757                if node.paragraph.max_font_multiplier != max {
6758                    node.paragraph.max_font_multiplier = max;
6759                    self.font_settings_changed(key);
6760                }
6761            }
6762            Prop::PointerEvents(value) => {
6763                let props = node.props.get_or_insert_default();
6764                if props.pointer_events != value {
6765                    props.pointer_events = value;
6766                    flags |= dirty::VIEW_PROPS;
6767                }
6768            }
6769            Prop::HitSlop(value) => {
6770                let props = node.props.get_or_insert_default();
6771                if props.hit_slop != value {
6772                    props.hit_slop = value;
6773                    flags |= dirty::VIEW_PROPS;
6774                    slop_moved = true;
6775                }
6776            }
6777            Prop::Href(value) => {
6778                let value = value.filter(|href| !href.is_empty());
6779                let props = node.props.get_or_insert_default();
6780                if props.href != value {
6781                    props.href = value;
6782                    flags |= dirty::VIEW_PROPS;
6783                    // A span's is recorded in its block's text (`link_hrefs`).
6784                    if node.kind == Kind::Text && node.inline {
6785                        rebuild_span = true;
6786                    }
6787                }
6788            }
6789            Prop::PanActivation(value) => {
6790                let props = node.props.get_or_insert_default();
6791                if props.pan_activation != value {
6792                    props.pan_activation = value;
6793                    flags |= dirty::VIEW_PROPS;
6794                }
6795            }
6796            Prop::InsetPadding(insets) | Prop::InsetMargin(insets) => {
6797                let slot = usize::from(matches!(prop, Prop::InsetMargin(_)));
6798                let mut all = node.insets.as_deref().copied().unwrap_or_default();
6799                if all[slot] != insets {
6800                    all[slot] = insets;
6801                    node.insets = (all != <[EdgeInsets; 2]>::default()).then(|| Box::new(all));
6802                    self.restyle(key);
6803                }
6804                return Ok(());
6805            }
6806            Prop::Class(names) => {
6807                self.set_classes(key, Some(names), None);
6808                return Ok(());
6809            }
6810            Prop::ClassList(list) => {
6811                self.set_classes(key, None, Some(list));
6812                return Ok(());
6813            }
6814            Prop::TailwindTheme(json) => {
6815                self.set_tailwind_theme(&json);
6816                return Ok(());
6817            }
6818            Prop::UiTheme(json) => {
6819                self.set_ui_theme(&json);
6820                return Ok(());
6821            }
6822            Prop::SnapToWindowMargin(margin) => {
6823                self.set_snap_to_window_margin(margin);
6824                return Ok(());
6825            }
6826            Prop::LayoutDirection(rtl) => {
6827                // The surface's direction (the root's): the user's language, as
6828                // JS or the policy sets it.
6829                if key == self.root && node.direction != Some(rtl) {
6830                    node.direction = Some(rtl);
6831                    self.mount.push(MountItem::LayoutDirection { rtl });
6832                    self.update_direction(key);
6833                    self.root_direction_changed(rtl);
6834                }
6835                return Ok(());
6836            }
6837            Prop::Appearance(appearance) => {
6838                // The app's appearance (the root's): `nsh.json`,
6839                // `setColorScheme`.
6840                if key == self.root {
6841                    self.set_appearance(appearance);
6842                }
6843                return Ok(());
6844            }
6845            Prop::Keymap(keymap) => {
6846                // The surface's shortcuts (the root's): `nsh/keymap`.
6847                if key == self.root {
6848                    let keymap = self.keymap_with_focus(keymap);
6849                    self.mount.push(MountItem::Keymap(keymap));
6850                }
6851                return Ok(());
6852            }
6853            Prop::LongPressDelay(value) => {
6854                let props = node.props.get_or_insert_default();
6855                if props.long_press_delay != value {
6856                    props.long_press_delay = value;
6857                    flags |= dirty::VIEW_PROPS;
6858                }
6859            }
6860            Prop::Ripple(value) => {
6861                let props = node.props.get_or_insert_default();
6862                if props.ripple != value {
6863                    props.ripple = value;
6864                    flags |= dirty::VIEW_PROPS;
6865                }
6866            }
6867            Prop::Elevation(value) => {
6868                let value = value.max(Points::ZERO);
6869                if node.elevation != value {
6870                    node.elevation = value;
6871                    flags |= dirty::VIEW;
6872                }
6873            }
6874            Prop::BackdropMaterial(value) => {
6875                if node.backdrop_material != value {
6876                    node.backdrop_material = value;
6877                    flags |= dirty::VIEW;
6878                }
6879            }
6880            Prop::MacOsBackdrop(value) => {
6881                if node.macos_backdrop != value {
6882                    node.macos_backdrop = value;
6883                    flags |= dirty::VIEW;
6884                }
6885            }
6886            Prop::WindowsBackdrop(value) => {
6887                if node.windows_backdrop != value {
6888                    node.windows_backdrop = value;
6889                    flags |= dirty::VIEW;
6890                }
6891            }
6892            Prop::ActiveStyle(patch) => {
6893                self.set_part_style(key, classes::Part::Active, patch);
6894                return Ok(());
6895            }
6896            Prop::HoverStyle(patch) => {
6897                self.set_part_style(key, classes::Part::Hover, patch);
6898                return Ok(());
6899            }
6900            Prop::FocusStyle(patch) => {
6901                self.set_part_style(key, classes::Part::Focus, patch);
6902                return Ok(());
6903            }
6904            Prop::DisabledStyle(patch) => {
6905                self.set_part_style(key, classes::Part::Disabled, patch);
6906                return Ok(());
6907            }
6908            Prop::SelectedStyle(patch) => {
6909                self.set_part_style(key, classes::Part::Selected, patch);
6910                return Ok(());
6911            }
6912            Prop::CheckedStyle(patch) => {
6913                self.set_part_style(key, classes::Part::Checked, patch);
6914                return Ok(());
6915            }
6916            Prop::IndeterminateStyle(patch) => {
6917                self.set_part_style(key, classes::Part::Indeterminate, patch);
6918                return Ok(());
6919            }
6920            Prop::PressedStyle(patch) => {
6921                self.set_part_style(key, classes::Part::Pressed, patch);
6922                return Ok(());
6923            }
6924            Prop::ExpandedStyle(patch) => {
6925                self.set_part_style(key, classes::Part::Expanded, patch);
6926                return Ok(());
6927            }
6928            Prop::FocusWithinStyle(patch) => {
6929                self.set_part_style(key, classes::Part::FocusWithin, patch);
6930                return Ok(());
6931            }
6932            Prop::FocusVisibleStyle(patch) => {
6933                self.set_part_style(key, classes::Part::FocusVisible, patch);
6934                return Ok(());
6935            }
6936            Prop::ProjectedStates(states) => {
6937                self.set_projected_states(key, states);
6938                return Ok(());
6939            }
6940            Prop::ProjectedData(data) => {
6941                self.set_projected_data(key, data);
6942                return Ok(());
6943            }
6944            Prop::ProjectedActive(group) => {
6945                self.set_projected_active(key, group);
6946                return Ok(());
6947            }
6948            Prop::HeaderStyle(patch) => {
6949                self.set_part_style(key, classes::Part::Header, patch);
6950                return Ok(());
6951            }
6952            Prop::HeaderClass(names) => {
6953                self.set_part_class(key, classes::Part::Header, &names);
6954                return Ok(());
6955            }
6956            Prop::HeaderClassList(list) => {
6957                self.set_part_class_list(key, classes::Part::Header, list);
6958                return Ok(());
6959            }
6960            Prop::ListContentClass(names) => {
6961                self.set_part_class(key, classes::Part::Content, &names);
6962                return Ok(());
6963            }
6964            Prop::TestId(value) => {
6965                let props = node.props.get_or_insert_default();
6966                if props.test_id != value {
6967                    props.test_id = value;
6968                    flags |= dirty::VIEW_PROPS;
6969                    // A span's id is recorded in its block's text.
6970                    if node.kind == Kind::Text && node.inline {
6971                        rebuild_span = true;
6972                    }
6973                }
6974            }
6975            Prop::ClearsKeyboard(value) => {
6976                if node.clears_keyboard != value {
6977                    // The `env()` terms in its subtree may come to
6978                    // something else: `sync_env` compares them all at the
6979                    // end of the commit and restyles the ones that did.
6980                    node.clears_keyboard = value;
6981                }
6982            }
6983            Prop::CopyText(value) => {
6984                if node.copy_text != value {
6985                    node.copy_text = value;
6986                    // Its block's text holds it; a render's content's is
6987                    // its placeholder's (`Core::attachment_copy_text`).
6988                    copy_text_changed = true;
6989                }
6990            }
6991            Prop::WebElement(value) => {
6992                let props = node.props.get_or_insert_default();
6993                if props.web_element != value {
6994                    props.web_element = value;
6995                    flags |= dirty::VIEW_PROPS;
6996                }
6997            }
6998            Prop::WindowDrag(value) => {
6999                let props = node.props.get_or_insert_default();
7000                if props.window_drag != value {
7001                    props.window_drag = value;
7002                    flags |= dirty::VIEW_PROPS;
7003                }
7004            }
7005            Prop::WindowControl(value) => {
7006                let props = node.props.get_or_insert_default();
7007                if props.window_control != value {
7008                    props.window_control = value;
7009                    flags |= dirty::VIEW_PROPS;
7010                }
7011            }
7012            Prop::WindowResize(value) => {
7013                let props = node.props.get_or_insert_default();
7014                if props.window_resize != value {
7015                    props.window_resize = value;
7016                    flags |= dirty::VIEW_PROPS;
7017                }
7018            }
7019            Prop::Focusable(value) => {
7020                let props = node.props.get_or_insert_default();
7021                if props.focusable != value {
7022                    props.focusable = value;
7023                    flags |= dirty::VIEW_PROPS;
7024                }
7025            }
7026            Prop::KeyCapture(value) => {
7027                let props = node.props.get_or_insert_default();
7028                if props.key_capture != value {
7029                    props.key_capture = value;
7030                    flags |= dirty::VIEW_PROPS;
7031                    key_ancestry = true;
7032                }
7033            }
7034            Prop::SelectableView(value) => {
7035                let props = node.props.get_or_insert_default();
7036                if props.selectable_view != value {
7037                    props.selectable_view = value;
7038                    flags |= dirty::VIEW_PROPS;
7039                }
7040            }
7041            Prop::SelectionMenu(items) => {
7042                let items: std::sync::Arc<[crate::desktop::MenuItem]> =
7043                    crate::desktop::MenuItem::selection_menu(&items).into();
7044                let props = node.props.get_or_insert_default();
7045                if props.selection_menu != items {
7046                    props.selection_menu = items;
7047                    flags |= dirty::VIEW_PROPS;
7048                }
7049            }
7050            Prop::ContinuesText(value) => {
7051                let props = node.props.get_or_insert_default();
7052                if props.continues_text != value {
7053                    props.continues_text = value;
7054                    flags |= dirty::VIEW_PROPS;
7055                }
7056            }
7057            Prop::Accessibility(prop) => {
7058                // A label changing on mounted props goes alone: it is
7059                // the one that follows app state (a count, a value).
7060                let label_only =
7061                    node.props.is_some() && matches!(prop, AccessibilityProp::Label(_));
7062                let props = node.props.get_or_insert_default();
7063                let a = &mut props.accessibility;
7064                let before = a.clone();
7065                match prop {
7066                    AccessibilityProp::Accessible(v) => a.accessible = v,
7067                    AccessibilityProp::Label(v) => a.label = v,
7068                    AccessibilityProp::Hint(v) => a.hint = v,
7069                    AccessibilityProp::Description(v) => a.description = v,
7070                    AccessibilityProp::Role(v) => a.role = v,
7071                    AccessibilityProp::State(v) => a.state = v,
7072                    AccessibilityProp::Value(v) => a.value = v,
7073                    AccessibilityProp::Hidden(v) => a.hidden = v,
7074                    AccessibilityProp::Important(accessible, hidden) => {
7075                        a.accessible = accessible;
7076                        a.hidden = hidden;
7077                    }
7078                    AccessibilityProp::LiveRegion(v) => a.live_region = v,
7079                    AccessibilityProp::Actions(v) => a.actions = v,
7080                    AccessibilityProp::Level(v) => a.level = v,
7081                    AccessibilityProp::Orientation(v) => a.orientation = v,
7082                    // Set as relations, above.
7083                    AccessibilityProp::ActiveDescendant(_)
7084                    | AccessibilityProp::Controls(_)
7085                    | AccessibilityProp::DescribedBy(_) => {}
7086                }
7087                let states = classes::accessibility_states(&a.state);
7088                let states_changed = states != classes::accessibility_states(&before.state);
7089                if *a != before {
7090                    flags |= if label_only {
7091                        dirty::LABEL
7092                    } else {
7093                        dirty::VIEW_PROPS
7094                    };
7095                }
7096                if states_changed {
7097                    if flags != 0 {
7098                        self.mark(key, flags);
7099                    }
7100                    self.set_accessibility_states(key, states);
7101                    return Ok(());
7102                }
7103            }
7104            Prop::KeyboardDismissMode(mode) => {
7105                if let Some(scroll) = node.scroll.as_mut() {
7106                    scroll.keyboard_dismiss = mode;
7107                    flags |= dirty::SCROLL;
7108                }
7109            }
7110            // `animation` on a dialog: the value pages and dialogs share.
7111            Prop::Screen(ScreenProp::Animation(a)) if node.kind == Kind::Modal => {
7112                if let Some(root) = node.root.as_mut() {
7113                    root.modal.animation = match a {
7114                        ScreenAnimation::Default => ModalAnimation::Slide,
7115                        ScreenAnimation::Fade => ModalAnimation::Fade,
7116                        ScreenAnimation::None => ModalAnimation::None,
7117                    };
7118                    flags |= dirty::MODAL;
7119                }
7120            }
7121            Prop::Screen(prop) => {
7122                if let Some(root) = node.root.as_mut() {
7123                    let c = &mut root.screen;
7124                    match prop {
7125                        ScreenProp::Title(v) => c.title = v,
7126                        ScreenProp::HeaderVisible(v) => c.header_visible = v,
7127                        ScreenProp::HeaderLargeTitle(v) => c.large_title = v,
7128                        ScreenProp::HeaderTransparent(v) => c.header_transparent = v,
7129                        ScreenProp::HeaderShadowVisible(v) => c.header_shadow_visible = v,
7130                        ScreenProp::HeaderTitleAlign(v) => c.title_align = v,
7131                        ScreenProp::HeaderBackgroundOnScroll(v) => {
7132                            c.header_background_on_scroll = v
7133                        }
7134                        ScreenProp::HidesBottomBarWhenPushed(v) => {
7135                            c.hides_bottom_bar_when_pushed = v
7136                        }
7137                        ScreenProp::HeaderBackTitle(v) => c.back_title = v,
7138                        ScreenProp::HeaderBackVisible(v) => c.back_visible = v,
7139                        ScreenProp::HeaderRightSystemItem(v) => c.right_system_item = v,
7140                        ScreenProp::HeaderRightSymbol(v) => c.right_symbol = v,
7141                        ScreenProp::HeaderLeftSystemItem(v) => c.left_system_item = v,
7142                        ScreenProp::HeaderLeftSymbol(v) => c.left_symbol = v,
7143                        ScreenProp::HeaderRightItems(v) => c.right_items = v,
7144                        ScreenProp::HeaderLeftItems(v) => c.left_items = v,
7145                        ScreenProp::PopOnSwipe(v) => c.gesture_enabled = v,
7146                        ScreenProp::PopOnBack(v) => c.prevent_back = !v,
7147                        ScreenProp::Animation(v) => c.animation = v,
7148                        // Taken by `set_prop`.
7149                        ScreenProp::StatusBar(_) | ScreenProp::Orientations(_) => {}
7150                    }
7151                    // Header changes move the content.
7152                    root.laid_out = None;
7153                    self.needs_layout = true;
7154                    flags |= dirty::SCREEN;
7155                }
7156            }
7157            Prop::NativeId(name) => {
7158                if node.kind == Kind::InputAccessory {
7159                    let attached = node.parent != NO_KEY;
7160                    if attached {
7161                        self.accessory_attached(key, false);
7162                    }
7163                    if let Some(root) = self.nodes[key as usize].root.as_mut() {
7164                        root.native_id = name;
7165                    }
7166                    if attached {
7167                        self.accessory_attached(key, true);
7168                    }
7169                    return Ok(());
7170                }
7171                // Other views: the embedding app finds them by it
7172                // (`watchScroll`).
7173                let value: Option<Arc<str>> = name.as_deref().map(Into::into);
7174                let props = node.props.get_or_insert_default();
7175                if props.native_id != value {
7176                    props.native_id = value;
7177                    flags |= dirty::VIEW_PROPS;
7178                }
7179            }
7180            Prop::Modal(prop) => {
7181                if let Some(root) = node.root.as_mut() {
7182                    let c = &mut root.modal;
7183                    match prop {
7184                        ModalProp::Animation(v) => c.animation = v,
7185                        ModalProp::Presentation(v) => c.presentation = v,
7186                        ModalProp::StatusBarTranslucent(v) => c.status_bar_translucent = v,
7187                        ModalProp::Orientations(v) => c.orientations = v,
7188                        ModalProp::CloseOnEscape(v) => c.close_on_escape = v,
7189                        ModalProp::CloseOnBackdropPress(v) => c.close_on_backdrop_press = v,
7190                        ModalProp::CloseOnSwipe(v) => c.close_on_swipe = v,
7191                        ModalProp::Detents(v) => c.detents = v,
7192                        ModalProp::Detent(v) => c.detent = v,
7193                        ModalProp::DefaultDetent(v) => c.default_detent = v,
7194                        ModalProp::Grabber(v) => c.grabber = v,
7195                        ModalProp::LargestUndimmedDetent(v) => c.largest_undimmed_detent = v,
7196                    }
7197                    flags |= dirty::MODAL;
7198                }
7199            }
7200            Prop::Overlay(prop) => {
7201                use crate::OverlayProp;
7202                // A hint makes an overlay a tooltip's, which counts among no
7203                // siblings (`is_element_child`): theirs move.
7204                let parent = node.parent;
7205                if matches!(prop, OverlayProp::Hint(_))
7206                    && parent != NO_KEY
7207                    && self.nodes[parent as usize]
7208                        .positional
7209                        .has(Positional::CHILDREN)
7210                {
7211                    self.queue_positions(parent);
7212                }
7213                self.set_overlay_config(key, |c| match prop {
7214                    OverlayProp::Anchor(v) => c.anchor = v,
7215                    OverlayProp::Placement(v) => c.placement = v,
7216                    OverlayProp::Align(v) => c.align = v,
7217                    OverlayProp::Offset(v) => c.offset = v,
7218                    OverlayProp::Margin(v) => c.margin = v,
7219                    OverlayProp::Hint(v) => c.hint = v,
7220                    OverlayProp::Open(v) => c.open = v,
7221                    OverlayProp::Cover(v) => c.cover = v,
7222                });
7223                if matches!(prop, OverlayProp::Margin(_))
7224                    && let Some(state) = self.overlay_mut(key)
7225                    && !state.margin_set
7226                {
7227                    state.margin_set = true;
7228                    state.placed = None;
7229                    self.needs_layout = true;
7230                }
7231                return Ok(());
7232            }
7233            Prop::Tooltip(content) => {
7234                self.set_tooltip(key, content);
7235                return Ok(());
7236            }
7237            Prop::HeaderSlot(slot) => {
7238                if let Some(root) = node.root.as_mut()
7239                    && root.slot != slot
7240                {
7241                    root.slot = slot;
7242                    let parent = node.parent;
7243                    if parent != NO_KEY {
7244                        self.mark(parent, dirty::SCREEN);
7245                    }
7246                }
7247            }
7248            // `scrollable` of scroll views and lists.
7249            Prop::Native(NativeProp::Scrollable(on)) if node.scroll.is_some() => {
7250                if let Some(scroll) = node.scroll.as_mut() {
7251                    scroll.behavior.enabled = on;
7252                    flags |= dirty::SCROLL_BEHAVIOR;
7253                }
7254            }
7255            Prop::Component(name) => {
7256                let created = node.created;
7257                if let Some(component) = node.component.as_mut() {
7258                    match &component.name {
7259                        // Named after its native view was made (a Rust
7260                        // component whose root is `native()` takes its
7261                        // host's place, which is made first): the platform
7262                        // is told now, and gets every prop again after it.
7263                        None if created => {
7264                            component.name = Some(name.clone());
7265                            component.changed =
7266                                component.props.iter().map(|(k, _)| k.clone()).collect();
7267                            self.mount.push(MountItem::Component { id, name });
7268                            flags |= dirty::COMPONENT;
7269                            if !component.slots.is_empty() {
7270                                component.slots_changed.set(true);
7271                                flags |= dirty::ANIMATION;
7272                            }
7273                        }
7274                        None => component.name = Some(name),
7275                        Some(old) if *old != name => log::warn!(
7276                            target: "js",
7277                            "a native component cannot change from `{old}` to `{name}`; render a new element"
7278                        ),
7279                        Some(_) => {}
7280                    }
7281                }
7282            }
7283            Prop::ComponentPropBinding(name, value) => {
7284                if let Some(component) = node.component.as_mut() {
7285                    let slot = match component.slots.iter().position(|k| *k == name) {
7286                        Some(s) => Some(s as u16),
7287                        None if value.is_none() => None,
7288                        None => {
7289                            component.slots.push(name.clone());
7290                            component.slots_changed.set(true);
7291                            Some((component.slots.len() - 1) as u16)
7292                        }
7293                    };
7294                    if let Some(slot) = slot {
7295                        let at = component.bound.iter().position(|(s, _)| *s == slot);
7296                        match (at, value) {
7297                            (Some(i), Some(n)) => component.bound[i].1 = n,
7298                            (None, Some(n)) => component.bound.push((slot, n)),
7299                            (Some(i), None) => {
7300                                component.bound.remove(i);
7301                                // Its static value (or its removal) is sent again.
7302                                if !component.changed.contains(&name) {
7303                                    component.changed.push(name);
7304                                }
7305                                flags |= dirty::COMPONENT;
7306                            }
7307                            (None, None) => {}
7308                        }
7309                        flags |= dirty::ANIMATION;
7310                    }
7311                }
7312            }
7313            Prop::ComponentProp(name, value) => {
7314                if let Some(component) = node.component.as_mut() {
7315                    let at = component.props.iter().position(|(k, _)| *k == name);
7316                    match (at, value) {
7317                        (Some(i), Some(v)) => component.props[i].1 = v,
7318                        (None, Some(v)) => component.props.push((name.clone(), v)),
7319                        (Some(i), None) => {
7320                            component.props.swap_remove(i);
7321                        }
7322                        (None, None) => {}
7323                    }
7324                    if !component.changed.contains(&name) {
7325                        component.changed.push(name);
7326                    }
7327                    flags |= dirty::COMPONENT;
7328                }
7329            }
7330            Prop::Native(prop) => {
7331                if let NativeProp::Disabled(d) = prop {
7332                    // `disabled:` classes, on any element.
7333                    self.set_disabled(key, d);
7334                }
7335                let node = &mut self.nodes[key as usize];
7336                // The platforms make a web view with its website data store
7337                // and the URL schemes it serves, from its first props.
7338                if node.created
7339                    && let Some(NativeProps::WebView(p)) = node.control.as_deref()
7340                {
7341                    let changed = match &prop {
7342                        NativeProp::Incognito(on) => Some(("`incognito` is", *on != p.incognito)),
7343                        NativeProp::Zoomable(on) => Some(("`zoomable` is", *on != p.zoomable)),
7344                        // A re-render builds new handlers: only a change
7345                        // of the schemes served is worth a warning.
7346                        NativeProp::UrlSchemes(schemes) => Some((
7347                            "URL schemes are",
7348                            !schemes
7349                                .iter()
7350                                .map(|s| s.scheme())
7351                                .eq(p.url_schemes.iter().map(|s| s.scheme())),
7352                        )),
7353                        _ => None,
7354                    };
7355                    if let Some((what, changed)) = changed {
7356                        if changed {
7357                            log::warn!(
7358                                target: "js",
7359                                "a web view's {what} read when it is made; render a new element to change it"
7360                            );
7361                        }
7362                        return Ok(());
7363                    }
7364                }
7365                if let Some(control) = node.control.as_mut() {
7366                    apply_native(control, prop);
7367                    flags |= dirty::NATIVE;
7368                }
7369            }
7370            Prop::Value(value) => {
7371                if let Some(input) = node.input.as_mut() {
7372                    input.value_set = true;
7373                    if input.value != value {
7374                        input.value = value;
7375                        flags |= dirty::INPUT_VALUE;
7376                        self.measure_input(key);
7377                    }
7378                }
7379            }
7380            Prop::DefaultValue(value) => {
7381                if let Some(input) = node.input.as_mut()
7382                    && !input.value_set
7383                {
7384                    input.value_set = true;
7385                    input.value = value;
7386                    flags |= dirty::INPUT_VALUE;
7387                    self.measure_input(key);
7388                }
7389            }
7390            prop => {
7391                let Some(input) = node.input.as_mut() else {
7392                    return Ok(());
7393                };
7394                let c = &mut input.config;
7395                let remeasure = match prop {
7396                    Prop::Placeholder(text) => {
7397                        c.placeholder = text;
7398                        true
7399                    }
7400                    Prop::Multiline(multiline) => {
7401                        c.multiline = multiline;
7402                        // Only a multiline input shows a built-in bar.
7403                        self.scrollbars_pending.push(key);
7404                        true
7405                    }
7406                    Prop::PlaceholderColor(color) => {
7407                        c.placeholder_color = color;
7408                        false
7409                    }
7410                    Prop::Secure(secure) => {
7411                        c.secure = secure;
7412                        false
7413                    }
7414                    Prop::KeyboardType(keyboard) => {
7415                        c.keyboard = keyboard;
7416                        false
7417                    }
7418                    Prop::KeyboardAppearance(appearance) => {
7419                        c.keyboard_appearance = appearance;
7420                        false
7421                    }
7422                    Prop::ReturnKeyType(key) => {
7423                        c.return_key = key;
7424                        false
7425                    }
7426                    Prop::AutoCapitalize(mode) => {
7427                        c.auto_capitalize = mode;
7428                        false
7429                    }
7430                    Prop::AutoCorrect(on) => {
7431                        c.auto_correct = on;
7432                        false
7433                    }
7434                    Prop::MaxLength(len) => {
7435                        c.max_length = len;
7436                        false
7437                    }
7438                    Prop::Readonly(on) => {
7439                        c.editable = !on;
7440                        false
7441                    }
7442                    Prop::SubmitBehavior(behavior) => {
7443                        c.submit_behavior = behavior;
7444                        false
7445                    }
7446                    Prop::PasteBehavior(behavior) => {
7447                        c.paste_behavior = behavior;
7448                        false
7449                    }
7450                    Prop::PasteMaxSize(max) => {
7451                        c.paste_max_size = max;
7452                        false
7453                    }
7454                    Prop::AutoFocus(on) => {
7455                        c.auto_focus = on;
7456                        false
7457                    }
7458                    Prop::SelectTextOnFocus(on) => {
7459                        c.select_text_on_focus = on;
7460                        false
7461                    }
7462                    Prop::Caret(on) => {
7463                        c.caret_hidden = !on;
7464                        false
7465                    }
7466                    Prop::InputAccessoryViewId(name) => {
7467                        c.accessory_id = name;
7468                        false
7469                    }
7470                    Prop::SelectionColor(color) => {
7471                        c.selection_color = color;
7472                        false
7473                    }
7474                    Prop::CaretColor(color) => {
7475                        c.caret_color = color;
7476                        false
7477                    }
7478                    Prop::AutoFill(fill) => {
7479                        c.auto_fill = fill;
7480                        false
7481                    }
7482                    Prop::Selection(start, end) => {
7483                        // Applied after the batch's value.
7484                        let id = node.id;
7485                        self.commands
7486                            .push((id, Command::SetSelection { start, end }));
7487                        return Ok(());
7488                    }
7489                    _ => return Ok(()),
7490                };
7491                flags |= dirty::INPUT;
7492                if remeasure {
7493                    self.measure_input(key);
7494                }
7495            }
7496        }
7497        if flags != 0 {
7498            self.mark(key, flags);
7499        }
7500        if slop_moved {
7501            self.slop_moved.push(key);
7502        }
7503        if rebuild_span {
7504            self.mark_text_block(key);
7505        }
7506        if copy_text_changed {
7507            if self.nodes[key as usize].inline {
7508                self.mark_text_block(key);
7509            } else if let Some(place) = self.placed_in_text(key) {
7510                self.mark_text_block(place);
7511            }
7512        }
7513        if key_ancestry {
7514            self.key_ancestry_dirty = true;
7515        }
7516        Ok(())
7517    }
7518
7519    /// Puts loose run `child_id` in text block or span `parent` without a
7520    /// node when it is the only child there; false when it cannot.
7521    fn fold_run(
7522        &mut self,
7523        parent: Key,
7524        parent_id: NodeId,
7525        child_id: NodeId,
7526        before: Option<NodeId>,
7527    ) -> bool {
7528        let node = &self.nodes[parent as usize];
7529        if before.is_some()
7530            || node.kind != Kind::Text
7531            || !node.children.is_empty()
7532            || self.folded.contains_key(&parent)
7533            || self.components.slot_hosts.contains_key(&parent_id)
7534        {
7535            return false;
7536        }
7537        let Some(run) = self.runs.get_mut(&child_id) else {
7538            return false;
7539        };
7540        // Moved from another block (no Remove first).
7541        let from = std::mem::replace(&mut run.block, parent);
7542        if from != NO_KEY {
7543            self.folded.remove(&from);
7544            self.mark_text_block(from);
7545        }
7546        self.folded.insert(parent, child_id);
7547        self.mark_text_block(parent);
7548        true
7549    }
7550
7551    /// Takes run `id` out of its block, keeping it without a node.
7552    fn unfold_run(&mut self, id: NodeId) {
7553        let Some(run) = self.runs.get_mut(&id) else {
7554            return;
7555        };
7556        let block = std::mem::replace(&mut run.block, NO_KEY);
7557        if block != NO_KEY {
7558            self.folded.remove(&block);
7559            self.mark_text_block(block);
7560        }
7561    }
7562
7563    /// Gives run `id` its node, in its block if it is in one (for any use
7564    /// other than holding text as a block's only child). Remove it from
7565    /// `runs` during allocation so the quota counts it only once, and
7566    /// restore it on failure so its block keeps its text.
7567    pub(super) fn materialize_run(&mut self, id: NodeId) -> Result<(), ApplyError> {
7568        let Some(run) = self.runs.remove(&id) else {
7569            return Ok(());
7570        };
7571        let key = match self.alloc(id, Kind::RawText) {
7572            Ok(key) => key,
7573            Err(e) => {
7574                self.runs.insert(id, run);
7575                return Err(e);
7576            }
7577        };
7578        self.nodes[key as usize].text = run.text;
7579        if run.block != NO_KEY {
7580            self.folded.remove(&run.block);
7581            let parent = self.nodes[run.block as usize].id;
7582            let _ = self.insert(parent, id, None);
7583        }
7584        Ok(())
7585    }
7586
7587    /// The text of the run text block or span `key` holds without a node.
7588    fn folded_text(&self, key: Key) -> Option<&str> {
7589        if self.folded.is_empty() {
7590            return None;
7591        }
7592        let id = self.folded.get(&key)?;
7593        self.runs.get(id).map(|r| r.text.as_str())
7594    }
7595
7596    fn insert(
7597        &mut self,
7598        parent_id: NodeId,
7599        child_id: NodeId,
7600        before: Option<NodeId>,
7601    ) -> Result<(), ApplyError> {
7602        let parent = self.key(parent_id)?;
7603        if !self.runs.is_empty() || !self.folded.is_empty() {
7604            if self.fold_run(parent, parent_id, child_id, before) {
7605                return Ok(());
7606            }
7607            self.materialize_run(child_id)?;
7608            if let Some(b) = before {
7609                self.materialize_run(b)?;
7610            }
7611            if let Some(&run) = self.folded.get(&parent) {
7612                self.materialize_run(run)?;
7613            }
7614        }
7615        let child = self.key(child_id)?;
7616        let from = self.nodes[child as usize].parent;
7617        if from != NO_KEY {
7618            self.input_bar_moves(child);
7619            self.note_move(from, parent);
7620        }
7621        let mut before = before.map(|b| self.key(b)).transpose()?;
7622        // Appended below the built-in bar, which stays on top.
7623        if before.is_none()
7624            && let Some((bar, _)) = self.nodes[parent as usize]
7625                .scroll
7626                .as_ref()
7627                .and_then(|s| s.bar.as_ref())
7628            && let Ok(bar) = self.key(*bar)
7629            && bar != child
7630        {
7631            before = Some(bar);
7632        }
7633        let Some(depth) = self
7634            .depth_outside(child, parent)
7635            .filter(|_| child != self.root)
7636        else {
7637            return Err(ApplyError::Cycle(child_id));
7638        };
7639        let max = MAX_TREE_DEPTH as u32;
7640        if depth + self.nodes[child as usize].height > max {
7641            // What left the child since may have made it shallower.
7642            if depth + self.count_heights(child) > max {
7643                return Err(ApplyError::TooDeep(MAX_TREE_DEPTH));
7644            }
7645        }
7646        if self.nodes[parent as usize]
7647            .shader
7648            .as_ref()
7649            .is_some_and(|s| {
7650                matches!(
7651                    s.role,
7652                    crate::shader::ShaderRole::Screen | crate::shader::ShaderRole::ScreenTransition
7653                )
7654            })
7655        {
7656            // It takes no space, so a child lays out in nothing: the
7657            // surface is what it draws through.
7658            log::warn!(
7659                target: "js",
7660                "node {child_id} in screen effect {parent_id}: a screen effect or transition has no children"
7661            );
7662        }
7663        if let Some(b) = before
7664            && (b == child || self.nodes[b as usize].parent != parent)
7665        {
7666            return Err(ApplyError::BadAnchor(self.nodes[b as usize].id));
7667        }
7668
7669        // Detach from the current position. A native view that stays visible
7670        // is moved by the insert below, so only emit a remove when the new
7671        // parent has no native view.
7672        let parent_created = self.nodes[parent as usize].created;
7673        if self.nodes[child as usize].parent != NO_KEY {
7674            self.unlink(child, !parent_created);
7675        }
7676
7677        let p = &self.nodes[parent as usize];
7678        // Inside a block or a span (not inside an attachment: its children
7679        // are its own layout's).
7680        let inline = p.kind == Kind::Text && !self.nodes[child as usize].fixed_view;
7681        let pos = match before {
7682            Some(b) => {
7683                let (pos, looked) = position_from_ends(&p.children, &b).expect("anchor is a child");
7684                self.placing(looked);
7685                pos
7686            }
7687            None => p.children.len(),
7688        };
7689        self.set_inline(child, inline);
7690        if !inline {
7691            // An attachment hidden with its span leaves the text: shown
7692            // where it goes (in a text, its block decides again).
7693            self.set_hidden_in_text(child, false);
7694        }
7695        self.nodes[child as usize].parent = parent;
7696        if self.nodes[child as usize].kind == Kind::Overlay {
7697            // Its logical parent changed: find its keyboard override again.
7698            self.key_ancestry_dirty = true;
7699        }
7700        self.nodes[parent as usize].children.insert(pos, child);
7701        self.raise_heights(child);
7702        self.key_content_changed(parent);
7703        self.rank_noted(child);
7704        self.tree_order_changed |= self.track_tree_order;
7705        self.tab_places_stale = true;
7706        if self.nodes[child as usize].states & crate::tailwind::state::FOCUS_WITHIN != 0 {
7707            // The focus moved with it: the views around it now.
7708            self.focus_moved = true;
7709        }
7710        self.ch_changed(child);
7711        self.status_bars_moved |= !self.status_bar_nodes.is_empty();
7712        self.outer_moved |= !self.parent_lists.is_empty() && self.may_hold_page_list(child);
7713        self.sticky_changed |= !self.sticky_nodes.is_empty();
7714        self.update_direction(child);
7715        if self.nodes[parent as usize].child_perspective.is_some() {
7716            self.mark(child, dirty::VIEW | dirty::ANIMATION);
7717        }
7718        let node = &self.nodes[parent as usize];
7719        let color = node.text_style.color.or(node.inherited_color);
7720        if self.nodes[child as usize].inherited_color != color {
7721            self.inherit_color_from(child, color);
7722        }
7723        self.groups_changed(child, parent);
7724        let child_node = &self.nodes[child as usize];
7725        if child_node
7726            .classes
7727            .as_ref()
7728            .is_some_and(|c| c.deps() & crate::tailwind::deps::POSITION != 0)
7729            // A view passing its position on reads it for its children.
7730            || (child_node.positional.has(Positional::PASS)
7731                && child_node.positional.has(Positional::CHILDREN))
7732        {
7733            self.reads_positions(parent);
7734        }
7735        if self.nodes[parent as usize]
7736            .positional
7737            .has(Positional::CHILDREN)
7738        {
7739            self.queue_positions(parent);
7740        }
7741        self.spacing_changed(parent, child);
7742        if self.pointer_none_classes > 0 {
7743            self.pointer_events_moved(parent);
7744        }
7745
7746        if inline {
7747            if self.nodes[child as usize].placeholder {
7748                self.ask_row(child);
7749            }
7750            self.mark_text_block(parent);
7751            return Ok(());
7752        }
7753        // A cell joining a list: register its slot and derive its style
7754        // from the list orientation.
7755        if self.nodes[parent as usize].list.is_some() {
7756            if let Some(slot) = self.nodes[child as usize].slot {
7757                self.nodes[parent as usize]
7758                    .list
7759                    .as_mut()
7760                    .expect("list")
7761                    .add_slot_cell(slot, child);
7762            }
7763            self.sync_layout_style(child);
7764        }
7765        let child_kind = self.nodes[child as usize].kind;
7766        if child_kind == Kind::InputAccessory {
7767            self.accessory_attached(child, true);
7768        }
7769        if child_kind == Kind::HeaderItem {
7770            self.mark(parent, dirty::SCREEN);
7771        }
7772        if let Some(child_layout) = self.nodes[child as usize].layout {
7773            // List cells, screens, modals and header items stay independent
7774            // layout roots.
7775            if self.nodes[parent as usize].list.is_none()
7776                && !self.nodes[child as usize].is_layout_root()
7777            {
7778                let index = self.layout_index_at(parent, pos);
7779                let parent_layout = self.nodes[parent as usize]
7780                    .layout
7781                    .expect("block parent has layout");
7782                self.layout
7783                    .insert_child_at_index(parent_layout, index as usize, child_layout);
7784            }
7785            self.needs_layout = true;
7786            // A dialog opening in content a scroll view has not made yet
7787            // makes the views around it: it shows over everything.
7788            let parent_created = parent_created
7789                || (child_kind == Kind::Modal
7790                    && self.nodes[parent as usize].culled
7791                    && self.uncull(parent));
7792            // An overlay's native view goes to its root view
7793            // (`sync_overlays`).
7794            if parent_created
7795                && !self.nodes[child as usize].is_overlay()
7796                && !{
7797                    let scope = self.cull_scope(parent);
7798                    self.hold_back(scope, child)
7799                }
7800            {
7801                self.ensure_created(child);
7802                let before = match self.nodes[parent as usize].list.as_ref() {
7803                    // Below the sticky cells of a list in its parent's
7804                    // viewport, which stay on top.
7805                    Some(list) if list.parent && !list.sent_sticky.is_empty() => {
7806                        self.below_sticky(parent, child)
7807                    }
7808                    _ => self.native_before_at(parent, child, pos),
7809                };
7810                // By the nodes' own ids (the ops may name an alias).
7811                self.mount.push(MountItem::Insert {
7812                    parent: self.nodes[parent as usize].id,
7813                    child: self.nodes[child as usize].id,
7814                    before,
7815                });
7816            }
7817        }
7818        Ok(())
7819    }
7820
7821    /// Detaches `key` from its parent (Remove op).
7822    fn detach(&mut self, key: Key) {
7823        self.input_bar_moves(key);
7824        self.unlink(key, true);
7825    }
7826
7827    /// A multiline input with a built-in bar beside it leaves its place:
7828    /// the bar goes, and is made again beside it where it goes.
7829    fn input_bar_moves(&mut self, key: Key) {
7830        let node = &self.nodes[key as usize];
7831        if node.input.as_ref().is_some_and(|i| i.bar.is_some()) {
7832            self.release_scrollbar(key);
7833            self.scrollbars_pending.push(key);
7834        }
7835    }
7836
7837    /// Unlinks `key` from its parent's children, layout and (optionally)
7838    /// native hierarchy.
7839    fn unlink(&mut self, key: Key, emit_remove: bool) {
7840        if self.nodes[key as usize].kind == Kind::Modal && self.nodes[key as usize].created {
7841            self.restoring_modal_focus = true;
7842        }
7843        let parent = self.nodes[key as usize].parent;
7844        let siblings = &mut self.nodes[parent as usize].children;
7845        let pos = siblings
7846            .iter()
7847            .position(|&c| c == key)
7848            .expect("child of parent");
7849        siblings.remove(pos);
7850        self.key_content_changed(parent);
7851        self.tree_order_changed |= self.track_tree_order;
7852        self.tab_places_stale = true;
7853        if let Some(list) = self.nodes[parent as usize].list.as_mut() {
7854            list.remove_cell(key);
7855        }
7856        if self.nodes[parent as usize]
7857            .positional
7858            .has(Positional::CHILDREN)
7859        {
7860            self.queue_positions(parent);
7861        }
7862        self.nodes[key as usize].parent = NO_KEY;
7863        if self.nodes[key as usize].states & crate::tailwind::state::FOCUS_WITHIN != 0 {
7864            // The focus left the views around it with it.
7865            self.focus_moved = true;
7866        }
7867        if self.nodes[parent as usize].child_perspective.is_some() {
7868            // Without the perspective wherever it goes next.
7869            self.mark(key, dirty::VIEW | dirty::ANIMATION);
7870        }
7871        self.spacing_changed(parent, NO_KEY);
7872        if self.pointer_none_classes > 0 && self.pointer_region(parent).is_some() {
7873            // It no longer inherits the region's `none`.
7874            self.pointer_pending.push(key);
7875            self.pointer_events_moved(parent);
7876        }
7877        self.groups_changed(key, parent);
7878        self.status_bars_moved |= !self.status_bar_nodes.is_empty();
7879        self.outer_moved |= !self.parent_lists.is_empty() && self.may_hold_page_list(key);
7880        self.sticky_changed |= !self.sticky_nodes.is_empty();
7881        if !self.pictured.is_empty() {
7882            self.unlinked_from.push(self.nodes[parent as usize].id);
7883        }
7884        let node = &self.nodes[key as usize];
7885        let (inline, layout, created, id) = (node.inline, node.layout, node.created, node.id);
7886        // Replaced by its row, of another size: the scroll views keep what
7887        // they show in place (`resize_anchor.rs`).
7888        self.resize_settling |= node.row_asked;
7889        if inline {
7890            self.mark_text_block(parent);
7891            return;
7892        }
7893        let kind = self.nodes[key as usize].kind;
7894        if kind == Kind::InputAccessory {
7895            self.accessory_attached(key, false);
7896        }
7897        if kind == Kind::HeaderItem {
7898            self.mark(parent, dirty::SCREEN);
7899        }
7900        if let Some(layout) = layout {
7901            if self.nodes[parent as usize].list.is_none()
7902                && !self.nodes[key as usize].is_layout_root()
7903            {
7904                let parent_layout = self.nodes[parent as usize]
7905                    .layout
7906                    .expect("block parent has layout");
7907                self.layout.remove_child(parent_layout, layout);
7908            }
7909            self.needs_layout = true;
7910            if emit_remove
7911                && created
7912                && self.nodes[parent as usize].created
7913                && !self.nodes[key as usize].is_overlay()
7914            {
7915                self.mount.push(MountItem::Remove { id });
7916                self.note_restructured(parent);
7917            }
7918        }
7919    }
7920
7921    /// A page's or dialog's `statusBar`: changed in place while the node
7922    /// is in the tree (so it keeps its place among the others); its entry
7923    /// is added or removed by [`Core::sync_status_bars`].
7924    fn set_status_bar(&mut self, key: Key, setting: Option<crate::StatusBarSetting>) {
7925        let Some(root) = self.nodes[key as usize].root.as_mut() else {
7926            return;
7927        };
7928        root.status_bar = setting;
7929        let entry = root.status_bar_entry;
7930        match (setting, entry) {
7931            (Some(s), Some(e)) => self.components.status_bars.set(e, s),
7932            (Some(_), None) => {
7933                if !self.status_bar_nodes.contains(&key) {
7934                    self.status_bar_nodes.push(key);
7935                }
7936                self.status_bars_moved = true;
7937            }
7938            (None, entry) => {
7939                if let Some(e) = entry {
7940                    self.components.status_bars.remove(e);
7941                    if let Some(root) = self.nodes[key as usize].root.as_mut() {
7942                        root.status_bar_entry = None;
7943                    }
7944                }
7945                self.status_bar_nodes.retain(|&k| k != key);
7946            }
7947        }
7948    }
7949
7950    /// The `statusBar` of each screen and modal in the tree has an entry,
7951    /// added in the order they got their setting; the others have none
7952    /// (once per commit, after the tree changed).
7953    fn sync_status_bars(&mut self) {
7954        if !std::mem::take(&mut self.status_bars_moved) {
7955            return;
7956        }
7957        for i in 0..self.status_bar_nodes.len() {
7958            let key = self.status_bar_nodes[i];
7959            let in_tree = self.is_ancestor(self.root, key);
7960            let Some(root) = self.nodes[key as usize].root.as_mut() else {
7961                continue;
7962            };
7963            match (in_tree, root.status_bar_entry, root.status_bar) {
7964                (true, None, Some(setting)) => {
7965                    root.status_bar_entry = Some(self.components.status_bars.add(setting));
7966                }
7967                (false, Some(entry), _) => {
7968                    root.status_bar_entry = None;
7969                    self.components.status_bars.remove(entry);
7970                }
7971                _ => {}
7972            }
7973        }
7974    }
7975
7976    fn release(&mut self, id: NodeId) -> Result<(), ApplyError> {
7977        if let Some(run) = self.runs.remove(&id) {
7978            if run.block != NO_KEY {
7979                self.folded.remove(&run.block);
7980                self.mark_text_block(run.block);
7981            }
7982            return Ok(());
7983        }
7984        let key = self.key(id)?;
7985        // Its run is orphaned like its children.
7986        if let Some(run) = self.folded.remove(&key)
7987            && let Some(run) = self.runs.get_mut(&run)
7988        {
7989            run.block = NO_KEY;
7990        }
7991        self.cancel_web_evaluations(id);
7992        self.webview_released(id);
7993        if key == self.root {
7994            return Ok(());
7995        }
7996        // What the core made for its `tooltip` goes first, out of it.
7997        if !self.overlay_state.tooltips.is_empty() {
7998            self.tooltip_released(id);
7999        }
8000        // So does its built-in bar.
8001        if self.nodes[key as usize].bar().is_some() {
8002            self.release_scrollbar(key);
8003        }
8004        if self.nodes[key as usize].parent != NO_KEY {
8005            // Deleting the view also detaches it natively.
8006            self.unlink(key, false);
8007        }
8008        // Out of the view it was virtualized against, before its key is
8009        // free for another node.
8010        if self.nodes[key as usize]
8011            .list
8012            .as_ref()
8013            .is_some_and(|l| l.parent)
8014        {
8015            self.forget_outer(key);
8016            self.parent_lists.retain(|&k| k != key);
8017        }
8018        let node = self.nodes.remove(key as usize);
8019        self.ch_readers -= usize::from(node.reads_ch);
8020        self.slots.remove(id as usize);
8021        if node.class_props.as_ref().and_then(|c| c.pointer_events)
8022            == Some(crate::props::PointerEvents::None)
8023        {
8024            self.pointer_none_classes -= 1;
8025        }
8026        if node.kind == Kind::List {
8027            self.lists.retain(|&k| k != key);
8028        }
8029        if node.sticky.is_some() {
8030            self.sticky_nodes.retain(|&k| k != key);
8031            self.sticky_changed = true;
8032        }
8033        if node.follow.is_some() {
8034            self.release_follower(key);
8035        }
8036        if !self.relators.is_empty() {
8037            self.release_relator(key);
8038        }
8039        if let Some(scroll) = node.scroll.as_ref() {
8040            if !scroll.dependents.is_empty() {
8041                self.outer_released(&scroll.dependents);
8042            }
8043            if scroll.asked.is_some() {
8044                self.outer_asked.retain(|&k| k != key);
8045            }
8046            self.sticky_views.retain(|&k| k != key);
8047            self.sticky_scrollers.retain(|&k| k != key);
8048        }
8049        if let Some((spacer, _)) = node.list.as_ref().and_then(|l| l.spacer) {
8050            self.layout.remove(spacer);
8051        }
8052        if node.kind == Kind::Text {
8053            self.attachment_blocks.retain(|&k| k != key);
8054        }
8055        if node.is_layout_root() {
8056            self.roots.retain(|&k| k != key);
8057        }
8058        if let Some(state) = node.root.as_ref().and_then(|r| r.overlay.as_ref()) {
8059            self.overlay_released(key, state.wrapper);
8060        }
8061        if let Some(root) = node.root.as_ref()
8062            && root.status_bar.is_some()
8063        {
8064            if let Some(entry) = root.status_bar_entry {
8065                self.components.status_bars.remove(entry);
8066            }
8067            self.status_bar_nodes.retain(|&k| k != key);
8068        }
8069        self.orientation_pages.retain(|&(k, _)| k != key);
8070        // Children are released by their own ops (the whole subtree became
8071        // unreachable in JS); orphan them so they never point at a dead key.
8072        for &c in &node.children {
8073            if let Some(child) = self.nodes.get_mut(c as usize) {
8074                child.parent = NO_KEY;
8075            }
8076        }
8077        if node.states & crate::tailwind::state::FOCUS_WITHIN != 0 {
8078            // The focus went with it, or is inside a child no longer in
8079            // it.
8080            self.focus_moved = true;
8081        }
8082        if let Some(layout) = node.layout {
8083            self.layout.remove(layout);
8084        }
8085        if node.created {
8086            self.mount.push(MountItem::Delete { id });
8087        }
8088        Ok(())
8089    }
8090
8091    /// A page's `supportedOrientations` (0: none): changed in place, so it
8092    /// keeps its place among the others.
8093    fn set_page_orientations(&mut self, key: Key, bits: u8) {
8094        match self.orientation_pages.iter_mut().find(|(k, _)| *k == key) {
8095            Some(page) if bits != 0 => page.1 = bits,
8096            Some(_) => self.orientation_pages.retain(|&(k, _)| k != key),
8097            None if bits != 0 => self.orientation_pages.push((key, bits)),
8098            None => {}
8099        }
8100    }
8101
8102    /// Sends the orientations of the page that decides them when they
8103    /// changed (once per commit): the last to get its setting of those in
8104    /// the tree and displayed, so a page kept in a tab that is not shown
8105    /// (`display: none`) does not decide while another tab is. Pages with a
8106    /// setting are few, and the walk is up their ancestors only.
8107    fn sync_orientations(&mut self) {
8108        if self.orientation_pages.is_empty() && self.orientations_shown == 0 {
8109            return;
8110        }
8111        let bits = self
8112            .orientation_pages
8113            .iter()
8114            .rev()
8115            .find(|&&(key, _)| self.displayed_in_tree(key))
8116            .map_or(0, |&(_, bits)| bits);
8117        if bits != self.orientations_shown {
8118            self.orientations_shown = bits;
8119            self.commands
8120                .push((crate::ROOT_ID, Command::Orientations(bits)));
8121        }
8122    }
8123
8124    /// Whether `key` is in the tree with no `display: none` on it or on any
8125    /// view above it, across layout roots (a page under a hidden tab).
8126    fn displayed_in_tree(&self, mut key: Key) -> bool {
8127        while key != NO_KEY {
8128            if key == self.root {
8129                return true;
8130            }
8131            let node = &self.nodes[key as usize];
8132            if node.layout.is_some_and(|l| self.layout.displays_none(l)) {
8133                return false;
8134            }
8135            key = node.parent;
8136        }
8137        false
8138    }
8139
8140    /// How many views are above `key` and `key` itself (1 for a view with
8141    /// no parent), or `None` when `ancestor` is one of them.
8142    fn depth_outside(&self, ancestor: Key, mut key: Key) -> Option<u32> {
8143        let mut depth = 0;
8144        while key != NO_KEY {
8145            if key == ancestor {
8146                return None;
8147            }
8148            depth += 1;
8149            key = self.nodes[key as usize].parent;
8150        }
8151        Some(depth)
8152    }
8153
8154    /// Counts how many levels of views are under each view of `key`'s
8155    /// subtree, keeps each count as that view's [`Node::height`] and returns
8156    /// `key`'s. Every view of it, not only `key`: [`Self::raise_heights`] stops at the first
8157    /// view already as high as what came under it, so a view left higher
8158    /// than it is would keep the views above it from hearing of what grows
8159    /// under it later.
8160    fn count_heights(&mut self, key: Key) -> u32 {
8161        // Each view after its parent: from the end, its children are
8162        // counted before it.
8163        let mut order = vec![key];
8164        let mut next = 0;
8165        while let Some(&at) = order.get(next) {
8166            next += 1;
8167            order.extend_from_slice(&self.nodes[at as usize].children);
8168        }
8169        for &at in order.iter().rev() {
8170            let height = self.nodes[at as usize]
8171                .children
8172                .iter()
8173                .map(|&c| self.nodes[c as usize].height + 1)
8174                .max()
8175                .unwrap_or(0);
8176            self.nodes[at as usize].height = height;
8177        }
8178        self.nodes[key as usize].height
8179    }
8180
8181    /// The app's keymap as mounted: with how the focus came
8182    /// (`Keymap::pointer_focus`) when a binding asks for
8183    /// it, kept to mount again as the focus moves (`sync_pointer_keymap`).
8184    fn keymap_with_focus(
8185        &mut self,
8186        keymap: Arc<crate::keymap::Keymap>,
8187    ) -> Arc<crate::keymap::Keymap> {
8188        if !keymap.takes_over_pointer_focus() {
8189            self.pointer_keymap = None;
8190            return keymap;
8191        }
8192        let pointer = self.focus.is_some() && self.focus_by_pointer;
8193        let mounted = Arc::new((*keymap).clone().with_pointer_focus(pointer));
8194        self.pointer_keymap = Some((keymap, pointer));
8195        mounted
8196    }
8197
8198    /// The focus a pointer gave came or went: the keymap whose bindings
8199    /// ask for it is mounted again, so the platform matches the next keys
8200    /// with it. One item per move, only for an app that asks.
8201    fn sync_pointer_keymap(&mut self) {
8202        let pointer = self.focus.is_some() && self.focus_by_pointer;
8203        let Some((keymap, sent)) = &self.pointer_keymap else {
8204            return;
8205        };
8206        if *sent == pointer {
8207            return;
8208        }
8209        let keymap = keymap.clone();
8210        let mounted = self.keymap_with_focus(keymap);
8211        self.mount.push(MountItem::Keymap(mounted));
8212    }
8213
8214    /// `key` came under its parent: the views above it are as high as it
8215    /// makes them. Stops at the first that was already: a view is always at
8216    /// least one higher than each of its children.
8217    fn raise_heights(&mut self, key: Key) {
8218        let mut height = self.nodes[key as usize].height + 1;
8219        let mut at = self.nodes[key as usize].parent;
8220        while at != NO_KEY {
8221            let node = &mut self.nodes[at as usize];
8222            if node.height >= height {
8223                break;
8224            }
8225            node.height = height;
8226            height += 1;
8227            at = node.parent;
8228        }
8229    }
8230
8231    /// A popup that gives the keyboard focus back to `to` opens
8232    /// ([`crate::element::ElementRef::focus_back_origin`]): on macOS and
8233    /// iOS, opened by a pointer, the focus it opened with is where the focus goes back to
8234    /// (the pointer's press left it there, off the trigger); elsewhere the
8235    /// trigger takes it back as the pointer's (`pointer_focus_back`);
8236    /// opened by the keyboard, the trigger takes it back, as before.
8237    pub(super) fn note_focus_origin(&mut self, to: NodeId) {
8238        let mut origins = std::mem::take(&mut self.focus_origins);
8239        // Triggers that are gone leave no note behind (a popup closed by a
8240        // press outside gives nothing back, so its note stays until then).
8241        origins.retain(|&(id, _)| id != to && self.key(id).is_ok());
8242        if self.modality == Some(crate::platform::InputModality::Pointer) {
8243            origins.push((to, self.focus));
8244        }
8245        self.focus_origins = origins;
8246    }
8247
8248    /// Whether a press leaves the keyboard focus where it is (macOS and
8249    /// iOS, as AppKit and UIKit do), so a popup a pointer opened gives it
8250    /// back where it was. Elsewhere a press focuses the trigger, as native
8251    /// buttons there do, and closing gives the trigger the focus.
8252    fn press_leaves_focus(&self) -> bool {
8253        matches!(
8254            self.components.environment.os,
8255            crate::platform::Os::MacOs | crate::platform::Os::Ios
8256        )
8257    }
8258
8259    /// The keyboard focus back from the popup `from` (its node, when it is
8260    /// still there) to `before`, the focus a pointer opened it with: there
8261    /// when that view is still in the tree and outside the popup, else off
8262    /// the popup, so its keys go to the app's shortcuts as they did before
8263    /// it opened.
8264    fn focus_back_to_origin(&mut self, before: Option<(Key, NodeId)>, from: Option<Key>) {
8265        let outside = |this: &Self, key: Key| from.is_none_or(|from| !this.is_ancestor(from, key));
8266        let alive = |this: &Self, (key, id): (Key, NodeId)| {
8267            this.key(id).is_ok_and(|k| k == key) && this.is_ancestor(this.root, key)
8268        };
8269        if let Some((_, id)) = before.filter(|&b| alive(self, b) && outside(self, b.0)) {
8270            self.commands.push((id, Command::Focus));
8271        } else if let Some((_, id)) = self.focus.filter(|&(key, _)| !outside(self, key)) {
8272            self.commands.push((id, Command::Blur));
8273        }
8274    }
8275
8276    /// A dialog opening gives the keyboard focus to its first control, as
8277    /// the web's `<dialog>` and the desktops' dialogs do, unless the focus
8278    /// is already inside it or goes there in this commit (`autoFocus`, the
8279    /// app's `focus()`). Desktops and the web only: a phone would raise
8280    /// its keyboard for a field.
8281    fn focus_opened_modals(&mut self) {
8282        let opened = std::mem::take(&mut self.modals_opened);
8283        if !self.has_window() {
8284            return;
8285        }
8286        for (modal, id) in opened {
8287            // Opened and removed again in the same commit.
8288            let Some(node) = self.nodes.get(modal as usize).filter(|n| n.id == id) else {
8289                continue;
8290            };
8291            if node.kind != Kind::Modal
8292                || !node.created
8293                || node.parent == NO_KEY
8294                || !self.displayed_in_tree(modal)
8295                // A window of the app's own is no dialog.
8296                || self.window_ids.values().any(|(root, _)| *root == node.id)
8297            {
8298                continue;
8299            }
8300            if self
8301                .focus
8302                .is_some_and(|(key, _)| self.is_ancestor(modal, key))
8303            {
8304                continue;
8305            }
8306            let inside = |this: &Self, id: NodeId| {
8307                this.key(id).is_ok_and(|key| this.is_ancestor(modal, key))
8308            };
8309            let asked = self
8310                .commands
8311                .iter()
8312                .any(|(to, c)| matches!(c, Command::Focus) && inside(self, *to))
8313                || self.mount.iter().any(|m| {
8314                    matches!(
8315                        m,
8316                        MountItem::Command {
8317                            id: to,
8318                            command: Command::Focus,
8319                        } if inside(self, *to)
8320                    )
8321                });
8322            if asked {
8323                continue;
8324            }
8325            // A field that focuses itself (`autoFocus`) is `Err`.
8326            if let Ok(Some(id)) = self.first_control(modal) {
8327                self.commands.push((id, Command::Focus));
8328                self.modal_focus_given = Some(id);
8329            }
8330        }
8331    }
8332
8333    /// The first view under `key` (depth first) the keyboard focus can go
8334    /// to: an enabled input, or an enabled view that takes presses or is
8335    /// `focusable`. Not in a hidden subtree, an overlay or another modal.
8336    /// `Err` when an input under it focuses itself (`autoFocus`).
8337    fn first_control(&self, key: Key) -> Result<Option<NodeId>, ()> {
8338        let mut found = None;
8339        let mut stack: Vec<Key> = self.nodes[key as usize]
8340            .children
8341            .iter()
8342            .rev()
8343            .copied()
8344            .collect();
8345        while let Some(k) = stack.pop() {
8346            let node = &self.nodes[k as usize];
8347            if matches!(node.kind, Kind::Overlay | Kind::Modal)
8348                || node.layout.is_some_and(|l| self.layout.displays_none(l))
8349            {
8350                continue;
8351            }
8352            let disabled = node.states & crate::tailwind::state::DISABLED != 0;
8353            let focusable = node.props.as_ref().and_then(|p| p.focusable);
8354            if let Some(input) = node.input.as_ref() {
8355                if input.config.auto_focus {
8356                    return Err(());
8357                }
8358                if found.is_none() && !disabled && focusable != Some(false) {
8359                    found = Some(node.id);
8360                }
8361            } else if found.is_none()
8362                && !disabled
8363                && (focusable == Some(true)
8364                    || (focusable.is_none() && node.mounted_events().contains(EventKind::Press)))
8365            {
8366                found = Some(node.id);
8367            }
8368            stack.extend(node.children.iter().rev().copied());
8369        }
8370        Ok(found)
8371    }
8372
8373    fn is_ancestor(&self, ancestor: Key, mut key: Key) -> bool {
8374        while key != NO_KEY {
8375            if key == ancestor {
8376                return true;
8377            }
8378            key = self.nodes[key as usize].parent;
8379        }
8380        false
8381    }
8382
8383    /// The native sibling `child` goes below: native views are stacked by
8384    /// `zIndex`, then in tree order.
8385    fn native_before(&self, parent: Key, child: Key) -> Option<NodeId> {
8386        let pos = self.nodes[parent as usize]
8387            .children
8388            .iter()
8389            .inspect(|_| self.placing(1))
8390            .position(|&c| c == child)?;
8391        self.native_before_at(parent, child, pos)
8392    }
8393
8394    /// [`Self::native_before`] for `child` at `pos` among its siblings.
8395    /// When none of them was ever stacked apart, the next made sibling.
8396    ///
8397    /// A view in its parent never goes below a sibling the platform places
8398    /// elsewhere (a screen, a modal, a header item, an input accessory):
8399    /// that sibling is not among the parent's native subviews, so the
8400    /// platform would add the view on top of the others instead.
8401    fn native_before_at(&self, parent: Key, child: Key, pos: usize) -> Option<NodeId> {
8402        let children = &self.nodes[parent as usize].children;
8403        let z = self.nodes[child as usize].stack_rank();
8404        let in_parent = !self.nodes[child as usize].kind.is_root();
8405        let anchors = |n: &Node| {
8406            n.created && n.layout.is_some() && !n.is_overlay() && !(in_parent && n.kind.is_root())
8407        };
8408        if !self.nodes[parent as usize].ranked_children && z == (0, false) {
8409            let next = children[pos + 1..].iter().find_map(|&c| {
8410                self.placing(1);
8411                let n = &self.nodes[c as usize];
8412                anchors(n).then_some(n.id)
8413            });
8414            return match next {
8415                Some(id) => Some(id),
8416                None if !self.overlays.is_empty() => self.first_overlay_in(parent),
8417                None => None,
8418            };
8419        }
8420        self.placing(children.len());
8421        let mut best: Option<((i32, bool), usize, NodeId)> = None;
8422        for (i, &c) in children.iter().enumerate() {
8423            let n = &self.nodes[c as usize];
8424            if c == child || !anchors(n) {
8425                continue;
8426            }
8427            let rank = n.stack_rank();
8428            if (rank, i) > (z, pos) && best.is_none_or(|b| (rank, i) < (b.0, b.1)) {
8429                best = Some((rank, i, n.id));
8430            }
8431        }
8432        // Below the overlays shown in it, when it is a root view.
8433        match best {
8434            Some(b) => Some(b.2),
8435            None if !self.overlays.is_empty() => self.first_overlay_in(parent),
8436            None => None,
8437        }
8438    }
8439
8440    /// Notes on `key`'s parent that `key` is stacked apart from the
8441    /// others, when it is ([`Node::ranked_children`]).
8442    fn rank_noted(&mut self, key: Key) {
8443        let node = &self.nodes[key as usize];
8444        let parent = node.parent;
8445        if parent != NO_KEY && node.stack_rank() != (0, false) {
8446            self.nodes[parent as usize].ranked_children = true;
8447        }
8448    }
8449
8450    /// `key`'s `zIndex` changed: moves its native view among its siblings.
8451    fn restack(&mut self, key: Key) {
8452        self.rank_noted(key);
8453        let node = &self.nodes[key as usize];
8454        let (parent, id) = (node.parent, node.id);
8455        if parent == NO_KEY
8456            || !node.created
8457            || node.layout.is_none()
8458            || node.inline
8459            || node.is_overlay()
8460        {
8461            return;
8462        }
8463        let p = &self.nodes[parent as usize];
8464        if !p.created || p.list.is_some() {
8465            return;
8466        }
8467        let before = self.native_before(parent, key);
8468        self.mount.push(MountItem::Insert {
8469            parent: p.id,
8470            child: id,
8471            before,
8472        });
8473    }
8474
8475    /// `allowFontScaling` / `maxFontSizeMultiplier` changed on `key`.
8476    fn font_settings_changed(&mut self, key: Key) {
8477        match self.nodes[key as usize].kind {
8478            Kind::Text => self.mark_text_block(key),
8479            Kind::Input => {
8480                self.measure_input(key);
8481                self.mark(key, dirty::INPUT);
8482            }
8483            _ => {}
8484        }
8485    }
8486
8487    /// Where the child at `pos` among `parent`'s children goes among the
8488    /// children of `parent`'s layout node: before the layout node of the
8489    /// next sibling that has one (the layout node's children are those
8490    /// siblings', in order), or after them all. Looks at the siblings next
8491    /// to it and at the layout children near `pos`, not at every sibling
8492    /// before it: views inserted before the one after a list's rows, or
8493    /// before the first of a chat's messages, look at a few of them each.
8494    fn layout_index_at(&self, parent: Key, pos: usize) -> u32 {
8495        let node = &self.nodes[parent as usize];
8496        let layout = node.layout.expect("block parent has layout");
8497        let next = node.children[pos + 1..]
8498            .iter()
8499            .inspect(|_| self.placing(1))
8500            .find_map(|&c| {
8501                let c = &self.nodes[c as usize];
8502                c.layout.filter(|_| !c.is_layout_root())
8503            });
8504        let index = match next {
8505            // As many layout children are before it as siblings with one
8506            // are: at most `pos`, fewer by those without one.
8507            Some(next) => match position_near(self.layout.children(layout), &next, pos) {
8508                Some((index, looked)) => {
8509                    self.placing(looked);
8510                    index
8511                }
8512                None => {
8513                    debug_assert!(false, "a sibling's layout node is its parent's child");
8514                    self.render_index(parent, pos) as usize
8515                }
8516            },
8517            None => self.layout.children_len(layout),
8518        };
8519        debug_assert!(
8520            pos + 1 != node.children.len() || index as u32 == self.rendering_before(parent, pos),
8521            "the layout node's children are its rendering children"
8522        );
8523        index as u32
8524    }
8525
8526    /// The rendering siblings before `pos` among `parent`'s children,
8527    /// counted: what [`Self::layout_index_at`] finds without counting them.
8528    /// Looks at each of them ([`Components::placing_work`]).
8529    fn render_index(&self, parent: Key, pos: usize) -> u32 {
8530        self.placing(pos);
8531        self.rendering_before(parent, pos)
8532    }
8533
8534    /// [`Self::render_index`] uncounted, for the check of debug builds.
8535    fn rendering_before(&self, parent: Key, pos: usize) -> u32 {
8536        self.nodes[parent as usize].children[..pos]
8537            .iter()
8538            .map(|&c| &self.nodes[c as usize])
8539            .filter(|c| c.layout.is_some() && !c.is_layout_root())
8540            .count() as u32
8541    }
8542
8543    /// Moves `key` (and its subtree) into or out of an inline context.
8544    fn set_inline(&mut self, key: Key, inline: bool) {
8545        let node = &mut self.nodes[key as usize];
8546        if node.inline == inline {
8547            return;
8548        }
8549        node.inline = inline;
8550        if node.kind != Kind::Text {
8551            // Other elements inside text are not supported; they are ignored.
8552            return;
8553        }
8554        if inline {
8555            // Block -> span: spans have no layout node or native view; the
8556            // span keeps the style for when it is a block again.
8557            if let Some(l) = node.layout.take() {
8558                if node.base_layout.is_none() {
8559                    node.base_layout = Some(Box::new(self.layout.style(l).clone()));
8560                }
8561                self.layout.remove(l);
8562            }
8563            if node.created {
8564                node.created = false;
8565                self.mount.push(MountItem::Delete { id: node.id });
8566            }
8567        } else {
8568            // A fixed text keeps its style: the layout node takes it with
8569            // the position it is fixed at ([`Self::sync_layout_style`]).
8570            let style = if node.fixed_view {
8571                node.base_layout.as_deref().cloned()
8572            } else {
8573                node.base_layout.take().map(|b| *b)
8574            }
8575            .unwrap_or_default();
8576            let cx = LeafContext::Text(Box::new(TextContext::new(Arc::default())));
8577            let layout = self.layout.new_leaf_with_context(style, cx);
8578            self.layout.set_tag(layout, key);
8579            node.layout = Some(layout);
8580            self.mark(key, dirty::TEXT_BUILD);
8581        }
8582    }
8583
8584    /// Creates the native views of `key`'s subtree if needed, wiring up the
8585    /// children in order.
8586    fn ensure_created(&mut self, key: Key) {
8587        let has_attachments = self.attachment_blocks.contains(&key);
8588        let node = &mut self.nodes[key as usize];
8589        if node.created || node.layout.is_none() {
8590            return;
8591        }
8592        node.created = true;
8593        self.pace.made += 1;
8594        // The frame it was given while culled, its view's first.
8595        let culled_frame = std::mem::take(&mut node.culled)
8596            .then_some(node.frame)
8597            .filter(|f| !f.origin.x.0.is_nan());
8598        self.tree_order_changed |= self.track_tree_order;
8599        self.tab_places_stale = true;
8600        if node.kind == Kind::Modal {
8601            self.modals_opened.push((key, node.id));
8602        }
8603        if node.kind == Kind::Text {
8604            self.measure_for_real(key);
8605        }
8606        // A follower made after layout (it waited, culled or paced) took the
8607        // frame layout gave it, and no walk of `emit_frames_in` told
8608        // `laid_follower` of it, so `place_follower` has nothing to place:
8609        // lay it out again, which does.
8610        if culled_frame.is_some()
8611            && self.nodes[key as usize].follow.is_some()
8612            && let Some(layout) = self.nodes[key as usize].layout
8613        {
8614            self.layout.mark_dirty(layout);
8615            self.needs_layout = true;
8616        }
8617        let node = &mut self.nodes[key as usize];
8618        if let Some(scroll) = node.scroll.as_mut() {
8619            scroll.content = None;
8620            // Sticky ranges computed while culled have not reached a
8621            // native view yet. Send them once this view is made.
8622            if !scroll.view_sticky.is_empty() {
8623                self.sticky_views.push(key);
8624            }
8625            // The new native view counts the core's scrolls from zero.
8626            scroll.issued = 0;
8627            scroll.target = None;
8628            scroll.pending.clear();
8629        }
8630        // A list in its parent's viewport is a plain view clipping its
8631        // cells.
8632        let parent_list = node.list.as_ref().is_some_and(|l| l.parent);
8633        let id = node.id;
8634        let kind = node.kind;
8635        let mut flags = self.mount_state(key);
8636        let node = &mut self.nodes[key as usize];
8637        if kind == Kind::Text && has_attachments {
8638            // Its attachments' views go inside the new view.
8639            node.attached.clear();
8640            flags |= dirty::TEXT_BUILD;
8641        }
8642        self.mount.push(MountItem::Create {
8643            id,
8644            kind: if parent_list {
8645                ViewKind::View
8646            } else {
8647                kind.view_kind()
8648            },
8649        });
8650        if let Some(component) = self.nodes[key as usize].component.as_mut() {
8651            // Unnamed, it is named later in this commit (`set_prop`), or
8652            // never: the flush of its props says which.
8653            if let Some(name) = &component.name {
8654                self.mount.push(MountItem::Component {
8655                    id,
8656                    name: name.clone(),
8657                });
8658            }
8659            // A GPU view's renderer, before its props (set later, it is
8660            // sent then).
8661            if let Some(source) = &component.source {
8662                self.mount.push(MountItem::GpuView {
8663                    id,
8664                    source: Some(source.clone()),
8665                });
8666            }
8667        }
8668        if let Some(item) = self.creation_tracking(key) {
8669            self.mount.push(item);
8670        }
8671        if let Some(frame) = culled_frame {
8672            self.nodes[key as usize].frame = frame;
8673            self.mount.push(MountItem::Frame { id, frame });
8674            // And its content size, before any scroll it is made for: the
8675            // platform clamps a scroll to the content it knows.
8676            let content = self.nodes[key as usize]
8677                .scroll
8678                .as_mut()
8679                .and_then(|s| s.culled_content.take());
8680            if let Some(size) = content {
8681                self.set_scroll_content(key, size);
8682            }
8683            if kind == Kind::Canvas
8684                && self.nodes[key as usize]
8685                    .drawing
8686                    .as_ref()
8687                    .is_some_and(|d| d.fit().is_some())
8688            {
8689                self.fitted_pending.push(key);
8690            }
8691            // Beside its frame, an input takes its content box from the
8692            // layout and a scroll view its extent; made after it was laid
8693            // out, nothing lays it out again to send them.
8694            if matches!(kind, Kind::Input | Kind::Scroll) {
8695                self.emit_frames(key);
8696            }
8697        }
8698        let projected = self.nodes[key as usize].projected;
8699        if self.mount_projected && projected != 0 {
8700            self.mount.push(MountItem::ProjectStates {
8701                id,
8702                states: projected,
8703            });
8704        }
8705        self.mark(key, flags);
8706        if !kind.is_container() {
8707            return;
8708        }
8709        // Bottom to top: by `zIndex`, then in order.
8710        let mut children = std::mem::take(&mut self.nodes[key as usize].children);
8711        let original = children.clone();
8712        if children
8713            .iter()
8714            .any(|&c| self.nodes[c as usize].stack_rank() != (0, false))
8715        {
8716            children.sort_by_key(|&c| self.nodes[c as usize].stack_rank());
8717        }
8718        // Children far down a scroll view's content wait (`cull.rs`).
8719        let scope = self.cull_scope(key);
8720        for &child in &children {
8721            let c = &self.nodes[child as usize];
8722            if c.layout.is_some() && !c.is_overlay() && !self.hold_back(scope, child) {
8723                self.ensure_created(child);
8724                let child_id = self.nodes[child as usize].id;
8725                self.mount.push(MountItem::Insert {
8726                    parent: id,
8727                    child: child_id,
8728                    before: None,
8729                });
8730            }
8731        }
8732        self.nodes[key as usize].children = original;
8733    }
8734
8735    /// Resets what `key`'s native view was last sent and returns what a new
8736    /// view needs: a new view has the default style and no listeners.
8737    fn mount_state(&mut self, key: Key) -> u32 {
8738        let node = &mut self.nodes[key as usize];
8739        let kind = node.kind;
8740        node.frame = Bounds::UNSET;
8741        node.emitted = None;
8742        if let Some(layout) = node.layout {
8743            self.layout.mark_stale(layout);
8744        }
8745        let node = &mut self.nodes[key as usize];
8746        // A list in its parent's viewport is a plain view clipping its
8747        // cells (`Node::mounted_view_style`), with no scroll view's config.
8748        let parent_list = node.list.as_ref().is_some_and(|l| l.parent);
8749        let mut flags = 0;
8750        if !node.view_style.is_default()
8751            || node.elevation != Points::ZERO
8752            || node.backdrop_material != crate::BackdropMaterial::default()
8753            || node.macos_backdrop.is_some()
8754            || node.windows_backdrop.is_some()
8755            || parent_list
8756            || node.spare
8757            || node.hidden_in_text
8758        {
8759            flags |= dirty::VIEW;
8760        }
8761        if !node.events.is_empty() {
8762            flags |= dirty::EVENTS;
8763        }
8764        if kind == Kind::Text {
8765            flags |= dirty::TEXT_MOUNT;
8766        }
8767        if node.image.as_ref().is_some_and(|i| i.source.is_some()) {
8768            flags |= dirty::IMAGE;
8769        }
8770        if let Some(scroll) = &node.scroll
8771            && !parent_list
8772        {
8773            flags |= dirty::SCROLL;
8774            if scroll.behavior != ScrollBehavior::default() {
8775                flags |= dirty::SCROLL_BEHAVIOR;
8776            }
8777            if scroll.refreshing {
8778                flags |= dirty::REFRESHING;
8779            }
8780        }
8781        if !node.animated.is_empty()
8782            || node.drawing.as_ref().is_some_and(|d| !d.slots.is_empty())
8783            || node.component.as_ref().is_some_and(|c| !c.slots.is_empty())
8784            || node
8785                .shader
8786                .as_ref()
8787                .and_then(|s| s.layer.as_ref())
8788                .is_some_and(|l| !l.nodes.is_empty())
8789        {
8790            flags |= dirty::ANIMATION;
8791        }
8792        if node.drawing.is_some() {
8793            flags |= dirty::CANVAS;
8794        }
8795        if node.shader.as_ref().is_some_and(|s| s.layer.is_some()) {
8796            flags |= dirty::SHADER;
8797        }
8798        if !node.gestures.is_empty() {
8799            flags |= dirty::PAN;
8800        }
8801        // What its classes and styles say of `pointer-events` was worked out
8802        // before the view was there to hear it.
8803        if node.props.is_some()
8804            || node.class_pointer != crate::props::PointerEvents::Auto
8805            || node.spare
8806            || node.hidden_in_text
8807            || node.list.as_ref().is_some_and(|l| l.parent)
8808        {
8809            flags |= dirty::VIEW_PROPS;
8810        }
8811        match kind {
8812            Kind::Screen => flags |= dirty::SCREEN,
8813            Kind::Modal => flags |= dirty::MODAL,
8814            _ => {}
8815        }
8816        if node.control.is_some() {
8817            flags |= dirty::NATIVE;
8818        }
8819        if let Some(list) = node.list.as_mut() {
8820            list.dirty = true;
8821        }
8822        if let Some(input) = node.input.as_mut() {
8823            input.content = None;
8824            flags |= dirty::INPUT;
8825            if !input.value.is_empty() {
8826                flags |= dirty::INPUT_VALUE;
8827            }
8828        }
8829        if let Some(component) = node.component.as_mut() {
8830            // The new component gets every property, and its slots' names.
8831            component.changed = component.props.iter().map(|(k, _)| k.clone()).collect();
8832            component.slots_changed.set(!component.slots.is_empty());
8833            flags |= dirty::COMPONENT;
8834        }
8835        flags
8836    }
8837
8838    #[inline]
8839    /// Sets GPU view `key`'s renderer: sent with its `Create`, or now when
8840    /// it is made already, with every prop again (a new renderer starts
8841    /// from none).
8842    fn set_gpu_source(&mut self, key: Key, id: NodeId, source: Option<crate::gpu::GpuSource>) {
8843        let node = &mut self.nodes[key as usize];
8844        let created = node.created;
8845        let Some(component) = node.component.as_mut() else {
8846            return;
8847        };
8848        if component.source == source {
8849            return;
8850        }
8851        component.source = source.clone();
8852        if !created {
8853            return;
8854        }
8855        self.mount.push(MountItem::GpuView { id, source });
8856        component.changed = component.props.iter().map(|(k, _)| k.clone()).collect();
8857        let mut flags = dirty::COMPONENT;
8858        if !component.slots.is_empty() {
8859            component.slots_changed.set(true);
8860            flags |= dirty::ANIMATION;
8861        }
8862        self.mark(key, flags);
8863    }
8864
8865    fn mark(&mut self, key: Key, flags: u32) {
8866        let node = &mut self.nodes[key as usize];
8867        node.dirty |= flags;
8868        // A culled view given a transform or an animated value may show
8869        // away from its frame now, and so may what a view with one holds
8870        // (`cull.rs`).
8871        if flags & (dirty::VIEW | dirty::ANIMATION) != 0
8872            && (node.culled
8873                || !self.culling.is_empty()
8874                    && (!node.animated.is_empty() || !node.view_style.transform.ops().is_empty()))
8875        {
8876            self.cull_dirty = true;
8877        }
8878        if !node.queued {
8879            node.queued = true;
8880            self.queue.push(key);
8881        }
8882    }
8883
8884    /// Marks the text block containing `key` (or `key` itself) for rebuild.
8885    fn mark_text_block(&mut self, mut key: Key) {
8886        loop {
8887            let node = &self.nodes[key as usize];
8888            if !node.inline {
8889                if node.kind == Kind::Text {
8890                    self.mark(key, dirty::TEXT_BUILD);
8891                }
8892                return;
8893            }
8894            if node.parent == NO_KEY {
8895                // A detached span: rebuilt when it is inserted into a block.
8896                return;
8897            }
8898            key = node.parent;
8899        }
8900    }
8901
8902    fn flush_dirty(&mut self) {
8903        loop {
8904            // The children that moved since, each parent's once.
8905            self.flush_positions();
8906            self.flush_dirty_once();
8907            // Text blocks create the views of new attachments while
8908            // flushing, which queues them; texts inside attachments built
8909            // after their block resize them, which builds the block again.
8910            self.check_attachments();
8911            if self.queue.is_empty() {
8912                break;
8913            }
8914        }
8915    }
8916
8917    fn flush_dirty_once(&mut self) {
8918        let mut queue = std::mem::take(&mut self.queue);
8919        for &key in &queue {
8920            let Some(node) = self.nodes.get_mut(key as usize) else {
8921                continue;
8922            };
8923            let mut flags = std::mem::take(&mut node.dirty);
8924            node.queued = false;
8925            if flags & dirty::TEXT_BUILD != 0 && node.layout.is_some() {
8926                if self.rebuild_text(key) {
8927                    flags |= dirty::TEXT_MOUNT;
8928                }
8929                // Whether it shows characters (`terminal_layout::Role`).
8930                self.sync_grid_role(key);
8931            }
8932            let node = &self.nodes[key as usize];
8933            if !node.created {
8934                continue;
8935            }
8936            let id = node.id;
8937            if flags & dirty::VIEW != 0 {
8938                let style = self.mounted_view_style(key);
8939                self.mount.push(MountItem::ViewStyle { id, style });
8940            }
8941            if flags & dirty::EVENTS != 0 {
8942                self.mount.push(MountItem::Events {
8943                    id,
8944                    events: node.mounted_events(),
8945                });
8946            }
8947            if flags & dirty::IMAGE != 0
8948                && let Some(image) = &node.image
8949            {
8950                // The style's `objectFit`; an image covers its box by
8951                // default.
8952                let resize_mode = node.object_fit.unwrap_or_default();
8953                // Bundled assets with variants: the one for the screen.
8954                let ratio = self.components.environment.pixel_ratio;
8955                self.mount.push(MountItem::Image {
8956                    id,
8957                    source: image.source.as_ref().map(|s| s.resolved(ratio)),
8958                    resize_mode,
8959                    options: crate::mount::ImageOptions {
8960                        placeholder: image
8961                            .options
8962                            .placeholder
8963                            .as_ref()
8964                            .map(|s| s.resolved(ratio)),
8965                        blur_radius: image.options.blur_radius,
8966                        fade_ms: image.options.fade_ms,
8967                        position: node.view_style.object_position,
8968                        current_color: image.svg_current_color.then(|| self.resolved_paint(key).1),
8969                    },
8970                });
8971            }
8972            if let Some(scroll) = &node.scroll
8973                && node.list.as_ref().is_none_or(|l| !l.parent)
8974            {
8975                if flags & dirty::SCROLL != 0 {
8976                    self.mount.push(MountItem::ScrollConfig {
8977                        id,
8978                        horizontal: scroll.horizontal,
8979                        // A built-in bar takes the indicator's place.
8980                        scrollbar_visible: scroll.scrollbar != crate::ScrollbarSetting::Hidden
8981                            && scroll.bar.is_none(),
8982                        replaced: scroll.bar.is_some(),
8983                        scroll_value: scroll.scroll_value,
8984                        pull_value: scroll.pull_value,
8985                        keyboard_dismiss: scroll.keyboard_dismiss,
8986                        mirrored: node.kind == Kind::List && scroll.horizontal && node.rtl,
8987                    });
8988                }
8989                if flags & dirty::SCROLL_BEHAVIOR != 0 {
8990                    self.mount.push(MountItem::ScrollBehavior {
8991                        id,
8992                        behavior: Box::new(scroll.behavior.clone()),
8993                    });
8994                }
8995                if flags & dirty::REFRESHING != 0 {
8996                    self.mount.push(MountItem::Refreshing {
8997                        id,
8998                        refreshing: scroll.refreshing,
8999                    });
9000                }
9001            }
9002            if flags & dirty::ANIMATION != 0 {
9003                let mut bindings = node.animated.clone();
9004                // A sticky view's animated inset is its scroll view's
9005                // (`sticky.rs`); other views' insets do not animate.
9006                if bindings
9007                    .iter()
9008                    .any(|(p, _)| matches!(p, AnimationProp::StickyTop | AnimationProp::StickyLeft))
9009                {
9010                    if node.sticky.is_none() && !self.inset_warned {
9011                        self.inset_warned = true;
9012                        log::warn!(
9013                            target: "js",
9014                            "an animated `top` / `left` only moves a `position: sticky` view's sticking point; it is ignored on view {id}"
9015                        );
9016                    }
9017                    bindings.retain(|(p, _)| {
9018                        !matches!(p, AnimationProp::StickyTop | AnimationProp::StickyLeft)
9019                    });
9020                }
9021                // Its transform's steps come after its parent's perspective.
9022                let steps = self.perspective_steps(key);
9023                if steps > 0 {
9024                    for (prop, _) in &mut bindings {
9025                        if let AnimationProp::Transform(i) = prop {
9026                            *i += steps;
9027                        }
9028                    }
9029                }
9030                if let Some(d) = &node.drawing {
9031                    bindings.extend(
9032                        d.slots
9033                            .iter()
9034                            .enumerate()
9035                            .map(|(i, &n)| (AnimationProp::CanvasArg(i as u16), n)),
9036                    );
9037                }
9038                if let Some(layer) = node.shader.as_ref().and_then(|s| s.layer.as_ref()) {
9039                    bindings.extend(
9040                        layer
9041                            .nodes
9042                            .iter()
9043                            .enumerate()
9044                            .map(|(i, &n)| (AnimationProp::CanvasArg(i as u16), n)),
9045                    );
9046                }
9047                if let Some(component) = &node.component {
9048                    bindings.extend(
9049                        component
9050                            .bound
9051                            .iter()
9052                            .map(|&(s, n)| (AnimationProp::ComponentSlot(s), n)),
9053                    );
9054                }
9055                if let Some(component) = &node.component
9056                    && component.slots_changed.replace(false)
9057                {
9058                    self.mount.push(MountItem::ComponentPropSlots {
9059                        id,
9060                        names: component.slots.clone(),
9061                    });
9062                }
9063                self.mount
9064                    .push(MountItem::AnimationBindings { id, bindings });
9065            }
9066            if flags & dirty::CANVAS != 0
9067                && let Some(drawing) = &node.drawing
9068            {
9069                if drawing.fit().is_some() {
9070                    // Its size comes with this round's layout.
9071                    self.fitted_pending.push(key);
9072                } else {
9073                    let drawing = self.mounted_drawing(key, drawing);
9074                    self.mount.push(MountItem::Canvas { id, drawing });
9075                }
9076            }
9077            if flags & dirty::SHADER != 0
9078                && let Some(shader) = &node.shader
9079            {
9080                self.mount.push(MountItem::Shader {
9081                    id,
9082                    layer: shader.layer.clone(),
9083                });
9084            }
9085            if flags & dirty::PAN != 0 {
9086                let mut values = node.gestures;
9087                if !node.pan_enabled {
9088                    values.pan_x = None;
9089                    values.pan_y = None;
9090                }
9091                self.mount.push(MountItem::Gestures { id, values });
9092            }
9093            if flags & dirty::VIEW_PROPS != 0 {
9094                self.mount.push(MountItem::ViewProps {
9095                    id,
9096                    props: node.mounted_props(),
9097                });
9098            } else if flags & dirty::LABEL != 0 {
9099                let label = node
9100                    .props
9101                    .as_ref()
9102                    .and_then(|p| p.accessibility.label.clone());
9103                self.mount.push(MountItem::AccessibilityLabel { id, label });
9104            }
9105            if flags & dirty::SCREEN != 0
9106                && let Some(config) = self.screen_config(key)
9107            {
9108                self.mount.push(MountItem::ScreenConfig {
9109                    id,
9110                    config: Box::new(config),
9111                });
9112            }
9113            if flags & dirty::COMPONENT != 0
9114                && self.nodes[key as usize].kind == Kind::Native
9115                && let Some(component) = self.nodes[key as usize].component.as_ref()
9116                && component.name.is_none()
9117            {
9118                log::warn!(target: "js", "a <native> element without `component`");
9119            }
9120            if flags & dirty::COMPONENT != 0
9121                && let Some(component) = self.nodes[key as usize].component.as_mut()
9122                && !component.changed.is_empty()
9123            {
9124                let changed = std::mem::take(&mut component.changed);
9125                let props: Vec<_> = changed
9126                    .into_iter()
9127                    // A bound prop's value waits until it is unbound.
9128                    .filter(|name| !component.is_bound(name))
9129                    .map(|name| {
9130                        let value = component
9131                            .props
9132                            .iter()
9133                            .find(|(k, _)| *k == name)
9134                            .map(|(_, v)| v.clone());
9135                        (name, value)
9136                    })
9137                    .collect();
9138                if !props.is_empty() {
9139                    self.mount.push(MountItem::ComponentProps { id, props });
9140                }
9141            }
9142            if flags & dirty::NATIVE != 0 && !self.web_unchecked.is_empty() {
9143                self.settle_web_urls(key);
9144            }
9145            let node = &self.nodes[key as usize];
9146            if flags & dirty::NATIVE != 0
9147                && let Some(control) = &node.control
9148            {
9149                self.mount.push(MountItem::NativeProps {
9150                    id,
9151                    props: (**control).clone(),
9152                });
9153            }
9154            if flags & dirty::MODAL != 0
9155                && let Some(root) = &node.root
9156            {
9157                let mut config = root.modal.clone();
9158                config.window = self.window_of(key);
9159                // A platform presents a dialog when it is inserted, over the
9160                // window its config names: a dialog inserted in this batch
9161                // (one that mounts in a window of the app's own already
9162                // open) gets its config ahead of its insertion.
9163                let item = MountItem::ModalConfig { id, config };
9164                match self
9165                    .mount
9166                    .iter()
9167                    .position(|m| matches!(m, MountItem::Insert { child, .. } if *child == id))
9168                {
9169                    Some(at) => self.mount.insert(at, item),
9170                    None => self.mount.push(item),
9171                }
9172            }
9173            if flags & dirty::NAV_SHADER != 0
9174                && let Some(root) = &node.root
9175            {
9176                let shader = root.nav_shader.clone();
9177                self.mount.push(MountItem::NavShader { id, shader });
9178            }
9179            if let Some(input) = &node.input {
9180                if flags & dirty::INPUT != 0 {
9181                    let mut config = input.config.clone();
9182                    config.accessory = config
9183                        .accessory_id
9184                        .as_deref()
9185                        .and_then(|name| self.accessories.get(name).copied());
9186                    // An explicit prop (Rust), then the style key, then
9187                    // the classes (`placeholder:text-*`, `caret-*`,
9188                    // `selection:bg-*`).
9189                    config.placeholder_color = config
9190                        .placeholder_color
9191                        .or(node.text_style.placeholder_color);
9192                    config.selection_color =
9193                        config.selection_color.or(node.text_style.selection_color);
9194                    let class = node.class_props.as_deref();
9195                    if let Some(c) = class {
9196                        config.placeholder_color = config.placeholder_color.or(c.placeholder_color);
9197                    }
9198                    config.selection_color =
9199                        config.selection_color.or(self.inherited_text_props(key).2);
9200                    config.caret_color = config
9201                        .caret_color
9202                        .or(node.text_style.caret_color)
9203                        .or(class.and_then(|c| c.caret_color));
9204                    config.style = scaled(
9205                        self.inherited_text_style(key).inherit(&node.text_style),
9206                        node.paragraph.font_multiplier(self.font_scale),
9207                    );
9208                    config.align = directed_align(
9209                        node.text_style.text_align.unwrap_or_default(),
9210                        node.rtl && !node.text_style.text_align_physical,
9211                    );
9212                    config.rtl = node.text_style.writing_direction.unwrap_or(node.rtl);
9213                    // A built-in bar takes the indicator's place.
9214                    config.scrollbar_visible =
9215                        input.scrollbar != crate::ScrollbarSetting::Hidden && input.bar.is_none();
9216                    config.report_scroll = input.bar.is_some() || input.watched;
9217                    self.mount.push(MountItem::Input {
9218                        id,
9219                        config: Box::new(config),
9220                    });
9221                }
9222                if flags & dirty::INPUT_VALUE != 0 {
9223                    self.mount.push(MountItem::InputValue {
9224                        id,
9225                        text: input.value.clone(),
9226                        count: input.count,
9227                    });
9228                }
9229            }
9230            if flags & dirty::TEXT_MOUNT != 0 {
9231                self.queue_text(key);
9232            }
9233        }
9234        queue.clear();
9235        // Keep the allocation (unless flushing queued more).
9236        if self.queue.is_empty() {
9237            self.queue = queue;
9238        }
9239    }
9240
9241    /// `onContentSizeChange` of input `key` if the size of its value (at the
9242    /// content box's width when multiline) changed. An empty input reports
9243    /// an empty line, as React Native does, though it is measured (sized)
9244    /// with its placeholder.
9245    fn report_content_size(&mut self, key: Key, width: f32) {
9246        let node = &self.nodes[key as usize];
9247        let (Some(input), Some(layout)) = (node.input.as_ref(), node.layout) else {
9248            return;
9249        };
9250        let max = input.config.multiline.then_some(width);
9251        let (placeholder, empty_line) = (input.placeholder_measured, input.empty_line);
9252        let Some(LeafContext::Text(cx)) = self.layout.get_node_context_mut(layout) else {
9253            return;
9254        };
9255        let size = if !placeholder {
9256            measure_text(&self.text_engine, &mut self.measure_cache, cx, max)
9257        } else if let Some((hash, size)) = empty_line
9258            && hash == cx.layout_hash
9259        {
9260            size
9261        } else {
9262            // Measured once per placeholder and style.
9263            let hash = cx.layout_hash;
9264            let mut empty = TextContext::new(Arc::new(self.input_text(key, "")));
9265            let size = measure_text(&self.text_engine, &mut self.measure_cache, &mut empty, max);
9266            let input = self.nodes[key as usize]
9267                .input
9268                .as_mut()
9269                .expect("input state");
9270            input.empty_line = Some((hash, size));
9271            size
9272        };
9273        let node = &mut self.nodes[key as usize];
9274        let input = node.input.as_mut().expect("input state");
9275        if input.content_size == Some(size) {
9276            return;
9277        }
9278        input.content_size = Some(size);
9279        let id = node.id;
9280        self.events.push(crate::element::JsEvent::Event(
9281            id,
9282            EventKind::ContentSizeChange,
9283            EventPayload::Map(vec![
9284                ("width", PayloadValue::Number(size.width.0 as f64)),
9285                ("height", PayloadValue::Number(size.height.0 as f64)),
9286            ]),
9287        ));
9288    }
9289
9290    fn text_cx(&mut self, layout: LayoutId) -> &mut TextContext<M::Prepared> {
9291        match self.layout.get_node_context_mut(layout) {
9292            Some(LeafContext::Text(cx)) => cx,
9293            _ => unreachable!("text block without text context"),
9294        }
9295    }
9296
9297    /// The text style `key` inherits from the views around it, as CSS
9298    /// does: `color` / `text-white` on a container styles the text in it
9299    /// (React Native views ignore text styles).
9300    /// The style text inherits at the root: React Native's defaults with
9301    /// the app's font.
9302    fn base_text_style(&self) -> ResolvedTextStyle {
9303        ResolvedTextStyle {
9304            font_family: self.default_font,
9305            ..ResolvedTextStyle::default()
9306        }
9307    }
9308
9309    /// A native component's `accentColor` style, passed to it as its
9310    /// `accentColor` prop (`#RRGGBBAA`; removed when unset): the system
9311    /// control shows its state in it, over the color its props give.
9312    fn sync_accent(&mut self, key: Key) {
9313        let node = &mut self.nodes[key as usize];
9314        let accent = node.view_style.accent_color;
9315        let Some(component) = node.component.as_mut() else {
9316            return;
9317        };
9318        let value = accent.map(|Color(c)| crate::JsonValue::from(format!("#{c:08X}")));
9319        let at = component
9320            .props
9321            .iter()
9322            .position(|(k, _)| &**k == ACCENT_PROP);
9323        if at.map(|i| &component.props[i].1) == value.as_ref() {
9324            return;
9325        }
9326        let name: Arc<str> = Arc::from(ACCENT_PROP);
9327        match (at, value) {
9328            (Some(i), Some(v)) => component.props[i].1 = v,
9329            (None, Some(v)) => component.props.push((name.clone(), v)),
9330            (Some(i), None) => {
9331                component.props.swap_remove(i);
9332            }
9333            (None, None) => return,
9334        }
9335        if !component.changed.contains(&name) {
9336            component.changed.push(name);
9337        }
9338        self.mark(key, dirty::COMPONENT);
9339    }
9340
9341    /// Texts and spans around `key` (it is inside an attachment) pass on
9342    /// their color only, as `currentColor` reaches the attachment's view:
9343    /// the attachment takes the color of the text it sits in, while its
9344    /// font and line height stay its own, which size the box its line
9345    /// makes room for.
9346    fn inherited_text_style(&self, key: Key) -> ResolvedTextStyle {
9347        let mut chain: Vec<Key> = Vec::new();
9348        let mut k = self.nodes[key as usize].parent;
9349        while k != NO_KEY {
9350            let node = &self.nodes[k as usize];
9351            let passes = if node.kind == Kind::Text {
9352                node.text_style.color.is_some()
9353            } else {
9354                node.text_style != TextStyle::default()
9355            };
9356            if passes {
9357                chain.push(k);
9358            }
9359            k = node.parent;
9360        }
9361        chain
9362            .iter()
9363            .rev()
9364            .fold(self.base_text_style(), |style, &k| {
9365                let node = &self.nodes[k as usize];
9366                if node.kind == Kind::Text {
9367                    ResolvedTextStyle {
9368                        color: node.text_style.color.unwrap_or(style.color),
9369                        ..style
9370                    }
9371                } else {
9372                    style.inherit(&node.text_style)
9373                }
9374            })
9375    }
9376
9377    /// What the classes of `key`, else of the nearest view around it that
9378    /// says, set for its lines' wrapping, its selection and the
9379    /// selection's highlight: `whitespace-*` and `select-*` inherit, as
9380    /// CSS's `white-space` and `user-select: auto` do, and `selection:bg-*`
9381    /// reaches the texts inside (Tailwind's `& *::selection`), as a view's
9382    /// own color does (Rust's `Element::selection_color`, over its
9383    /// classes'). One walk up.
9384    fn inherited_text_props(&self, key: Key) -> (Option<bool>, Option<bool>, Option<Color>) {
9385        let (no_wrap, selectable, highlight, _) = self.inherited_text_wrap(key);
9386        (no_wrap, selectable, highlight)
9387    }
9388
9389    /// [`Core::inherited_text_props`] and whether its lines wrap
9390    /// `text-pretty`, which inherits with `white-space` (the same classes
9391    /// set both).
9392    fn inherited_text_wrap(&self, key: Key) -> (Option<bool>, Option<bool>, Option<Color>, bool) {
9393        let (mut no_wrap, mut selectable, mut highlight) = (None, None, None);
9394        let mut pretty = None;
9395        let mut k = key;
9396        while k != NO_KEY && (no_wrap.is_none() || selectable.is_none() || highlight.is_none()) {
9397            let node = &self.nodes[k as usize];
9398            if !matches!(node.kind, Kind::Text | Kind::Input) {
9399                highlight = highlight.or(node.paragraph.selection_color);
9400            }
9401            if let Some(c) = node.class_props.as_deref() {
9402                if no_wrap.is_none() && c.no_wrap.is_some() {
9403                    pretty = Some(c.pretty);
9404                }
9405                no_wrap = no_wrap.or(c.no_wrap);
9406                selectable = selectable.or(c.selectable);
9407                highlight = highlight.or(c.selection_color);
9408            }
9409            k = node.parent;
9410        }
9411        (no_wrap, selectable, highlight, pretty.unwrap_or(false))
9412    }
9413
9414    /// The nearest `textAlign` set on a view around `key`.
9415    fn inherited_text_align(&self, key: Key) -> Option<(TextAlign, bool)> {
9416        let mut k = self.nodes[key as usize].parent;
9417        while k != NO_KEY {
9418            let node = &self.nodes[k as usize];
9419            if let Some(a) = node.text_style.text_align {
9420                return Some((a, node.text_style.text_align_physical));
9421            }
9422            k = node.parent;
9423        }
9424        None
9425    }
9426
9427    /// `textIndent` in effect for `key`: the nearest node that sets it,
9428    /// with an `em` value resolved against that node's font size (an
9429    /// inherited length does not grow with a child's font, as in CSS).
9430    fn inherited_text_indent(&self, key: Key) -> Option<Points> {
9431        let mut k = key;
9432        while k != NO_KEY {
9433            let style = &self.nodes[k as usize].text_style;
9434            // A node sets one of the two (`textIndent` clears the other).
9435            if let Some(em) = style.text_indent_em {
9436                return Some(Points(self.font_size_at(k) * em));
9437            }
9438            if let Some(points) = style.text_indent {
9439                return Some(points);
9440            }
9441            k = self.nodes[k as usize].parent;
9442        }
9443        None
9444    }
9445
9446    /// The font size `key` resolves to: its own (`fontSize`, an `em` or a
9447    /// percentage of the inherited one), else the one it inherits.
9448    fn font_size_at(&self, key: Key) -> f32 {
9449        let mut em = 1.0f32;
9450        let mut k = key;
9451        loop {
9452            let style = &self.nodes[k as usize].text_style;
9453            if let Some(scale) = style.font_size_em {
9454                em *= scale;
9455            } else if let Some(size) = style.font_size {
9456                return size.0 * em;
9457            }
9458            let parent = self.nodes[k as usize].parent;
9459            if parent == NO_KEY {
9460                return self.base_text_style().font_size.0 * em;
9461            }
9462            k = parent;
9463        }
9464    }
9465
9466    /// Text blocks and inputs inside `key` inherit its new text style.
9467    fn mark_inheriting_text(&mut self, key: Key) {
9468        self.ch_changed(key);
9469        let mut stack: Vec<Key> = self.nodes[key as usize].children.clone();
9470        while let Some(k) = stack.pop() {
9471            match self.nodes[k as usize].kind {
9472                // The texts inside its attachments inherit too.
9473                Kind::Text => {
9474                    if !self.nodes[k as usize].inline {
9475                        self.mark_text_block(k);
9476                    }
9477                    stack.extend_from_slice(&self.nodes[k as usize].children);
9478                }
9479                Kind::Input => {
9480                    self.measure_input(k);
9481                    self.mark(k, dirty::INPUT);
9482                }
9483                Kind::RawText => {}
9484                _ => stack.extend_from_slice(&self.nodes[k as usize].children),
9485            }
9486        }
9487    }
9488
9489    /// Rebuilds the attributed text of a block. Returns true if it changed.
9490    ///
9491    /// Only layout-relevant changes invalidate measurement and layout; a
9492    /// color change keeps both and just needs a new final layout.
9493    fn rebuild_text(&mut self, key: Key) -> bool {
9494        // Far down a scroll view's content, with no view yet: estimated
9495        // until it comes near (`cull.rs`).
9496        let deferred = !self.nodes[key as usize].created && self.cull_scope(key).is_some();
9497        let node = &self.nodes[key as usize];
9498        // Its own style's and classes' (`numberOfLines`, `textOverflow`).
9499        let class = node.class_props.as_deref();
9500        let max_lines = class.and_then(|c| c.number_of_lines).unwrap_or(0);
9501        let ellipsize = class.and_then(|c| c.ellipsize).unwrap_or_default();
9502        let inherited = self.inherited_text_style(key);
9503        let (no_wrap, selectable, highlight, pretty) = self.inherited_text_wrap(key);
9504        let (align, physical) = node
9505            .text_style
9506            .text_align
9507            .map(|align| (align, node.text_style.text_align_physical))
9508            .or_else(|| self.inherited_text_align(key))
9509            .unwrap_or_default();
9510        let base = inherited.inherit(&node.text_style);
9511        let mut text = AttributedText {
9512            paragraph_strut: Some(base),
9513            align: directed_align(align, node.rtl && !physical),
9514            writing_direction: node.text_style.writing_direction,
9515            rtl: node.rtl,
9516            max_lines,
9517            ellipsize,
9518            // A line clamp already keeps lines from wrapping past it, and
9519            // must ellipsize at the box (`truncate`).
9520            no_wrap: max_lines == 0 && no_wrap.unwrap_or(false),
9521            shadow: node.text_style.shadow(),
9522            selectable,
9523            selection_color: node
9524                .paragraph
9525                .selection_color
9526                .or(node.text_style.selection_color)
9527                .or(highlight),
9528            ..AttributedText::default()
9529        };
9530        let multiplier = node.paragraph.font_multiplier(self.font_scale);
9531        let options = crate::TextOptions::default().indent(
9532            self.inherited_text_indent(key)
9533                .map(|indent| indent * multiplier),
9534        );
9535        let inserted = self.update_attachments(key);
9536        let baselines = self.attachment_baselines(key);
9537        let mut parts = TextAttachments {
9538            alignments: crate::AttachmentAlignments::default(),
9539            spacers: Vec::new(),
9540            baselines: &baselines,
9541            next_baseline: 0,
9542        };
9543        self.collect_text(key, base, &mut text, &mut parts, false);
9544        let TextAttachments {
9545            alignments,
9546            spacers,
9547            ..
9548        } = parts;
9549        self.hide_attachments(key, false);
9550        if multiplier != 1.0 {
9551            if let Some(strut) = &mut text.paragraph_strut {
9552                *strut = scaled(*strut, multiplier);
9553            }
9554            for span in &mut text.spans {
9555                span.style = scaled(span.style, multiplier);
9556            }
9557        }
9558        let layout = self.nodes[key as usize]
9559            .layout
9560            .expect("text block has layout");
9561        let colors_at_draw = self.text_engine.draws_colors_from_text();
9562        let cx = self.text_cx(layout);
9563        cx.deferred = deferred;
9564        cx.spacers = spacers;
9565        let pretty_changed = cx.pretty.is_some() != pretty;
9566        if pretty_changed {
9567            cx.pretty = pretty.then(|| Box::new((f32::NAN, Points::ZERO)));
9568            cx.laid_out = None;
9569        }
9570        if *cx.text == text && cx.alignments == alignments && cx.options == options {
9571            if inserted {
9572                // New attachment views: placed with the next final layout.
9573                cx.laid_out = None;
9574            }
9575            return inserted || pretty_changed;
9576        }
9577        if !cx.text.metadata_eq(&text)
9578            && !inserted
9579            && cx.alignments == alignments
9580            && cx.options == options
9581            && cx.text.rendering_eq(&text)
9582        {
9583            cx.text = Arc::new(text);
9584            cx.metadata_changed = true;
9585            return true;
9586        }
9587        // Only colors or hidden runs changed, and the platform draws them
9588        // from the text: its typesetting, measurements and final layout all
9589        // stand; the new text is mounted with the layout drawn (a fitted
9590        // text has a layout of its own text, made again).
9591        if !inserted
9592            && cx.alignments == alignments
9593            && cx.options == options
9594            && colors_at_draw
9595            && cx
9596                .laid_out
9597                .as_ref()
9598                .is_none_or(|l| Arc::ptr_eq(&l.text, &cx.text))
9599            && cx.text.same_but_colors(&text)
9600        {
9601            let text = Arc::new(text);
9602            if let Some(laid) = &mut cx.laid_out {
9603                laid.text = text.clone();
9604            }
9605            cx.text = text;
9606            cx.metadata_changed = true;
9607            return true;
9608        }
9609        cx.metadata_changed = false;
9610        let same_layout =
9611            cx.text.layout_eq(&text) && cx.alignments == alignments && cx.options == options;
9612        cx.alignments = alignments;
9613        cx.options = options;
9614        cx.text = Arc::new(text);
9615        // Platform typesetting state embeds colors too (unless it draws
9616        // them from the text, above): rebuild it.
9617        cx.prepared = None;
9618        cx.min_content = None;
9619        cx.laid_out = None;
9620        if let Some(p) = &mut cx.pretty {
9621            p.0 = f32::NAN;
9622        }
9623        if !same_layout {
9624            cx.layout_hash = text_layout_hash(&cx.alignments, &cx.text, &cx.options);
9625            cx.cache = None;
9626            cx.baseline = None;
9627            cx.same_lines = None;
9628            cx.no_ahead = false;
9629            // A text that measures as before leaves every layout standing:
9630            // only the text is mounted again. Attachments are placed by its
9631            // final layout, laid out again with the rest.
9632            let attachments =
9633                !cx.alignments.is_empty() || !self.nodes[key as usize].attached.is_empty();
9634            let measure = leaf_measure(&self.text_engine, &mut self.measure_cache);
9635            // A text sized by its style never resizes its box: no need to
9636            // typeset it to know.
9637            if attachments
9638                || !(self.layout.sized_by_style(layout)
9639                    || self.layout.measures_as_before(layout, measure))
9640            {
9641                self.layout.mark_dirty(layout);
9642                self.needs_layout = true;
9643            }
9644        }
9645        true
9646    }
9647
9648    /// The text of `key`'s children into `out`, what it learns of their
9649    /// attachments into `parts`; `in_press`: inside a span taking presses.
9650    fn collect_text(
9651        &self,
9652        key: Key,
9653        style: ResolvedTextStyle,
9654        out: &mut AttributedText,
9655        parts: &mut TextAttachments<'_>,
9656        in_press: bool,
9657    ) {
9658        if let Some(text) = self.folded_text(key) {
9659            out.push(text, style);
9660        }
9661        for &c in &self.nodes[key as usize].children {
9662            let child = &self.nodes[c as usize];
9663            if child.is_overlay() {
9664                continue;
9665            }
9666            match child.kind {
9667                Kind::RawText => out.push(&child.text, style),
9668                Kind::Text => {
9669                    let start = out.len_utf16();
9670                    let mut inner = style.inherit(&child.text_style);
9671                    if let Some(mut b) = span_background(&child.view_style, child.id) {
9672                        (b.top, b.bottom) = span_vertical_padding(child);
9673                        inner.background = Some(b);
9674                    }
9675                    // `visibility: "hidden"` on a span hides its characters,
9676                    // and those of the spans inside it, where they stand.
9677                    if inner.hidden || child.view_style.hidden {
9678                        inner = inner.hide();
9679                    }
9680                    let press = pressable(child.events);
9681                    let hinted = child.overlay_watched & overlay::watch::HINT != 0;
9682                    // Read from the classes, not `tracked`, which may be
9683                    // updated after this merge in the same commit.
9684                    let tracked = child.classes.as_ref().map_or(0, |c| c.tracked_states());
9685                    let hovers = tracked & crate::tailwind::state::HOVERED != 0;
9686                    // Horizontal padding takes room in the line, as a CSS
9687                    // inline box's does: an empty attachment at each end in
9688                    // the span's style, so its background spans it too.
9689                    let (first, last) = span_padding(child, out.rtl);
9690                    let pad = |out: &mut AttributedText, spacers: &mut Vec<u32>, w: f32| {
9691                        if w > 0.0 {
9692                            spacers.push(out.len_utf16());
9693                            out.push_attachment(crate::geometry::size_pt(w, 0.0), inner);
9694                        }
9695                    };
9696                    pad(out, &mut parts.spacers, first);
9697                    self.collect_text(c, inner, out, parts, in_press || press);
9698                    pad(out, &mut parts.spacers, last);
9699                    // A link with a hint (its URL) hears the pointer come
9700                    // over its characters and leave them. A span that takes
9701                    // no presses (a `RichEditor`'s link mark: the editor's
9702                    // touches place the caret and open it) is one only for
9703                    // its hint: no press, no stop of Tab. Inside a span that
9704                    // takes presses it is none, so that span, the innermost
9705                    // link there, keeps the press of those characters.
9706                    // Hidden characters take no presses, as CSS's hidden
9707                    // elements take no pointer events. A span with
9708                    // `hover:` / `active:` styles hears the pointer and
9709                    // its presses the same way: it has no view to report
9710                    // its states, `Self::span_state` takes them from these.
9711                    if !inner.hidden && (press || ((hinted || hovers) && !in_press)) {
9712                        let mut events = child.events;
9713                        if hinted || hovers {
9714                            events.set(EventKind::MouseEnter, true);
9715                            events.set(EventKind::MouseLeave, true);
9716                        }
9717                        if press && tracked & crate::tailwind::state::PRESSED != 0 {
9718                            events.set(EventKind::PressDown, true);
9719                            events.set(EventKind::PressUp, true);
9720                        }
9721                        // Where it goes (`TextView`'s links), for platforms
9722                        // that make it a hyperlink (the web's `<a href>`).
9723                        if let Some(href) = child.props.as_ref().and_then(|p| p.href.clone()) {
9724                            out.link_hrefs
9725                                .push(crate::text::LinkHref::new(out.links.len() as u32, href));
9726                        }
9727                        out.links.push(crate::text::TextLink {
9728                            start,
9729                            end: out.len_utf16(),
9730                            node: child.id,
9731                            events,
9732                            focus_stop: press
9733                                && child.props.as_ref().is_none_or(|p| p.focus_stop(true)),
9734                        });
9735                    }
9736                    if let Some(test_id) = child.props.as_ref().and_then(|p| p.test_id.clone()) {
9737                        out.test_ids.push(crate::text::SpanTestId {
9738                            start,
9739                            end: out.len_utf16(),
9740                            test_id,
9741                        });
9742                    }
9743                }
9744                // Placed in its root view, not in the text.
9745                Kind::Overlay => {}
9746                // An attachment, laid out by `update_attachments`.
9747                _ => {
9748                    if let Some(l) = child.layout {
9749                        let size = self.rounded_layout(l).size;
9750                        // The baselines are in the attachments' order: the
9751                        // next one is this attachment's, or a later one's.
9752                        if let Some(&(_, baseline)) = parts
9753                            .baselines
9754                            .get(parts.next_baseline)
9755                            .filter(|b| b.0 == c)
9756                        {
9757                            parts.next_baseline += 1;
9758                            parts
9759                                .alignments
9760                                .set_baseline(out.len_utf16(), Some(baseline));
9761                        }
9762                        if let Some(copy) = self.attachment_copy_text(c) {
9763                            out.copy_texts.push(crate::text::AttachmentCopyText::new(
9764                                out.len_utf16(),
9765                                copy.clone(),
9766                            ));
9767                        }
9768                        parts.alignments.push(
9769                            out,
9770                            crate::geometry::size_pt(size.width, size.height),
9771                            self.attachment_align(c),
9772                            style,
9773                        );
9774                    }
9775                }
9776            }
9777        }
9778    }
9779
9780    /// Where attachment `key` sits in its line (`verticalAlign`). A
9781    /// placeholder of a render (`renderCustom`, ...) that sets none takes
9782    /// what its content sets: the placeholder and JS's holder around the
9783    /// content are not the app's views, so the app styles only the content
9784    /// (`<View style={{ verticalAlign: "middle" }}>` in `renderCustom`).
9785    fn attachment_align(&self, key: Key) -> crate::style::VerticalAlign {
9786        use crate::style::VerticalAlign;
9787        let node = &self.nodes[key as usize];
9788        if node.vertical_align != VerticalAlign::Baseline
9789            || !self.components.renders.is_place(node.id)
9790        {
9791            return node.vertical_align;
9792        }
9793        self.render_content(key)
9794            .map_or(VerticalAlign::Baseline, |content| {
9795                self.nodes[content as usize].vertical_align
9796            })
9797    }
9798
9799    /// What a copy gives in place of attachment `key` (`copyText`): its
9800    /// own, or for a placeholder of a render (`renderCustom`, ...) that
9801    /// sets none its content's, as [`Self::attachment_align`] reads the
9802    /// content's alignment. An empty one copies as nothing, as unset.
9803    fn attachment_copy_text(&self, key: Key) -> Option<&Arc<str>> {
9804        let node = &self.nodes[key as usize];
9805        let copy = match &node.copy_text {
9806            Some(copy) => Some(copy),
9807            None if self.components.renders.is_place(node.id) => self
9808                .render_content(key)
9809                .and_then(|content| self.nodes[content as usize].copy_text.as_ref()),
9810            None => None,
9811        };
9812        copy.filter(|c| !c.is_empty())
9813    }
9814
9815    /// The content of render placeholder `key`: the placeholder's only
9816    /// child is the holder; the holder's, the content.
9817    fn render_content(&self, key: Key) -> Option<Key> {
9818        let mut key = key;
9819        for _ in 0..2 {
9820            let mut children = self.nodes[key as usize]
9821                .children
9822                .iter()
9823                .filter(|&&c| !self.nodes[c as usize].is_overlay());
9824            match (children.next(), children.next()) {
9825                (Some(&only), None) => key = only,
9826                _ => return None,
9827            }
9828        }
9829        Some(key)
9830    }
9831
9832    /// The attachments of text block `key` that stand on the baseline by
9833    /// a baseline of their own, with how far below their top it is: the
9834    /// first line's of the first text in each, laid out by
9835    /// [`Core::update_attachments`], as CSS stands an `inline-block` or
9836    /// `inline-flex` box on the baseline of its first line box. One with
9837    /// no text in it (an image, a box), or whose engine knows no
9838    /// baselines, stands on its bottom edge, as a replaced box.
9839    fn attachment_baselines(&mut self, key: Key) -> Vec<(Key, Points)> {
9840        let mut keys = Vec::new();
9841        self.attachments_of(key, &mut keys);
9842        keys.retain(|&a| self.attachment_align(a) == crate::style::VerticalAlign::Baseline);
9843        keys.into_iter()
9844            .filter_map(|a| Some((a, self.first_text_baseline(a, true)?)))
9845            .collect()
9846    }
9847
9848    /// How far below `key`'s top the baseline of the first line of text
9849    /// in it is (`root`: `key` is the box asked about, else its place in
9850    /// its parent counts too); none without a text.
9851    fn first_text_baseline(&mut self, key: Key, root: bool) -> Option<Points> {
9852        let node = &self.nodes[key as usize];
9853        if node.is_overlay() {
9854            return None;
9855        }
9856        let layout = node.layout?;
9857        // Only what takes part in the box's flow has its baseline: not a
9858        // `display: none` subtree, which has no box (CSS Display), nor an
9859        // absolutely positioned one, out of the flow.
9860        if !root
9861            && (self.layout.displays_none(layout)
9862                || self.layout.style(layout).position == Position::Absolute)
9863        {
9864            return None;
9865        }
9866        let text = node.kind == Kind::Text;
9867        let l = *self.layout.unrounded_layout(layout);
9868        let top = if root { 0.0 } else { l.location.y };
9869        if text {
9870            let width =
9871                l.size.width - l.padding.left - l.padding.right - l.border.left - l.border.right;
9872            let engine = &self.text_engine;
9873            let Some(LeafContext::Text(cx)) = self.layout.get_node_context_mut(layout) else {
9874                return None;
9875            };
9876            let baseline = text_baseline(engine, cx, width.max(0.0))?;
9877            return Some(Points(top + l.border.top + l.padding.top) + baseline);
9878        }
9879        let children = self.nodes[key as usize].children.clone();
9880        children
9881            .into_iter()
9882            .find_map(|c| self.first_text_baseline(c, false))
9883            .map(|inner| Points(top) + inner)
9884    }
9885
9886    /// The render placeholder in a text that view `key` is the content of
9887    /// (see [`Core::attachment_align`]), if it is one.
9888    fn placed_in_text(&self, key: Key) -> Option<Key> {
9889        let holder = self.nodes[key as usize].parent;
9890        if holder == NO_KEY || !self.is_render_holder(self.nodes[holder as usize].id) {
9891            return None;
9892        }
9893        let place = self.nodes[holder as usize].parent;
9894        (place != NO_KEY && self.nodes[place as usize].inline).then_some(place)
9895    }
9896
9897    /// The attachments of text block `key` (views and images inside it,
9898    /// also inside its spans), in text order.
9899    fn attachments_of(&self, key: Key, out: &mut Vec<Key>) {
9900        for &c in &self.nodes[key as usize].children {
9901            let child = &self.nodes[c as usize];
9902            if child.is_overlay() {
9903                continue;
9904            }
9905            match child.kind {
9906                Kind::RawText | Kind::Overlay => {}
9907                Kind::Text => self.attachments_of(c, out),
9908                _ if child.layout.is_some() => out.push(c),
9909                _ => {}
9910            }
9911        }
9912    }
9913
9914    /// The text block an attachment is in, if it is one.
9915    fn attachment_block(&self, key: Key) -> Option<Key> {
9916        let node = &self.nodes[key as usize];
9917        if !node.inline || node.layout.is_none() || node.kind == Kind::Text {
9918            return None;
9919        }
9920        let mut k = node.parent;
9921        while k != NO_KEY {
9922            let n = &self.nodes[k as usize];
9923            if !n.inline {
9924                return (n.kind == Kind::Text).then_some(k);
9925            }
9926            k = n.parent;
9927        }
9928        None
9929    }
9930
9931    /// Lays out the attachments of text block `key` (each a layout root
9932    /// at its own content size) and keeps their native views inside the
9933    /// block's. Returns true if views were inserted (they need placing).
9934    fn update_attachments(&mut self, key: Key) -> bool {
9935        let mut keys = Vec::new();
9936        self.attachments_of(key, &mut keys);
9937        let block = &self.nodes[key as usize];
9938        if keys.is_empty() && block.attached.is_empty() {
9939            return false;
9940        }
9941        let (block_id, created) = (block.id, block.created);
9942        let old = std::mem::take(&mut self.nodes[key as usize].attached);
9943        let mut inserted = false;
9944        for &a in &keys {
9945            let id = self.nodes[a as usize].id;
9946            let new = !old.contains(&id);
9947            if created && new {
9948                self.ensure_created(a);
9949                self.mount.push(MountItem::Insert {
9950                    parent: block_id,
9951                    child: id,
9952                    before: None,
9953                });
9954                inserted = true;
9955            }
9956            let layout = self.nodes[a as usize].layout.expect("attachment layout");
9957            let dirty = self.layout.dirty(layout);
9958            if dirty {
9959                self.layout_root(
9960                    layout,
9961                    taffy::Size {
9962                        width: AvailableSpace::MaxContent,
9963                        height: AvailableSpace::MaxContent,
9964                    },
9965                );
9966            }
9967            if created && (dirty || new) {
9968                // Its own frame follows the text; its subtree's now.
9969                let children = std::mem::take(&mut self.nodes[a as usize].children);
9970                for &child in &children {
9971                    self.emit_frames(child);
9972                }
9973                self.nodes[a as usize].children = children;
9974            }
9975        }
9976        // Views that left the block and were not moved natively elsewhere.
9977        for id in old {
9978            let Ok(k) = self.key(id) else { continue };
9979            let n = &self.nodes[k as usize];
9980            let moved = n.parent != NO_KEY && !n.inline && self.nodes[n.parent as usize].created;
9981            if n.created && !moved && self.attachment_block(k).is_none() {
9982                self.mount.push(MountItem::Remove { id });
9983            }
9984        }
9985        let ids: Vec<NodeId> = keys.iter().map(|&a| self.nodes[a as usize].id).collect();
9986        let has = !ids.is_empty();
9987        self.nodes[key as usize].attached = if created { ids } else { Vec::new() };
9988        match (has, self.attachment_blocks.contains(&key)) {
9989            (true, false) => self.attachment_blocks.push(key),
9990            (false, true) => self.attachment_blocks.retain(|&k| k != key),
9991            _ => {}
9992        }
9993        inserted
9994    }
9995
9996    /// Text blocks whose attachments' content changed are built again.
9997    fn check_attachments(&mut self) {
9998        let mut i = 0;
9999        while i < self.attachment_blocks.len() {
10000            let key = self.attachment_blocks[i];
10001            i += 1;
10002            let Some(node) = self.nodes.get(key as usize) else {
10003                continue;
10004            };
10005            let dirty = node.attached.iter().any(|&id| {
10006                self.key(id).is_ok_and(|k| {
10007                    self.nodes[k as usize]
10008                        .layout
10009                        .is_some_and(|l| self.layout.dirty(l))
10010                })
10011            });
10012            if dirty {
10013                self.mark(key, dirty::TEXT_BUILD);
10014            }
10015        }
10016    }
10017
10018    /// Where the layout of the node around `layout` is in its layout root
10019    /// (the sum of the unrounded locations above it), as Taffy's rounding
10020    /// carries it down: added from the root down, in Taffy's order, so the
10021    /// sum is the same to the last bit of an `f32` (an edge at x.5 rounds
10022    /// one way or the other on it).
10023    fn positioning_parent(&self, layout: LayoutId) -> Option<LayoutId> {
10024        let mut parent = self.layout.parent(layout)?;
10025        match self.layout.style(layout).position {
10026            Position::Absolute => {
10027                while !self.layout.style(parent).position.is_positioned() {
10028                    let Some(above) = self.layout.parent(parent) else {
10029                        break;
10030                    };
10031                    parent = above;
10032                }
10033            }
10034            Position::Fixed => {
10035                while let Some(above) = self.layout.parent(parent) {
10036                    parent = above;
10037                }
10038            }
10039            _ => {}
10040        }
10041        Some(parent)
10042    }
10043
10044    fn layout_origin(&self, layout: LayoutId) -> taffy::Point<f32> {
10045        let mut above = Vec::new();
10046        let mut at = self.positioning_parent(layout);
10047        while let Some(node) = at {
10048            above.push(node);
10049            at = self.positioning_parent(node);
10050        }
10051        above
10052            .iter()
10053            .rev()
10054            .fold(taffy::Point::ZERO, |origin, &node| {
10055                let l = self.layout.unrounded_layout(node);
10056                taffy::Point {
10057                    x: origin.x + l.location.x,
10058                    y: origin.y + l.location.y,
10059                }
10060            })
10061    }
10062
10063    /// `layout`'s layout, rounded to the surface's device pixels as Taffy's
10064    /// rounding pass rounds to whole points ([`rounded`]); on a grid
10065    /// surface, to its whole Cells.
10066    fn rounded_layout(&self, layout: LayoutId) -> taffy::Layout {
10067        rounded(
10068            self.layout.unrounded_layout(layout),
10069            self.containing_origin(layout),
10070            self.frame_ratio(),
10071        )
10072    }
10073
10074    /// The [`Origin`] of the box `layout` is placed in: the node around
10075    /// it, or its containing block ([`Core::positioning_parent`]).
10076    fn containing_origin(&self, layout: LayoutId) -> Origin {
10077        self.positioning_parent(layout)
10078            .map_or(Origin::default(), |parent| self.box_origin(parent))
10079    }
10080
10081    /// `layout`'s own box as the [`Origin`] of the nodes placed in it.
10082    fn box_origin(&self, layout: LayoutId) -> Origin {
10083        let origin = self.layout_origin(layout);
10084        let l = self.layout.unrounded_layout(layout);
10085        Origin::of(
10086            taffy::Point {
10087                x: origin.x + l.location.x,
10088                y: origin.y + l.location.y,
10089            },
10090            l.size,
10091            self.frame_ratio(),
10092        )
10093    }
10094
10095    /// What frames are rounded to, per axis, in "pixels" per point: the
10096    /// surface's device pixels, or on a grid surface its Cells (one Cell a
10097    /// pixel: [`terminal_layout::Grid::ratio`]).
10098    fn frame_ratio(&self) -> taffy::Size<f32> {
10099        match self.layout.grid() {
10100            Some(grid) => grid.ratio(),
10101            None => {
10102                let ratio = self.pixel_ratio();
10103                taffy::Size {
10104                    width: ratio,
10105                    height: ratio,
10106                }
10107            }
10108        }
10109    }
10110
10111    /// The surface's Cell size is now `cell` (`None`: it is no grid):
10112    /// styles are put on the grid, or taken off it, and everything is laid
10113    /// out again ([`grid`]).
10114    fn cell_changed(&mut self, cell: Option<Size<Points>>, dark: bool) {
10115        let grid = cell
10116            .and_then(terminal_layout::Grid::new)
10117            .map(|g| g.with_page(dark));
10118        let cell = grid.map(|g| Size::new(Points(g.width), Points(g.height)));
10119        if self.measure_cache.set_cell(cell) {
10120            self.fonts_changed();
10121        }
10122        if self.layout.set_grid(grid) {
10123            self.needs_layout = true;
10124        }
10125    }
10126
10127    /// The device pixels per point layouts and text measurements are rounded
10128    /// to: the environment's pixel ratio ([`MeasureCache::pixel_ratio`]).
10129    fn pixel_ratio(&self) -> f32 {
10130        self.measure_cache.pixel_ratio()
10131    }
10132
10133    /// The surface's pixel ratio is now `ratio`: frames are rounded to its
10134    /// device pixels and text is measured in them, so a new ratio measures
10135    /// text again and sends every frame that moves.
10136    fn pixel_ratio_changed(&mut self, ratio: f32) {
10137        if !self.measure_cache.set_pixel_ratio(ratio) {
10138            return;
10139        }
10140        self.fonts_changed();
10141        let layouts: Vec<LayoutId> = self
10142            .nodes
10143            .iter()
10144            .filter(|(_, n)| n.created)
10145            .filter_map(|(_, n)| n.layout)
10146            .collect();
10147        for layout in layouts {
10148            self.layout.mark_dirty(layout);
10149        }
10150        self.needs_layout = true;
10151    }
10152
10153    /// Lays out the main tree if it changed. Returns true if it did.
10154    fn layout_main(&mut self) -> bool {
10155        let root = self.nodes[self.root as usize].layout.expect("root layout");
10156        let available = taffy::Size {
10157            width: AvailableSpace::Definite(self.viewport.width.0),
10158            height: AvailableSpace::Definite(self.viewport.height.0),
10159        };
10160        // A clean root has nothing new to lay out, nor frames to emit.
10161        let main = self.layout.dirty(root);
10162        if main {
10163            // A main window that fits its content: laid out at its
10164            // content's size on those sides ([`Core::fit_window`]).
10165            let (fitting, fitted) = self
10166                .windows
10167                .get(&crate::ROOT_ID)
10168                .map_or(((false, false), false), |r| (r.fits(), r.fitted.is_some()));
10169            let mut available = available;
10170            if fitting != (false, false) || fitted {
10171                let mut style = root_style(self.viewport);
10172                if fitting.0 {
10173                    available.width = AvailableSpace::MaxContent;
10174                    style.size.width = taffy::Dimension::auto();
10175                }
10176                if fitting.1 {
10177                    available.height = AvailableSpace::MaxContent;
10178                    style.size.height = taffy::Dimension::auto();
10179                }
10180                self.layout.set_style(root, style);
10181            }
10182            self.layout_root(root, available);
10183            self.fit_window(self.root, root);
10184        }
10185        main
10186    }
10187
10188    /// Lays out screens, modals and header items whose size or content
10189    /// changed, outer ones first (a stack may live in a modal), and emits
10190    /// their frames.
10191    fn layout_roots(&mut self) {
10192        if self.roots.is_empty() {
10193            return;
10194        }
10195        let mut order: Vec<(u32, Key)> = self
10196            .roots
10197            .iter()
10198            .filter(|&&k| {
10199                let n = &self.nodes[k as usize];
10200                n.created
10201                    && n.parent != NO_KEY
10202                    && (!n.is_overlay() || self.overlay(k).is_some_and(|s| s.host.is_some()))
10203            })
10204            .map(|&k| (self.root_depth(k), k))
10205            .collect();
10206        order.sort_unstable();
10207        for (_, key) in order {
10208            self.layout_detached(key);
10209        }
10210    }
10211
10212    /// Input accessory `key` was attached to the tree (or detached): the
10213    /// inputs that name it are configured again.
10214    fn accessory_attached(&mut self, key: Key, attached: bool) {
10215        let node = &self.nodes[key as usize];
10216        let Some(name) = node.root.as_ref().and_then(|r| r.native_id.clone()) else {
10217            return;
10218        };
10219        let id = node.id;
10220        if attached {
10221            self.accessories.insert(name.clone(), id);
10222        } else if self.accessories.get(&name) == Some(&id) {
10223            self.accessories.remove(&name);
10224        } else {
10225            return;
10226        }
10227        let inputs: Vec<Key> = self
10228            .nodes
10229            .iter()
10230            .filter(|(_, n)| {
10231                n.input
10232                    .as_ref()
10233                    .is_some_and(|i| i.config.accessory_id.as_deref() == Some(&*name))
10234            })
10235            .map(|(k, _)| k as Key)
10236            .collect();
10237        for k in inputs {
10238            self.mark(k, dirty::INPUT);
10239        }
10240    }
10241
10242    /// Number of screens / modals / header items above `key`.
10243    fn root_depth(&self, mut key: Key) -> u32 {
10244        let mut depth = 0;
10245        key = self.nodes[key as usize].parent;
10246        while key != NO_KEY {
10247            let n = &self.nodes[key as usize];
10248            if n.is_layout_root() {
10249                depth += 1;
10250            }
10251            key = n.parent;
10252        }
10253        depth
10254    }
10255
10256    /// How far the system UI at the top (status bar) reaches into `key`:
10257    /// its root's top inset minus its offset in that root.
10258    fn top_overlap(&self, key: Key) -> f32 {
10259        let mut y = 0.0;
10260        let mut k = key;
10261        loop {
10262            let n = &self.nodes[k as usize];
10263            if k == self.root {
10264                return (self.safe_area.top.0 - y).max(0.0);
10265            }
10266            if n.is_layout_root() {
10267                let inset = match n.kind {
10268                    Kind::Modal => n.root.as_ref().map_or(0.0, |r| r.insets.top.0),
10269                    _ => 0.0,
10270                };
10271                return (inset - y).max(0.0);
10272            }
10273            if !n.frame.origin.y.0.is_nan() {
10274                y += n.frame.origin.y.0;
10275            }
10276            if n.parent == NO_KEY {
10277                return 0.0;
10278            }
10279            k = n.parent;
10280        }
10281    }
10282
10283    /// The platform draws a header of its own above screens (iOS,
10284    /// Android); without one ([`crate::NO_NATIVE_HEADER`]) a screen's
10285    /// `header` slot is placed at its top.
10286    fn native_header(&self) -> bool {
10287        self.header_heights != crate::NO_NATIVE_HEADER
10288    }
10289
10290    /// The size of screen `key`: its stack's (`None` outside a stack).
10291    fn screen_size(&self, key: Key) -> Option<Size<Points>> {
10292        let parent = self.nodes[key as usize].parent;
10293        let p = self.nodes.get(parent as usize)?;
10294        let stack_layout = p.layout.filter(|_| p.kind == Kind::Stack)?;
10295        let s = self.rounded_layout(stack_layout).size;
10296        Some(size_pt(s.width, s.height))
10297    }
10298
10299    /// The `header` slot item of screen `key`, once created.
10300    fn header_slot(&self, key: Key) -> Option<Key> {
10301        self.nodes[key as usize]
10302            .children
10303            .iter()
10304            .copied()
10305            .find(|&c| {
10306                let n = &self.nodes[c as usize];
10307                n.kind == Kind::HeaderItem
10308                    && n.created
10309                    && n.root
10310                        .as_ref()
10311                        .is_some_and(|r| r.slot == HeaderSlot::Header)
10312            })
10313    }
10314
10315    /// Without a native header: the height of screen `key`'s `header` slot,
10316    /// laid out first (as wide as the screen), 0 without one.
10317    fn drawn_header(&mut self, key: Key) -> f32 {
10318        let Some(item) = self.header_slot(key) else {
10319            return 0.0;
10320        };
10321        self.layout_detached(item);
10322        self.nodes[item as usize]
10323            .layout
10324            .map_or(0.0, |l| self.rounded_layout(l).size.height)
10325    }
10326
10327    fn layout_detached(&mut self, key: Key) {
10328        if self.nodes[key as usize].is_overlay() {
10329            self.layout_overlay(key);
10330            return;
10331        }
10332        let native_header = self.native_header();
10333        let drawn_header = if !native_header && self.nodes[key as usize].kind == Kind::Screen {
10334            self.drawn_header(key)
10335        } else {
10336            0.0
10337        };
10338        let title_room = {
10339            let n = &self.nodes[key as usize];
10340            let title = native_header
10341                && n.kind == Kind::HeaderItem
10342                && n.root.as_ref().is_some_and(|r| r.slot == HeaderSlot::Title);
10343            let parent = n.parent;
10344            if title && parent != NO_KEY {
10345                self.title_room(parent).unwrap_or(0.0)
10346            } else {
10347                0.0
10348            }
10349        };
10350        let node = &self.nodes[key as usize];
10351        let (Some(layout), kind, parent) = (node.layout, node.kind, node.parent) else {
10352            return;
10353        };
10354        let root = node.root.as_ref().expect("root state");
10355        let (size, header, available) = match kind {
10356            Kind::Screen => {
10357                let Some(size) = self.screen_size(key) else {
10358                    return;
10359                };
10360                let c = &root.screen;
10361                let measured = root
10362                    .header
10363                    .filter(|_| !c.large_title && !c.header_transparent);
10364                let header = if !native_header {
10365                    drawn_header
10366                } else if !c.header_visible {
10367                    0.0
10368                } else if let Some(measured) = measured {
10369                    measured
10370                } else {
10371                    let bar = if c.large_title {
10372                        self.header_heights.1
10373                    } else {
10374                        self.header_heights.0
10375                    };
10376                    bar.0 + self.top_overlap(parent)
10377                };
10378                (size, header, definite(size))
10379            }
10380            // A screen's `header` without a native header: as wide as the
10381            // screen, as tall as its content.
10382            Kind::HeaderItem if !native_header && root.slot == HeaderSlot::Header => {
10383                let Some(screen) = self.screen_size(parent) else {
10384                    return;
10385                };
10386                (
10387                    size_pt(screen.width.0, 0.0),
10388                    0.0,
10389                    taffy::Size {
10390                        width: AvailableSpace::Definite(screen.width.0),
10391                        height: AvailableSpace::MaxContent,
10392                    },
10393                )
10394            }
10395            // A native header's title view: at its content's width, at most
10396            // the room the bar leaves between its items (as the toolbar's own
10397            // title), so a long title shrinks instead of running under them.
10398            Kind::HeaderItem if native_header && root.slot == HeaderSlot::Title => (
10399                Size::default(),
10400                title_room,
10401                taffy::Size {
10402                    width: AvailableSpace::MaxContent,
10403                    height: AvailableSpace::MaxContent,
10404                },
10405            ),
10406            Kind::Modal => {
10407                // A window whose size is not known yet: its content's.
10408                let known = self.root_view_size(key);
10409                let size = known.unwrap_or_default();
10410                let mut available = match known {
10411                    Some(size) => definite(size),
10412                    None => taffy::Size {
10413                        width: AvailableSpace::MaxContent,
10414                        height: AvailableSpace::MaxContent,
10415                    },
10416                };
10417                // A window that fits its content: laid out at its content's
10418                // size on those sides ([`Core::fit_window`]).
10419                let (width, height) = self
10420                    .windows
10421                    .get(&node.id)
10422                    .map_or((false, false), |r| r.fits());
10423                if width {
10424                    available.width = AvailableSpace::MaxContent;
10425                }
10426                if height {
10427                    available.height = AvailableSpace::MaxContent;
10428                }
10429                (size, 0.0, available)
10430            }
10431            // As wide as the window, as tall as its content.
10432            Kind::InputAccessory => (
10433                size_pt(self.viewport.width.0, 0.0),
10434                0.0,
10435                taffy::Size {
10436                    width: AvailableSpace::Definite(self.viewport.width.0),
10437                    height: AvailableSpace::MaxContent,
10438                },
10439            ),
10440            _ => (
10441                Size::default(),
10442                0.0,
10443                taffy::Size {
10444                    width: AvailableSpace::MaxContent,
10445                    height: AvailableSpace::MaxContent,
10446                },
10447            ),
10448        };
10449        let changed = root.laid_out != Some((size, header));
10450        if !changed && !self.layout.dirty(layout) {
10451            return;
10452        }
10453        if kind == Kind::HeaderItem && native_header && root.slot == HeaderSlot::Title {
10454            let mut style = self.layout.style(layout).clone();
10455            style.max_size.width = if header > 0.0 {
10456                taffy::LengthPercentageAuto::length(header)
10457            } else {
10458                taffy::LengthPercentageAuto::auto()
10459            };
10460            self.layout.set_style(layout, style);
10461        } else if kind == Kind::InputAccessory
10462            || (kind == Kind::HeaderItem && size.width > Points::ZERO)
10463        {
10464            let mut style = self.layout.style(layout).clone();
10465            style.size.width = taffy::Dimension::length(size.width.0);
10466            self.layout.set_style(layout, style);
10467        } else if kind != Kind::HeaderItem {
10468            let config_padding = match kind {
10469                // Large titles and transparent headers lay the content out
10470                // under the native header (scroll views inset themselves
10471                // natively).
10472                Kind::Screen
10473                    if native_header
10474                        && (root.screen.header_transparent || root.screen.large_title) =>
10475                {
10476                    0.0
10477                }
10478                _ => header,
10479            };
10480            let mut style = self.nodes[key as usize]
10481                .base_layout
10482                .as_deref()
10483                .cloned()
10484                .unwrap_or_default();
10485            style.size = taffy::Size {
10486                width: taffy::Dimension::length(size.width.0),
10487                height: taffy::Dimension::length(size.height.0),
10488            };
10489            if kind == Kind::Modal {
10490                let id = self.nodes[key as usize].id;
10491                let (mut width, mut height) =
10492                    self.windows.get(&id).map_or((false, false), |r| r.fits());
10493                if self.root_view_size(key).is_none() {
10494                    (width, height) = (true, true);
10495                }
10496                if width {
10497                    style.size.width = taffy::Dimension::auto();
10498                }
10499                if height {
10500                    style.size.height = taffy::Dimension::auto();
10501                }
10502            }
10503            if config_padding > 0.0 {
10504                let base = match style.padding.top.into_raw() {
10505                    raw if raw.tag() == taffy::CompactLength::LENGTH_TAG => raw.value(),
10506                    _ => 0.0,
10507                };
10508                style.padding.top = taffy::LengthPercentage::length(base + config_padding);
10509            }
10510            self.layout.set_style(layout, style);
10511        }
10512        let header_changed = root.laid_out.is_none_or(|(_, h)| h != header);
10513        self.nodes[key as usize]
10514            .root
10515            .as_mut()
10516            .expect("root state")
10517            .laid_out = Some((size, header));
10518        self.layout_root(layout, available);
10519        if kind == Kind::Modal {
10520            self.fit_window(key, layout);
10521        }
10522        self.emit_frames(key);
10523        let screen = match kind {
10524            Kind::Screen if header_changed => Some(key),
10525            Kind::HeaderItem if self.header_item_emptied(key) => Some(parent),
10526            _ => None,
10527        };
10528        if let Some(screen) = screen {
10529            let id = self.nodes[screen as usize].id;
10530            if let Some(config) = self.screen_config(screen) {
10531                self.mount.push(MountItem::ScreenConfig {
10532                    id,
10533                    config: Box::new(config),
10534                });
10535            }
10536        }
10537    }
10538
10539    /// Header item `key` was laid out: records whether a leading,
10540    /// trailing or title one has no width (its content is gone, or shows nothing)
10541    /// and answers whether that changed, so its screen's options go out
10542    /// again with the bar's item left out or put back.
10543    fn header_item_emptied(&mut self, key: Key) -> bool {
10544        let width = self.nodes[key as usize]
10545            .layout
10546            .map_or(0.0, |l| self.rounded_layout(l).size.width);
10547        let root = self.nodes[key as usize].root.as_mut().expect("root state");
10548        if root.slot == HeaderSlot::Header {
10549            return false;
10550        }
10551        let empty = width <= 0.0;
10552        std::mem::replace(&mut root.empty, empty) != empty
10553    }
10554
10555    /// The width a native header leaves screen `key`'s title view: the
10556    /// screen's, less the bar's insets, the back button and the leading and
10557    /// trailing items (laid out first). `None` outside a stack.
10558    fn title_room(&mut self, key: Key) -> Option<f32> {
10559        /// The bar's inset at either end, and the gap after an item.
10560        const INSET: f32 = 16.0;
10561        /// The back button's room, its inset included.
10562        const BACK: f32 = 56.0;
10563        /// The room of a native bar button.
10564        const BUTTON: f32 = 48.0;
10565        let width = self.screen_size(key)?.width.0;
10566        let items: Vec<(Key, HeaderSlot)> = self.nodes[key as usize]
10567            .children
10568            .iter()
10569            .filter_map(|&c| {
10570                let n = &self.nodes[c as usize];
10571                let slot = n.root.as_ref()?.slot;
10572                (n.kind == Kind::HeaderItem
10573                    && n.created
10574                    && matches!(slot, HeaderSlot::Left | HeaderSlot::Right))
10575                .then_some((c, slot))
10576            })
10577            .collect();
10578        let mut room = width - 2.0 * INSET;
10579        let (mut left, mut right) = (false, false);
10580        for (item, slot) in items {
10581            self.layout_detached(item);
10582            let w = self.nodes[item as usize]
10583                .layout
10584                .map_or(0.0, |l| self.rounded_layout(l).size.width);
10585            room -= w + INSET;
10586            match slot {
10587                HeaderSlot::Left => left = true,
10588                _ => right = true,
10589            }
10590        }
10591        let screen = &self.nodes[key as usize];
10592        let config = &screen.root.as_ref()?.screen;
10593        if !right && !config.right_items.is_empty() {
10594            room -= config.right_items.len() as f32 * BUTTON;
10595        }
10596        if !left && !config.left_items.is_empty() {
10597            room -= config.left_items.len() as f32 * BUTTON;
10598        }
10599        // Not the stack's first screen: a back button leads the bar.
10600        let first = self.nodes[screen.parent as usize].children.first() == Some(&key);
10601        if !left && config.back_visible && !first {
10602            room -= BACK;
10603        }
10604        Some(room.max(1.0))
10605    }
10606
10607    /// The options of screen `key`, with its header items.
10608    fn screen_config(&self, key: Key) -> Option<ScreenConfig> {
10609        let node = &self.nodes[key as usize];
10610        let root = node.root.as_ref().filter(|_| node.kind == Kind::Screen)?;
10611        let mut config = root.screen.clone();
10612        config.header_height = Points(root.laid_out.map_or(0.0, |(_, h)| h));
10613        for &c in &node.children {
10614            let child = &self.nodes[c as usize];
10615            if child.kind != Kind::HeaderItem || !child.created {
10616                continue;
10617            }
10618            let slot = child.root.as_ref().map_or(HeaderSlot::Left, |r| r.slot);
10619            // A side's item with nothing to show leaves the bar without a
10620            // button there, unless the platform's own button stands in for
10621            // it (and presses it).
10622            let empty = child.root.as_ref().is_some_and(|r| r.empty);
10623            let system = match slot {
10624                HeaderSlot::Left => {
10625                    config.left_system_item.is_some() || config.left_symbol.is_some()
10626                }
10627                HeaderSlot::Right => {
10628                    config.right_system_item.is_some() || config.right_symbol.is_some()
10629                }
10630                // An empty title view gives the platform's title text back.
10631                HeaderSlot::Title => false,
10632                HeaderSlot::Header => true,
10633            };
10634            if empty && !system {
10635                continue;
10636            }
10637            let target = match slot {
10638                HeaderSlot::Left => &mut config.left,
10639                HeaderSlot::Right => &mut config.right,
10640                HeaderSlot::Title => &mut config.title_view,
10641                HeaderSlot::Header => &mut config.header_view,
10642            };
10643            *target = Some(child.id);
10644        }
10645        if let Some(style) = self.part_resolved(key, classes::Part::Header) {
10646            let background = style.view.background_color;
10647            config.background_color = (background.0 & 0xff != 0).then_some(background);
10648            config.title_color = style.text.color;
10649            config.tint_color = style.view.tint_color;
10650        }
10651        Some(config)
10652    }
10653
10654    /// Lays out the list cells that changed: items at their column's
10655    /// width, the header, footer and empty placeholder at the content's.
10656    fn layout_cells(&mut self) {
10657        for i in 0..self.lists.len() {
10658            let key = self.lists[i];
10659            let list = &self.nodes[key as usize];
10660            let Some(list_layout) = list.layout else {
10661                continue;
10662            };
10663            let state = list.list.as_ref().expect("list");
10664            let horizontal = state.horizontal;
10665            let l = self.rounded_layout(list_layout);
10666            let size = l.size;
10667            let cross = if !state.parent {
10668                if horizontal { size.height } else { size.width }
10669            } else if horizontal {
10670                // In its parent's viewport: the cells fill its content box.
10671                (size.height - l.border.top - l.border.bottom - l.padding.top - l.padding.bottom)
10672                    .max(0.0)
10673            } else {
10674                (size.width - l.border.left - l.border.right - l.padding.left - l.padding.right)
10675                    .max(0.0)
10676            };
10677            // In a terminal its scroll bar takes a column (a row) of its own
10678            // once the content overflows, as a scroll view's does.
10679            let cross = if state.parent {
10680                cross
10681            } else {
10682                let main = if horizontal {
10683                    size.width - l.border.left - l.border.right - l.padding.left - l.padding.right
10684                } else {
10685                    size.height - l.border.top - l.border.bottom - l.padding.top - l.padding.bottom
10686                };
10687                let room = self.layout.list_bar_room(list_layout, horizontal);
10688                if room > 0.0 && state.content_len() > main + 0.5 {
10689                    (cross - room).max(0.0)
10690                } else {
10691                    cross
10692                }
10693            };
10694            let cell = self
10695                .layout
10696                .grid()
10697                .map(|g| if horizontal { g.height } else { g.width });
10698            let item_cross = state.column(cross, 0, cell).1;
10699            let extra_cross = state.full_width(cross).1;
10700            let stretch = state
10701                .content
10702                .align_items
10703                .is_none_or(|a| a == taffy::AlignItems::STRETCH);
10704            let available = |c: f32| {
10705                let cross = if stretch {
10706                    AvailableSpace::Definite(c)
10707                } else {
10708                    AvailableSpace::MaxContent
10709                };
10710                if horizontal {
10711                    taffy::Size {
10712                        width: AvailableSpace::MaxContent,
10713                        height: cross,
10714                    }
10715                } else {
10716                    taffy::Size {
10717                        width: cross,
10718                        height: AvailableSpace::MaxContent,
10719                    }
10720                }
10721            };
10722            // Laying out even a clean root costs a tree walk (taffy rounds the
10723            // whole subtree), so only dirty cells are laid out again — all
10724            // of them when the list's cross size or columns changed.
10725            let list_state = self.nodes[key as usize].list.as_mut().expect("list");
10726            let resized = list_state.cells_cross != cross;
10727            list_state.cells_cross = cross;
10728            let cells = std::mem::take(&mut self.nodes[key as usize].children);
10729            for &cell in &cells {
10730                let node = &self.nodes[cell as usize];
10731                // Its built-in bar: laid out by `layout_scrollbars`.
10732                let (Some(cell_layout), false) = (node.layout, node.decoration) else {
10733                    continue;
10734                };
10735                let c = match node.slot {
10736                    Some(CellSlot::Item(_)) | None => item_cross,
10737                    Some(_) => extra_cross,
10738                };
10739                self.layout.set_host(cell_layout, list_layout);
10740                if resized || self.layout.dirty(cell_layout) {
10741                    self.layout_root(cell_layout, available(c));
10742                    self.nodes[cell as usize].relaid = true;
10743                }
10744            }
10745            self.nodes[key as usize].children = cells;
10746        }
10747    }
10748
10749    /// Lays out the tree under `root` within `available`.
10750    fn layout_root(&mut self, root: LayoutId, available: taffy::Size<AvailableSpace>) {
10751        let measure = leaf_measure(&self.text_engine, &mut self.measure_cache);
10752        self.layout
10753            .compute_layout_with_measure(root, available, measure);
10754    }
10755
10756    /// Lays out the relayout boundaries a change inside made dirty
10757    /// (`LayoutTree::relayout_boundaries`), returning those laid out on
10758    /// their own: their subtrees' frames are new.
10759    fn relayout_boundaries(&mut self) -> Vec<Key> {
10760        let measure = leaf_measure(&self.text_engine, &mut self.measure_cache);
10761        self.layout.relayout_boundaries(measure)
10762    }
10763
10764    /// Whether `key` is out of the layout: `display: none` on it or on a
10765    /// view it is laid out in (Taffy gives all of them no size).
10766    fn displays_none(&self, key: Key) -> bool {
10767        let mut k = key;
10768        while k != NO_KEY {
10769            let n = &self.nodes[k as usize];
10770            if let Some(layout) = n.layout
10771                && self.layout.displays_none(layout)
10772            {
10773                return true;
10774            }
10775            if n.is_layout_root() {
10776                return false;
10777            }
10778            k = n.parent;
10779        }
10780        false
10781    }
10782
10783    #[inline]
10784    fn queue_text(&mut self, key: Key) {
10785        let node = &mut self.nodes[key as usize];
10786        if !node.text_queued {
10787            node.text_queued = true;
10788            self.pending_text.push(key);
10789        }
10790    }
10791
10792    /// Makes the final layout of every queued text block whose content or
10793    /// box changed, and emits it.
10794    fn flush_text(&mut self) {
10795        let mut pending = std::mem::take(&mut self.pending_text);
10796        // Attachment views to place: (block, its final layout, content box).
10797        let mut placements: Vec<(Key, TextLayout, Bounds<Points>)> = Vec::new();
10798        for &key in &pending {
10799            let Some(node) = self.nodes.get_mut(key as usize) else {
10800                continue;
10801            };
10802            node.text_queued = false;
10803            let align_vertical = node.text_style.align_vertical.unwrap_or_default();
10804            let report_lines = node.events.contains(EventKind::TextLayout);
10805            // Shrinking stops at a tenth: smaller is unreadable anyway.
10806            let fit = node
10807                .paragraph
10808                .fit
10809                .then_some(node.paragraph.min_font_scale.max(0.1));
10810            let (id, created, Some(layout)) = (node.id, node.created, node.layout) else {
10811                continue;
10812            };
10813            if !created {
10814                continue;
10815            }
10816            if let Some(commit) = self.measure_cache.resizing
10817                && let Some(LeafContext::Text(cx)) = self.layout.get_node_context_mut(layout)
10818                && cx.near_screen != commit
10819                && cx
10820                    .laid_out
10821                    .as_ref()
10822                    .is_some_and(|l| Arc::ptr_eq(&l.text, &cx.text))
10823            {
10824                cx.held = true;
10825                continue;
10826            }
10827            // Whatever Taffy keeps for it (`emit_frames_in`).
10828            let hidden = self.displays_none(key);
10829            let mut content = if hidden {
10830                Bounds::default()
10831            } else {
10832                content_box(&self.rounded_layout(layout))
10833            };
10834            // The width Taffy measured its lines in, before its box was
10835            // rounded to device pixels (none on a grid, whose Cells hold
10836            // whole characters).
10837            let measured_width = (!hidden && self.layout.grid().is_none())
10838                .then(|| content_box(self.layout.unrounded_layout(layout)).size.width);
10839            let ratio = self.frame_ratio().width;
10840            let engine = &self.text_engine;
10841            let cache = &mut self.measure_cache;
10842            let Some(LeafContext::Text(cx)) = self.layout.get_node_context_mut(layout) else {
10843                continue;
10844            };
10845            let no_wrap = cx.text.no_wrap;
10846            let typeset = |rounded: Points| match measured_width {
10847                Some(measured) if !no_wrap => typeset_width(rounded, measured, ratio),
10848                _ => rounded,
10849            };
10850            if hidden {
10851                // Out of the layout (`display: none`). Its glyphs typeset
10852                // in its zero box would still show where a platform does
10853                // not clip text to its box (a browser), so it gets an
10854                // empty layout; the text itself stays what it is.
10855                if let Some((text, layout)) = cx.remount_metadata(content) {
10856                    self.mount.push(MountItem::Text {
10857                        id,
10858                        text,
10859                        layout,
10860                        content,
10861                    });
10862                    continue;
10863                }
10864                if matches!(&cx.laid_out, Some(l) if l.content == content) {
10865                    continue;
10866                }
10867                let layout =
10868                    engine.layout(&engine.prepare(&AttributedText::default()), content.size);
10869                cx.laid_out = Some(LaidText {
10870                    content,
10871                    layout: layout.clone(),
10872                    text: cx.text.clone(),
10873                });
10874                cx.metadata_changed = false;
10875                self.mount.push(MountItem::Text {
10876                    id,
10877                    text: cx.text.clone(),
10878                    layout,
10879                    content,
10880                });
10881                continue;
10882            }
10883            if cx.text.no_wrap {
10884                // One line at its natural width, past the box if need be.
10885                content.size.width = content
10886                    .size
10887                    .width
10888                    .max(measure_text(engine, cache, cx, None).width);
10889            }
10890            if align_vertical > Percentage(0.0) {
10891                // Text shorter than its box: moved down within it.
10892                let height =
10893                    measure_text(engine, cache, cx, Some(typeset(content.size.width).0)).height;
10894                if height < content.size.height {
10895                    content.origin.y += align_vertical.of(content.size.height - height);
10896                    content.size.height = height;
10897                }
10898            }
10899            if cx.pretty.is_some() && fit.is_none() {
10900                // Lines broken narrower than the box, where they go in it
10901                // as the text is aligned.
10902                let width = pretty_width(engine, cx, content.size.width);
10903                let spare = content.size.width - width;
10904                if spare > Points::ZERO {
10905                    content.origin.x += match cx.text.align {
10906                        TextAlign::Center => spare * 0.5,
10907                        TextAlign::Right => spare,
10908                        TextAlign::Auto if cx.text.rtl => spare,
10909                        _ => Points::ZERO,
10910                    };
10911                    content.size.width = width;
10912                }
10913            }
10914            if let Some((text, layout)) = cx.remount_metadata(content) {
10915                self.mount.push(MountItem::Text {
10916                    id,
10917                    text,
10918                    layout,
10919                    content,
10920                });
10921                continue;
10922            }
10923            let size = content.size;
10924            if let Some(min) = fit {
10925                // Shrunk to fit: its own text, laid out on its own.
10926                if matches!(&cx.laid_out, Some(l) if l.content == content) {
10927                    continue;
10928                }
10929                let text = Arc::new(fitted(
10930                    engine,
10931                    &cx.text,
10932                    &cx.alignments,
10933                    &cx.options,
10934                    size,
10935                    min,
10936                ));
10937                let prepared = engine.prepare_with(&text, &cx.alignments, &cx.options);
10938                let text_layout = engine.layout(&prepared, size);
10939                cx.laid_out = Some(LaidText {
10940                    content,
10941                    layout: text_layout.clone(),
10942                    text: text.clone(),
10943                });
10944                cx.metadata_changed = false;
10945                if report_lines {
10946                    self.events.push(crate::element::JsEvent::Event(
10947                        id,
10948                        EventKind::TextLayout,
10949                        text_lines(engine, &text, &text_layout),
10950                    ));
10951                    keep_geometry(
10952                        &self.geometry_engine,
10953                        &mut self.geometries,
10954                        id,
10955                        &text_layout,
10956                        &text,
10957                        &cx.spacers,
10958                    );
10959                }
10960                if !text.attachments.is_empty() {
10961                    placements.push((key, text_layout.clone(), content));
10962                }
10963                self.mount.push(MountItem::Text {
10964                    id,
10965                    text,
10966                    layout: text_layout,
10967                    content,
10968                });
10969                continue;
10970            }
10971            let text_layout = match &cx.laid_out {
10972                Some(l) if l.content == content => continue,
10973                // Only moved (padding, vertical alignment): the same layout.
10974                Some(l) if l.content.size == size => l.layout.clone(),
10975                // Another width with the same lines in the same places: what
10976                // a window's resize does to most text, typeset for nothing.
10977                Some(l) if keeps_lines(cx, l, size) => l.layout.clone(),
10978                _ => {
10979                    let prepared = cx.prepared.get_or_insert_with(|| {
10980                        engine.prepare_with(&cx.text, &cx.alignments, &cx.options)
10981                    });
10982                    let layout =
10983                        engine.layout(prepared, Size::new(typeset(size.width), size.height));
10984                    if report_lines {
10985                        self.events.push(crate::element::JsEvent::Event(
10986                            id,
10987                            EventKind::TextLayout,
10988                            text_lines(engine, &cx.text, &layout),
10989                        ));
10990                        keep_geometry(
10991                            &self.geometry_engine,
10992                            &mut self.geometries,
10993                            id,
10994                            &layout,
10995                            &cx.text,
10996                            &cx.spacers,
10997                        );
10998                    }
10999                    layout
11000                }
11001            };
11002            cx.laid_out = Some(LaidText {
11003                content,
11004                layout: text_layout.clone(),
11005                text: cx.text.clone(),
11006            });
11007            cx.metadata_changed = false;
11008            if !cx.text.attachments.is_empty() {
11009                placements.push((key, text_layout.clone(), content));
11010            }
11011            self.mount.push(MountItem::Text {
11012                id,
11013                text: cx.text.clone(),
11014                layout: text_layout,
11015                content,
11016            });
11017        }
11018        pending.clear();
11019        self.pending_text = pending;
11020        for (key, layout, content) in placements {
11021            self.place_attachments(key, &layout, content);
11022        }
11023    }
11024
11025    /// Moves the views of text block `key`'s attachments onto their
11026    /// placeholders in `layout` (content box `content`); cut off ones out
11027    /// of sight.
11028    fn place_attachments(&mut self, key: Key, layout: &TextLayout, content: Bounds<Points>) {
11029        let mut points = self.text_engine.attachments(layout);
11030        if let Some(l) = self.nodes[key as usize].layout {
11031            // Padding of spans is no view's.
11032            let cx = self.text_cx(l);
11033            if !cx.spacers.is_empty() {
11034                let mut indices = cx.text.attachments.iter().map(|a| a.index);
11035                points.retain(|_| indices.next().is_none_or(|i| !cx.spacers.contains(&i)));
11036            }
11037        }
11038        let attached = std::mem::take(&mut self.nodes[key as usize].attached);
11039        for (i, &id) in attached.iter().enumerate() {
11040            let Ok(a) = self.key(id) else { continue };
11041            let Some(l) = self.nodes[a as usize].layout else {
11042                continue;
11043            };
11044            let size = self.rounded_layout(l).size;
11045            let (x, y) = match points.get(i).copied().flatten() {
11046                Some(p) => (content.origin.x.0 + p.x.0, content.origin.y.0 + p.y.0),
11047                // Far away, like unbound list cells.
11048                None => (-100_000.0, 0.0),
11049            };
11050            self.set_frame(a, rect(x, y, size.width, size.height));
11051        }
11052        self.nodes[key as usize].attached = attached;
11053    }
11054
11055    /// Emits the frame of `key` and its subtree (if changed).
11056    fn emit_frames(&mut self, key: Key) {
11057        let parent = self.nodes[key as usize].parent;
11058        let hidden = parent != NO_KEY && self.displays_none(parent);
11059        let origin = self.nodes[key as usize]
11060            .layout
11061            .and_then(|l| self.layout.parent(l))
11062            .map_or(Origin::default(), |parent| self.box_origin(parent));
11063        self.emit_frames_in(key, hidden, origin);
11064    }
11065
11066    /// [`Core::emit_frames`] of `key`, `hidden` when a view around it is
11067    /// `display: none`. A view in such a subtree has no frame whatever
11068    /// Taffy keeps for it: Taffy can leave a node moved into a hidden
11069    /// subtree with its former layout (its dirty marking stops at the
11070    /// first node whose cache is empty, which hidden nodes' always are),
11071    /// and never rounds the absolutely positioned ones there (they are
11072    /// rounded through their containing block, which hidden layout does
11073    /// not record), so their native views would keep showing at their
11074    /// former size in a parent of no size.
11075    ///
11076    /// `origin` is where the layout of the view around it is in its layout
11077    /// root ([`Origin`]), carried down the walk.
11078    fn emit_frames_in(&mut self, key: Key, hidden: bool, origin: Origin) {
11079        let node = &self.nodes[key as usize];
11080        let Some(layout) = node.layout else { return };
11081        if !node.created {
11082            if node.culled {
11083                self.cull_frames_in(key, hidden, origin);
11084            }
11085            return;
11086        }
11087        let hidden = hidden || self.layout.displays_none(layout);
11088        if hidden {
11089            self.layout.emitted(layout);
11090            self.nodes[key as usize].emitted = None;
11091            if self.nodes[key as usize].follow.is_some() {
11092                self.laid_follower(key, None, false, (0.0, 0.0));
11093            }
11094            self.set_frame(key, Bounds::default());
11095            // An input's field would still show at its former content box
11096            // where a platform does not clip a view's children (a browser),
11097            // so it gets none either.
11098            let node = &mut self.nodes[key as usize];
11099            if let Some(input) = node.input.as_mut()
11100                && input.content.is_some_and(|c| c != Bounds::default())
11101            {
11102                input.content = Some(Bounds::default());
11103                self.mount.push(MountItem::InputContent {
11104                    id: node.id,
11105                    content: Bounds::default(),
11106                });
11107            }
11108            if self.nodes[key as usize].kind.is_container() {
11109                let children = std::mem::take(&mut self.nodes[key as usize].children);
11110                for &child in &children {
11111                    if !self.nodes[child as usize].is_layout_root() {
11112                        self.emit_frames_in(child, true, origin);
11113                    }
11114                }
11115                self.nodes[key as usize].children = children;
11116            }
11117            return;
11118        }
11119        let node = &self.nodes[key as usize];
11120        let unrounded = *self.layout.unrounded_layout(layout);
11121        // An absolute view in a positioned parent (React Native's default
11122        // `relative`) is placed in that parent, whose origin is `origin`,
11123        // summed in the same order as `layout_origin` sums it: only one
11124        // placed further up walks there (every cell of a table would walk to
11125        // the root, each frame the tree is laid out).
11126        let position = self.layout.style(layout).position;
11127        let escaping = position == Position::Fixed
11128            || (position == Position::Absolute
11129                && !self
11130                    .layout
11131                    .parent(layout)
11132                    .is_some_and(|p| self.layout.style(p).position.is_positioned()));
11133        let ratio = self.frame_ratio();
11134        // Nothing in the subtree was laid out anew and its origin moved by
11135        // whole device pixels (or not at all), its edges as they were: every
11136        // frame in it, relative to its parent, rounds as it did. A scroll
11137        // that moves a table's rows walks the rows' origin, not each cell.
11138        if !self.layout.stale(layout)
11139            && !node.escapes
11140            && !node.is_overlay()
11141            && !node.decoration
11142            && !self.nodes.get(node.parent as usize).is_some_and(|p| p.rtl)
11143            && node.emitted.is_some_and(|(at, r)| {
11144                let moved = |a: f32, b: f32, ratio: f32| {
11145                    let d = (a - b) * ratio;
11146                    d == d.round()
11147                };
11148                r == ratio
11149                    && at.back == origin.back
11150                    && moved(origin.at.x, at.at.x, ratio.width)
11151                    && moved(origin.at.y, at.at.y, ratio.height)
11152            })
11153        {
11154            self.nodes[key as usize].emitted = Some((origin, ratio));
11155            return;
11156        }
11157        self.layout.emitted(layout);
11158        let containing = if escaping {
11159            self.containing_origin(layout)
11160        } else {
11161            origin
11162        };
11163        let inner = Origin::of(
11164            taffy::Point {
11165                x: containing.at.x + unrounded.location.x,
11166                y: containing.at.y + unrounded.location.y,
11167            },
11168            unrounded.size,
11169            ratio,
11170        );
11171        let l = rounded(&unrounded, containing, ratio);
11172        let offset = origin.to(containing, ratio);
11173        let mut frame = rect(
11174            l.location.x + offset.x,
11175            l.location.y + offset.y,
11176            l.size.width,
11177            l.size.height,
11178        );
11179        // Children of a right-to-left horizontal scroll view: mirrored in
11180        // its content (not its bar, over the viewport).
11181        if let Some(parent) = self.nodes.get(node.parent as usize)
11182            && !node.decoration
11183            && parent.rtl
11184            && let Some(ScrollState {
11185                horizontal: true,
11186                content: Some(content),
11187                ..
11188            }) = parent.scroll.as_deref()
11189            && parent.kind == Kind::Scroll
11190        {
11191            frame.origin.x = content.width - frame.origin.x - frame.size.width;
11192        }
11193        if node.is_overlay() {
11194            frame.origin = self.overlay_origin(key, frame);
11195        }
11196        // A multiline input's bar: over it, laid out on its own.
11197        let beside = self.nodes[key as usize].beside;
11198        if beside != NO_KEY {
11199            frame.origin = self.nodes[beside as usize].frame.origin;
11200        } else if self.nodes[key as usize].decoration {
11201            // A scroll view's bar is laid out on its own, at no location:
11202            // `origin` is where it sits in the viewport (its
11203            // `scrollbar_inset`, [`Core::layout_scrollbars`]).
11204            let offset = Origin::default().to(origin, ratio);
11205            frame.origin.x.0 += offset.x;
11206            frame.origin.y.0 += offset.y;
11207        }
11208        if self.nodes[key as usize].follow.is_some() {
11209            // Its frame along the main axis is the element's it follows,
11210            // laid out by now or not: placed once every frame is out.
11211            let column = self.layout.parent(layout).is_some_and(|p| {
11212                let style = self.layout.style(p);
11213                style.display == taffy::Display::Flex
11214                    && matches!(
11215                        style.flex_direction,
11216                        taffy::FlexDirection::Column | taffy::FlexDirection::ColumnReverse
11217                    )
11218            });
11219            let m = unrounded.margin;
11220            let margins = if column {
11221                (round(m.top, ratio.height), round(m.bottom, ratio.height))
11222            } else {
11223                (round(m.left, ratio.width), round(m.right, ratio.width))
11224            };
11225            self.laid_follower(key, Some(frame), column, margins);
11226        } else {
11227            self.set_frame(key, frame);
11228        }
11229        self.sync_cell_style(key, layout, &unrounded);
11230        self.sync_focus_ring(key);
11231        let kind = self.nodes[key as usize].kind;
11232        if kind == Kind::Input {
11233            let content = content_box(&l);
11234            let node = &mut self.nodes[key as usize];
11235            let input = node.input.as_mut().expect("input state");
11236            if input.content != Some(content) {
11237                input.content = Some(content);
11238                self.mount.push(MountItem::InputContent {
11239                    id: node.id,
11240                    content,
11241                });
11242            }
11243            if node.events.contains(EventKind::ContentSizeChange) {
11244                self.report_content_size(key, content.size.width.0);
11245            }
11246        }
11247        if kind == Kind::Scroll {
11248            let horizontal = self.nodes[key as usize]
11249                .scroll
11250                .as_ref()
11251                .is_some_and(|s| s.horizontal);
11252            self.set_scroll_content(key, scroll_extent(&l, horizontal));
11253        }
11254        // List cells are positioned by `update_lists`, roots by
11255        // `layout_roots`.
11256        let mut escapes = escaping;
11257        if kind.is_container() && kind != Kind::List {
11258            let children = std::mem::take(&mut self.nodes[key as usize].children);
11259            for &child in &children {
11260                if !self.nodes[child as usize].is_layout_root() {
11261                    self.emit_frames_in(child, false, inner);
11262                    escapes |= self.nodes[child as usize].escapes;
11263                }
11264            }
11265            self.nodes[key as usize].children = children;
11266            self.update_overflow(key);
11267        }
11268        let node = &mut self.nodes[key as usize];
11269        node.escapes = escapes;
11270        node.emitted = Some((origin, ratio));
11271    }
11272
11273    /// In a terminal, mounts node `key` without the borders its layout
11274    /// `l` gives no Cell (`Node::cell_border`) and with whether that layout
11275    /// shows its label (`Node::cell_label`), again when either changes;
11276    /// off a terminal, with its borders as styled again and no label.
11277    fn sync_cell_style(&mut self, key: Key, layout: LayoutId, l: &taffy::Layout) {
11278        let w = self.nodes[key as usize].view_style.borders.widths;
11279        let styled = [w.top, w.right, w.bottom, w.left]
11280            .iter()
11281            .any(|&v| v > Points::ZERO);
11282        // Only a bordered view's style changes.
11283        let sides = self.layout.grid().filter(|_| styled).map(|_| {
11284            let b = l.border;
11285            [b.top, b.right, b.bottom, b.left]
11286                .iter()
11287                .enumerate()
11288                .fold(0u8, |m, (bit, &v)| m | (u8::from(v > 0.0) << bit))
11289        });
11290        let label = self.layout.labelled(layout);
11291        let node = &mut self.nodes[key as usize];
11292        if node.cell_border == sides && node.cell_label == label {
11293            return;
11294        }
11295        node.cell_border = sides;
11296        node.cell_label = label;
11297        let id = node.id;
11298        let style = self.mounted_view_style(key);
11299        self.mount.push(MountItem::ViewStyle { id, style });
11300    }
11301
11302    /// Queues node `key`'s frame for its layout listeners once it was laid
11303    /// out: a listener added after layout still learns the frame.
11304    fn report_frame(&mut self, key: Key) {
11305        let node = &self.nodes[key as usize];
11306        if !node.frame.origin.x.0.is_nan() {
11307            self.events.push(crate::element::JsEvent::Event(
11308                node.id,
11309                EventKind::Layout,
11310                EventPayload::Layout(node.frame),
11311            ));
11312        }
11313    }
11314
11315    fn set_frame(&mut self, key: Key, frame: Bounds<Points>) {
11316        let node = &mut self.nodes[key as usize];
11317        if node.frame != frame {
11318            let resized = node.frame.size != frame.size;
11319            node.frame = frame;
11320            self.note_resized(key, resized);
11321            // What views follow may have moved.
11322            self.follow_changed |= !self.followers.is_empty();
11323            let node = &self.nodes[key as usize];
11324            let (id, is_text) = (node.id, node.kind == Kind::Text);
11325            if node.events.contains(EventKind::Layout) {
11326                self.events.push(crate::element::JsEvent::Event(
11327                    id,
11328                    EventKind::Layout,
11329                    EventPayload::Layout(frame),
11330                ));
11331            }
11332            if node.created {
11333                self.mount.push(MountItem::Frame { id, frame });
11334            }
11335            let node = &self.nodes[key as usize];
11336            // A list's cell moved: the logical order goes by where cells are.
11337            if self.track_tree_order
11338                && node.parent != NO_KEY
11339                && self.nodes[node.parent as usize].list.is_some()
11340            {
11341                self.tree_order_changed = true;
11342            }
11343            let node = &self.nodes[key as usize];
11344            // Translations by a fraction of the size follow it, and so does
11345            // the perspective of its parent, seen from the parent's center.
11346            let parent_perspective = self.perspective_steps(key) > 0;
11347            if node.created && (node.view_style.transform.has_fractions() || parent_perspective) {
11348                let style = self.mounted_view_style(key);
11349                self.mount.push(MountItem::ViewStyle { id, style });
11350            }
11351            if node.child_perspective.is_some() {
11352                // Its center moved for its children.
11353                let children = node.children.clone();
11354                for c in children {
11355                    self.mark(c, dirty::VIEW);
11356                }
11357            }
11358            if is_text {
11359                self.queue_text(key);
11360            }
11361            // A view box fits into the new size.
11362            let node = &self.nodes[key as usize];
11363            if node.kind == Kind::Canvas && node.drawing.as_ref().is_some_and(|d| d.fit().is_some())
11364            {
11365                self.fitted_pending.push(key);
11366            }
11367        }
11368    }
11369
11370    fn set_scroll_content(&mut self, key: Key, size: Size<Points>) {
11371        let node = &mut self.nodes[key as usize];
11372        let (id, rtl, kind, viewport) = (node.id, node.rtl, node.kind, node.frame.size.width.0);
11373        if let Some(scroll) = node.scroll.as_mut()
11374            && scroll.content != Some(size)
11375        {
11376            let old = scroll.content.replace(size);
11377            // Items are only inserted before it since (a `ScrollBy`, the
11378            // layout animation), so it is at its index or later.
11379            let batch = self.batches;
11380            let queued = scroll
11381                .content_item
11382                .filter(|&(b, _)| b == batch)
11383                .and_then(|(_, i)| {
11384                    let at = self.mount.get(i..)?.iter().position(
11385                        |m| matches!(m, MountItem::ScrollContent { id: queued, .. } if *queued == id),
11386                    )?;
11387                    Some(i + at)
11388                });
11389            // A shrink after a scroll must keep the earlier extent until
11390            // that scroll has applied. Growth can replace the extent once.
11391            let shrunk = old.is_some_and(|old| {
11392                if scroll.horizontal {
11393                    size.width < old.width
11394                } else {
11395                    size.height < old.height
11396                }
11397            });
11398            let keep_earlier = shrunk
11399                && queued.is_some_and(|j| {
11400                    self.mount[j + 1..].iter().any(|item| match item {
11401                        MountItem::ScrollBy { id: scrolled, .. } => *scrolled == id,
11402                        MountItem::Command {
11403                            id: scrolled,
11404                            command: Command::ScrollTo { .. },
11405                        } => *scrolled == id,
11406                        _ => false,
11407                    })
11408                });
11409            if let Some(j) = queued
11410                && !keep_earlier
11411            {
11412                self.mount[j] = MountItem::ScrollContent { id, size };
11413            }
11414            if queued.is_none() || keep_earlier {
11415                scroll.content_item = Some((batch, self.mount.len()));
11416                self.mount.push(MountItem::ScrollContent { id, size });
11417            }
11418            // Right to left, a horizontal scroll view starts at its right
11419            // end and keeps its distance from it as the content changes.
11420            if kind == Kind::Scroll && scroll.horizontal && rtl {
11421                match old {
11422                    None => self.commands.push((
11423                        id,
11424                        Command::ScrollTo {
11425                            x: (size.width - Points(viewport)).max(Points::ZERO),
11426                            y: Points::ZERO,
11427                            animated: false,
11428                        },
11429                    )),
11430                    Some(old) if old.width != size.width => {
11431                        let dx = size.width - old.width;
11432                        self.mount.push(MountItem::ScrollBy {
11433                            id,
11434                            dx,
11435                            dy: Points::ZERO,
11436                        });
11437                        self.scroll_issued(key, PendingScroll::By(dx.0));
11438                    }
11439                    Some(_) => {}
11440                }
11441            }
11442        }
11443    }
11444
11445    /// Measures rendered cells, keeps the visible content anchored, picks
11446    /// the items to render and positions the cells of every list.
11447    fn update_lists(&mut self, relayout: bool) {
11448        // A cell measured before JS's render of its content arrives would
11449        // record the size of its empty placeholders.
11450        let mut awaiting = std::mem::take(&mut self.awaiting_renders);
11451        self.cells_awaiting_renders(&mut awaiting);
11452        self.awaiting_renders = awaiting;
11453        for i in 0..self.lists.len() {
11454            let key = self.lists[i];
11455            // Lists in their parent's viewport come after, outer ones first.
11456            if self.nodes[key as usize]
11457                .list
11458                .as_ref()
11459                .is_some_and(|l| l.parent)
11460            {
11461                continue;
11462            }
11463            self.update_list(key, relayout, None);
11464        }
11465        if !self.parent_lists.is_empty() {
11466            if self.outer_moved {
11467                self.resolve_outer();
11468            }
11469            for i in 0..self.parent_lists.len() {
11470                let key = self.parent_lists[i];
11471                if !self.nodes[key as usize].created {
11472                    continue;
11473                }
11474                // Out of the tree, or not placed yet.
11475                let Some(outer) = self.outer_input(key) else {
11476                    continue;
11477                };
11478                self.update_list(key, relayout, Some(outer));
11479            }
11480        }
11481        if !self.sticky_nodes.is_empty()
11482            || !self.sticky_scrollers.is_empty()
11483            || !self.decorated.is_empty()
11484        {
11485            self.update_sticky_views(relayout);
11486        }
11487        if !self.sticky_views.is_empty() {
11488            self.send_page_sticky();
11489        }
11490    }
11491
11492    /// Hides the attachments of text `key` (views and images inside it) that
11493    /// are inside a hidden span, `hidden` when `key` is one, and shows the
11494    /// others: nothing of a hidden span is drawn or takes presses.
11495    fn hide_attachments(&mut self, key: Key, hidden: bool) {
11496        let count = self.nodes[key as usize].children.len();
11497        for i in 0..count {
11498            let c = self.nodes[key as usize].children[i];
11499            let child = &self.nodes[c as usize];
11500            if child.is_overlay() {
11501                continue;
11502            }
11503            match child.kind {
11504                Kind::RawText | Kind::Overlay => {}
11505                Kind::Text => {
11506                    let hidden = hidden || child.view_style.hidden;
11507                    self.hide_attachments(c, hidden);
11508                }
11509                _ if child.layout.is_some() => self.set_hidden_in_text(c, hidden),
11510                _ => {}
11511            }
11512        }
11513    }
11514
11515    /// Hides attachment `key` with the hidden span it is in, or shows it
11516    /// again; sent at once, as [`Core::set_spare`].
11517    fn set_hidden_in_text(&mut self, key: Key, hidden: bool) {
11518        let node = &mut self.nodes[key as usize];
11519        if node.hidden_in_text == hidden {
11520            return;
11521        }
11522        node.hidden_in_text = hidden;
11523        if !node.created {
11524            // Its new view gets both (`ensure_created`).
11525            return;
11526        }
11527        let (id, props) = (node.id, node.mounted_props());
11528        let style = self.mounted_view_style(key);
11529        self.mount.push(MountItem::ViewStyle { id, style });
11530        self.mount.push(MountItem::ViewProps { id, props });
11531    }
11532
11533    /// Hides list cell `key`, which has no item but still shows its last
11534    /// row (`visibility: hidden` and `accessibilityElementsHidden`), or
11535    /// shows it again as its list places it. Sent at once: this round's
11536    /// dirty flags were flushed before the lists' update.
11537    fn set_spare(&mut self, key: Key, spare: bool) {
11538        let node = &mut self.nodes[key as usize];
11539        if node.spare == spare {
11540            return;
11541        }
11542        node.spare = spare;
11543        // A spare cell shows no row for views to follow (`follow.rs`).
11544        self.follow_changed |= !self.followers.is_empty();
11545        let node = &self.nodes[key as usize];
11546        if !node.created {
11547            // Its new view gets both (`ensure_created`).
11548            return;
11549        }
11550        let (id, props) = (node.id, node.mounted_props());
11551        let style = self.mounted_view_style(key);
11552        self.mount.push(MountItem::ViewStyle { id, style });
11553        self.mount.push(MountItem::ViewProps { id, props });
11554    }
11555
11556    /// Hides list cell `key`, which the render window left behind, from
11557    /// assistive technology, or reads it again as its list places it: its
11558    /// frame is where its row was laid out last, which rows measured since
11559    /// may have moved past. Its props only: it stays drawn, out of sight.
11560    fn set_left_behind(&mut self, key: Key, left_behind: bool) {
11561        let node = &mut self.nodes[key as usize];
11562        if node.left_behind == left_behind {
11563            return;
11564        }
11565        node.left_behind = left_behind;
11566        if !node.created || node.spare {
11567            // Its new view gets them (`ensure_created`), or `set_spare`
11568            // sends them as it shows the cell again.
11569            return;
11570        }
11571        let (id, props) = (node.id, node.mounted_props());
11572        self.mount.push(MountItem::ViewProps { id, props });
11573    }
11574
11575    /// [`Core::update_lists`] for list `key`; `outer`: where a list in its
11576    /// parent's viewport is in the view it is virtualized against.
11577    fn update_list(
11578        &mut self,
11579        key: Key,
11580        relayout: bool,
11581        outer: Option<parent_viewport::OuterInput>,
11582    ) {
11583        let moved = match &outer {
11584            Some(o) => self.nodes[key as usize]
11585                .list
11586                .as_mut()
11587                .expect("list")
11588                .set_outer(o.start, o.offset, o.viewport, o.max, o.settled),
11589            None => false,
11590        };
11591        let node = &self.nodes[key as usize];
11592        if !node.created {
11593            return;
11594        }
11595        // Under `display: none` it has no size, which is no viewport to
11596        // empty its window by: it keeps its rows bound until it shows again
11597        // (a page kept alive under a hidden tab).
11598        if self.displays_none(key) {
11599            return;
11600        }
11601        let list = node.list.as_ref().expect("list");
11602        if !(relayout || moved || list.dirty || self.commands.iter().any(|c| c.0 == node.id)) {
11603            return;
11604        }
11605        let (id, events) = (node.id, node.events);
11606        let horizontal = list.horizontal;
11607        let l = self.rounded_layout(node.layout.expect("list layout"));
11608        let (main, cross) = match &outer {
11609            // The view's viewport, and the list's content box across.
11610            Some(o) => (o.viewport, o.cross),
11611            None if horizontal => (l.size.width, l.size.height),
11612            None => (l.size.height, l.size.width),
11613        };
11614        let main_of = |s: taffy::Size<f32>| if horizontal { s.width } else { s.height };
11615
11616        // Sizes of cells showing their item, and of the extras.
11617        let mut ready = std::mem::take(&mut self.cells_scratch);
11618        ready.clear();
11619        ready.extend(
11620            list.slots
11621                .iter()
11622                .filter_map(|s| s.ready().map(|i| (i, s.cell))),
11623        );
11624        let extras = list.extras;
11625        // An inverted list that loads at its start keeps its rows in
11626        // place when scrolled away from it (`keeps_visible_rows`).
11627        self.nodes[key as usize]
11628            .list
11629            .as_mut()
11630            .expect("list")
11631            .loads_at_start = events.contains(EventKind::LoadMoreAtStart);
11632        let mut anchor = 0.0;
11633        for &(index, cell) in &ready {
11634            // Waiting for JS's render: it keeps its estimate (or the size
11635            // measured last) until the holder arrives and lays it out
11636            // again. A list in a view sized by its content would otherwise
11637            // shrink to nothing and leave no row in its window to render.
11638            if self.awaiting_renders.binary_search(&cell).is_ok() {
11639                continue;
11640            }
11641            if let Some(cell_layout) = self.nodes.get(cell as usize).and_then(|c| c.layout) {
11642                let size = main_of(self.rounded_layout(cell_layout).size);
11643                let list = self.nodes[key as usize].list.as_mut().expect("list");
11644                anchor += list.measured(index, size);
11645            }
11646        }
11647        for (kind, extra) in [ExtraKind::Header, ExtraKind::Footer, ExtraKind::Empty]
11648            .into_iter()
11649            .zip(extras)
11650        {
11651            if self.awaiting_renders.binary_search(&extra.cell).is_ok() {
11652                continue;
11653            }
11654            if let Some(cell_layout) = self.nodes.get(extra.cell as usize).and_then(|c| c.layout) {
11655                let size = main_of(self.rounded_layout(cell_layout).size);
11656                let list = self.nodes[key as usize].list.as_mut().expect("list");
11657                anchor += list.measured_extra(kind, size);
11658            }
11659        }
11660
11661        // Its own scroll view's range takes the content inset in; in its
11662        // parent's viewport, the view around it has the range.
11663        let inset = match (&outer, self.nodes[key as usize].scroll.as_deref()) {
11664            (None, Some(scroll)) => {
11665                let i = scroll.behavior.content_inset;
11666                if horizontal {
11667                    (i.left.0, i.right.0)
11668                } else {
11669                    (i.top.0, i.bottom.0)
11670                }
11671            }
11672            _ => (0.0, 0.0),
11673        };
11674        let list = self.nodes[key as usize].list.as_mut().expect("list");
11675        // Not on the first layout: there is nothing to clamp yet.
11676        let grew = outer.is_none() && list.viewport > 0.0 && main > list.viewport;
11677        list.viewport = main;
11678        list.inset = inset;
11679        list.offset += anchor;
11680        // A splice above the viewport already moved the offset, to keep
11681        // the visible rows in place: like measurements, that says nothing
11682        // about where the user is.
11683        let spliced = list.take_splice_anchor();
11684        anchor += spliced;
11685        let kept = anchor;
11686        // A row growing under its own layout animation (a reveal) moves
11687        // the end while its frames slide: a scroll to the new end would
11688        // land at once, ahead of them, so the list keeps its place.
11689        let revealing = !self.scoped_layout.is_empty() && {
11690            let scoped = &self.scoped_layout;
11691            scoped.iter().any(|&(scope, ..)| {
11692                self.key(scope)
11693                    .is_ok_and(|k| k != key && self.is_within(k, key))
11694            })
11695        };
11696        let list = self.nodes[key as usize].list.as_mut().expect("list");
11697        list.revealing = revealing;
11698        // Inverted lists keep their distance from the end instead;
11699        // `maintainVisibleContentPosition` follows the end near it.
11700        anchor += list.anchor_end(kept);
11701        // The last scroll command's target moves as its cells are
11702        // measured: the list follows it.
11703        let mut retarget = None;
11704        match list.follow_pin(anchor) {
11705            Follow::Stay => {}
11706            Follow::By(delta) => anchor += delta,
11707            Follow::To(offset) => retarget = Some(offset),
11708        }
11709        // `maintainVisibleContentPosition={{ animated }}`: the end moved
11710        // away by a large step, so the list animates there instead of
11711        // jumping, and the pin keeps the animation's target at the end as
11712        // the content goes on growing.
11713        if list.take_animated_end() {
11714            let end = list.target_offset(PinTarget::End);
11715            list.pin(Some(PinTarget::End), end, true);
11716            retarget = Some(end);
11717        }
11718
11719        // The End key's commands, if any, are resolved below with the
11720        // rest (`Core::key_scrolled`).
11721        list.key_ends.clear();
11722        // Scroll commands for the list, now that sizes are known: the
11723        // window follows a jump in this same commit. In its parent's
11724        // viewport, the view around it scrolls instead.
11725        let mut outer_to = None;
11726        // The `ScrollTo`s sent with this layout, recorded after its
11727        // anchoring `ScrollBy` (below): the platform applies that one
11728        // first, a mount item before the commands. Counted the other way,
11729        // a report between the two would replay the `ScrollBy` over the
11730        // `ScrollTo` and leave the list believed away from where it is.
11731        let mut scrolls_to = Vec::new();
11732        for (target, command) in &mut self.commands {
11733            if *target != id {
11734                continue;
11735            }
11736            let list = self.nodes[key as usize].list.as_mut().expect("list");
11737            let (pin, animated) = match *command {
11738                Command::ScrollToIndex {
11739                    index,
11740                    animated,
11741                    view_position,
11742                    view_offset,
11743                } => (
11744                    Some(PinTarget::Index {
11745                        index,
11746                        view_position: view_position.0,
11747                        view_offset: view_offset.0,
11748                    }),
11749                    animated,
11750                ),
11751                Command::ScrollToEnd { animated } => (Some(PinTarget::End), animated),
11752                Command::ScrollTo { animated, .. } => (None, animated),
11753                _ => continue,
11754            };
11755            let offset = match (pin, &*command) {
11756                (Some(pin), _) => list.target_offset(pin),
11757                (None, &Command::ScrollTo { x, y, .. }) => {
11758                    let offset = if horizontal { x.0 } else { y.0 };
11759                    if outer.is_some() {
11760                        list.clamped(offset)
11761                    } else {
11762                        offset
11763                    }
11764                }
11765                _ => continue,
11766            };
11767            // An offset of the app's own ends the pin.
11768            list.pin(pin, offset, animated);
11769            // A new command replaces the pin's retargeting.
11770            retarget = None;
11771            if !animated {
11772                list.jump(offset);
11773            }
11774            if let Some(o) = &outer {
11775                outer_to = Some((o.start + offset, animated));
11776                continue;
11777            }
11778            scrolls_to.push((offset, animated));
11779            let (x, y) = if horizontal {
11780                (Points(offset), Points::ZERO)
11781            } else {
11782                (Points::ZERO, Points(offset))
11783            };
11784            *command = Command::ScrollTo { x, y, animated };
11785        }
11786        if outer_to.is_some() {
11787            // Sent to the view around the list instead.
11788            self.commands.retain(|(target, command)| {
11789                *target != id
11790                    || !matches!(
11791                        command,
11792                        Command::ScrollTo { .. }
11793                            | Command::ScrollToIndex { .. }
11794                            | Command::ScrollToEnd { .. }
11795                    )
11796            });
11797        }
11798        if let (Some(offset), Some(o)) = (retarget, &outer) {
11799            outer_to = Some((o.start + offset, true));
11800        } else if let Some(offset) = retarget {
11801            scrolls_to.push((offset, true));
11802            let (x, y) = if horizontal {
11803                (Points(offset), Points::ZERO)
11804            } else {
11805                (Points::ZERO, Points(offset))
11806            };
11807            let command = Command::ScrollTo {
11808                x,
11809                y,
11810                animated: true,
11811            };
11812            self.commands.push((id, command));
11813        }
11814
11815        // The components' own lists bind in the core, at once; the
11816        // runtime's pace their overscan.
11817        let paced = !self.components.is_virtual_list(id);
11818        let list = self.nodes[key as usize].list.as_mut().expect("list");
11819        list.paced = paced;
11820        let mut binds = Vec::new();
11821        let edges = list.update_window(&mut binds);
11822        if edges.end {
11823            self.events.push(crate::element::JsEvent::Event(
11824                id,
11825                EventKind::LoadMore,
11826                EventPayload::None,
11827            ));
11828        }
11829        if edges.start && events.contains(EventKind::LoadMoreAtStart) {
11830            self.events.push(crate::element::JsEvent::Event(
11831                id,
11832                EventKind::LoadMoreAtStart,
11833                EventPayload::None,
11834            ));
11835        }
11836        if !binds.is_empty() {
11837            self.list_binds.push(ListBind { list: id, binds });
11838        }
11839        if list.paced && list.has_paced() && !self.paced_lists.contains(&id) {
11840            self.paced_lists.push(id);
11841        }
11842        if events.contains(EventKind::ViewableItemsChange) {
11843            let viewable = list.viewable_items();
11844            if viewable != list.viewable {
11845                list.viewable = viewable;
11846                let (first, last) = viewable.map_or((-1.0, -1.0), |(f, l)| (f as f64, l as f64));
11847                self.events.push(crate::element::JsEvent::Event(
11848                    id,
11849                    EventKind::ViewableItemsChange,
11850                    EventPayload::Map(vec![
11851                        ("first", PayloadValue::Number(first)),
11852                        ("last", PayloadValue::Number(last)),
11853                    ]),
11854                ));
11855            }
11856        }
11857
11858        // Position cells that show their item (the window may have
11859        // changed which ones). Descendant frames only change when the
11860        // cell was laid out again.
11861        let list = self.nodes[key as usize].list.as_ref().expect("list");
11862        let sticky = list.sticky_enabled();
11863        ready.clear();
11864        ready.extend(
11865            list.slots
11866                .iter()
11867                .filter_map(|s| s.ready().map(|i| (i, s.cell))),
11868        );
11869        // A cell bound just now to the row it already shows (it took it
11870        // back after the items changed) gets no render to lay it out
11871        // again, and was not ready when the list measured above: measured
11872        // now, the rows after it are placed after its real size.
11873        for &(index, cell) in &ready {
11874            if self.awaiting_renders.binary_search(&cell).is_ok() {
11875                continue;
11876            }
11877            if let Some(cell_layout) = self.nodes.get(cell as usize).and_then(|c| c.layout) {
11878                let size = main_of(self.rounded_layout(cell_layout).size);
11879                let list = self.nodes[key as usize].list.as_mut().expect("list");
11880                list.measured_unknown(index, size);
11881            }
11882        }
11883        let list = self.nodes[key as usize].list.as_ref().expect("list");
11884        let content_len = list.content_len();
11885        let blocks = list.blocks();
11886        // Cells left without an item, or not showing theirs yet (a paced
11887        // bind, or one the frame's rounds did not reach), still show their
11888        // last one. Those in the render window (the data changed, the list
11889        // jumped) would show through: move them out of sight. They, the ones
11890        // never placed and, once the items changed, all of them are hidden
11891        // until placed again ([`Core::set_spare`]); the few the window leaves
11892        // behind while scrolling are out of sight already and soon reused,
11893        // so they stay drawn, but screen readers skip them: they would read
11894        // rows out of the window, by frames rows measured since may have
11895        // passed ([`Core::set_left_behind`]).
11896        let (window_start, window_end) = list.render_window();
11897        let motion = outer.is_none() && self.list_motion.active();
11898        if motion {
11899            let cells: Vec<Key> = list
11900                .slots
11901                .iter()
11902                .map(|s| s.cell)
11903                .chain(list.extras.iter().map(|e| e.cell))
11904                .collect();
11905            self.note_cell_starts(cells);
11906        }
11907        let list = self.nodes[key as usize].list.as_ref().expect("list");
11908        // In its parent's viewport, the cells start inside the list's
11909        // border and padding.
11910        let inset = outer.map_or((0.0, 0.0), |o| o.inset);
11911        let unbound: Vec<Key> = list
11912            .slots
11913            .iter()
11914            .filter(|s| s.ready().is_none() && s.cell != u32::MAX)
11915            .map(|s| s.cell)
11916            .collect();
11917        let changed = std::mem::take(
11918            &mut self.nodes[key as usize]
11919                .list
11920                .as_mut()
11921                .expect("list")
11922                .items_changed,
11923        );
11924        for cell in unbound {
11925            let frame = self.nodes[cell as usize].frame;
11926            if frame.size.width.0.is_nan() {
11927                // Never placed: nowhere to move it from.
11928                self.set_spare(cell, true);
11929                continue;
11930            }
11931            let (start, size) = if horizontal {
11932                (frame.origin.x.0 - inset.0, frame.size.width.0)
11933            } else {
11934                (frame.origin.y.0 - inset.0, frame.size.height.0)
11935            };
11936            if start + size <= window_start || start >= window_end {
11937                if changed {
11938                    self.set_spare(cell, true);
11939                } else {
11940                    self.set_left_behind(cell, true);
11941                }
11942                continue;
11943            }
11944            self.set_spare(cell, true);
11945            let away = if horizontal {
11946                Bounds {
11947                    origin: Point::new(Points(-HIDDEN), frame.origin.y),
11948                    ..frame
11949                }
11950            } else {
11951                Bounds {
11952                    origin: Point::new(frame.origin.x, Points(-HIDDEN)),
11953                    ..frame
11954                }
11955            };
11956            if frame != away {
11957                self.set_frame(cell, away);
11958                self.nodes[key as usize]
11959                    .list
11960                    .as_mut()
11961                    .expect("list")
11962                    .unplace(cell);
11963            }
11964        }
11965        let mut sticky_cells = Vec::new();
11966        let place = |this: &mut Self, cell: Key, at: f32, row: f32, (x, width): (f32, f32)| {
11967            let cell_layout = this.nodes.get(cell as usize).and_then(|c| c.layout)?;
11968            let size = this.rounded_layout(cell_layout).size;
11969            let list = this.nodes[key as usize].list.as_ref().expect("list");
11970            let mut main_at = list.to_content(at, row.max(main_of(size)));
11971            let mut x = x;
11972            if outer.is_some() {
11973                main_at += inset.0;
11974                x += inset.1;
11975            }
11976            let cell_cross = if horizontal { size.height } else { size.width };
11977            x = list.align_cross(x, width, cell_cross);
11978            let frame = if horizontal {
11979                rect(main_at, x, size.width, cell_cross)
11980            } else {
11981                rect(x, main_at, cell_cross, size.height)
11982            };
11983            this.set_frame(cell, frame);
11984            this.set_left_behind(cell, false);
11985            this.set_spare(cell, false);
11986            if std::mem::take(&mut this.nodes[cell as usize].relaid) {
11987                // A cell that waits to be made (`pace.rs`) made none of
11988                // its views: they wait with it, placed as culled views
11989                // are, so the ones that show are made when the cell is,
11990                // not behind every view that waits out of sight.
11991                let waits = {
11992                    let node = &this.nodes[cell as usize];
11993                    !node.created && node.culled
11994                };
11995                let children = std::mem::take(&mut this.nodes[cell as usize].children);
11996                for &child in &children {
11997                    if waits {
11998                        let node = &mut this.nodes[child as usize];
11999                        if !node.created && !node.is_layout_root() {
12000                            node.culled = true;
12001                        }
12002                    }
12003                    this.emit_frames(child);
12004                }
12005                this.nodes[cell as usize].children = children;
12006                this.update_overflow(cell);
12007                this.cells_framed = true;
12008            }
12009            Some(main_of(size))
12010        };
12011        // In a terminal the columns are whole Cells of the width the cells
12012        // were laid out at (`layout_cells`: without the scroll bar's
12013        // column).
12014        let unit = self
12015            .layout
12016            .grid()
12017            .map(|g| if horizontal { g.height } else { g.width });
12018        let columns_cross = {
12019            let laid = self.nodes[key as usize]
12020                .list
12021                .as_ref()
12022                .expect("list")
12023                .cells_cross;
12024            if unit.is_some() && laid.is_finite() {
12025                laid
12026            } else {
12027                cross
12028            }
12029        };
12030        let mut placed = list_motion::Placed::default();
12031        for &(index, cell) in &ready {
12032            let list = self.nodes[key as usize].list.as_ref().expect("list");
12033            let (at, row) = (list.item_at(index), list.row_extent(index));
12034            let column = list.column(columns_cross, list.column_of(index), unit);
12035            let Some(size) = place(self, cell, at, row, column) else {
12036                continue;
12037            };
12038            let list = self.nodes[key as usize].list.as_mut().expect("list");
12039            if list.place(index) {
12040                placed.new.push(cell);
12041            } else {
12042                placed.kept.push(cell);
12043            }
12044            let list = self.nodes[key as usize].list.as_ref().expect("list");
12045            if sticky && list.sticky.binary_search(&index).is_ok() {
12046                let range = list.sticky_range(index, self.nodes[cell as usize].id, size);
12047                sticky_cells.push(range);
12048            }
12049        }
12050        let full = self.nodes[key as usize]
12051            .list
12052            .as_ref()
12053            .expect("list")
12054            .full_width(columns_cross);
12055        for (extra, at) in extras
12056            .iter()
12057            .zip([blocks.header, blocks.footer, blocks.body])
12058        {
12059            if extra.cell != u32::MAX && place(self, extra.cell, at, 0.0, full).is_some() {
12060                placed.kept.push(extra.cell);
12061            }
12062        }
12063        self.cells_scratch = ready;
12064
12065        sticky_cells.sort_by_key(|c| c.cell);
12066        let list = self.nodes[key as usize].list.as_mut().expect("list");
12067        if let Some(o) = &outer {
12068            // The view around the list pins them, with its other lists'.
12069            if sticky_cells != list.sent_sticky {
12070                let old = std::mem::replace(&mut list.sent_sticky, sticky_cells);
12071                self.page_sticky_changed(key, o.view, &old);
12072            }
12073        } else if sticky_cells != list.sent_sticky {
12074            // Sent at the end of the commit in one set with the other
12075            // views it pins (its built-in bar, its sticky views, its lists'
12076            // rows in its viewport): a set of its rows alone would drop the
12077            // others and raise its rows above its bar.
12078            list.sent_sticky = sticky_cells;
12079            self.sticky_views.push(key);
12080        }
12081
12082        if let Some(o) = &outer {
12083            // The view around the list scrolls (the commit sends it at
12084            // its end; a scroll to an offset after the anchoring, which
12085            // it supersedes), and the list takes its new length in layout.
12086            if anchor != 0.0 {
12087                self.ask_outer(o.view, None, anchor);
12088            }
12089            if outer_to.is_some() {
12090                self.ask_outer(o.view, outer_to, 0.0);
12091            }
12092            self.sync_spacer(key, false);
12093            return;
12094        }
12095        let content = if horizontal {
12096            size_pt(content_len, cross)
12097        } else {
12098            size_pt(cross, content_len)
12099        };
12100        // Platforms clamp the offset to the content: grow the content
12101        // before scrolling, scroll before shrinking it.
12102        let old_len = self.nodes[key as usize]
12103            .scroll
12104            .as_ref()
12105            .and_then(|s| s.content)
12106            .map_or(0.0, |c| if horizontal { c.width.0 } else { c.height.0 });
12107        let list = self.nodes[key as usize].list.as_mut().expect("list");
12108        if anchor != 0.0 {
12109            list.issue_scroll_by(anchor);
12110        }
12111        for (offset, animated) in scrolls_to {
12112            list.issue_scroll_to(offset, animated);
12113        }
12114        let scroll_by = (anchor != 0.0).then(|| {
12115            let (dx, dy) = if horizontal {
12116                (Points(anchor), Points::ZERO)
12117            } else {
12118                (Points::ZERO, Points(anchor))
12119            };
12120            MountItem::ScrollBy { id, dx, dy }
12121        });
12122        // Platforms clamp the offset to the content and the viewport:
12123        // scroll before the viewport grows or the content shrinks, and
12124        // after the content grows (a shrinking viewport's frame comes
12125        // first anyway).
12126        let frame_at = grew
12127            .then(|| {
12128                self.mount
12129                    .iter()
12130                    .position(|m| matches!(m, MountItem::Frame { id: f, .. } if *f == id))
12131            })
12132            .flatten();
12133        match (scroll_by, frame_at) {
12134            // The viewport and the content both grow (rows arriving as a
12135            // placeholder beside the list goes away): the content first,
12136            // then the scroll, then the frame. A frame grown over the old
12137            // content clamps the scroll back to its start.
12138            (Some(item), Some(at)) if content_len > old_len => {
12139                self.set_scroll_content(key, content);
12140                match self
12141                    .mount
12142                    .iter()
12143                    .rposition(|m| matches!(m, MountItem::ScrollContent { id: c, .. } if *c == id))
12144                {
12145                    Some(queued) if queued > at => {
12146                        let grown = self.mount.remove(queued);
12147                        self.mount.insert(at, grown);
12148                        self.mount.insert(at + 1, item);
12149                    }
12150                    _ => self.mount.insert(at, item),
12151                }
12152            }
12153            (Some(item), Some(at)) => {
12154                self.mount.insert(at, item);
12155                self.set_scroll_content(key, content);
12156            }
12157            (Some(item), None) if content_len < old_len => {
12158                self.mount.push(item);
12159                self.set_scroll_content(key, content);
12160            }
12161            (item, _) => {
12162                self.set_scroll_content(key, content);
12163                self.mount.extend(item);
12164            }
12165        }
12166        if motion {
12167            self.move_list_cells(key, id, horizontal, anchor, placed);
12168        }
12169    }
12170}
12171
12172/// How far out of sight unbound list cells are moved.
12173const HIDDEN: f32 = 1.0e6;
12174
12175/// Where `x` is in `items`, looked for from both ends at once, and how
12176/// many items were looked at: few for an item near either end.
12177fn position_from_ends<T: PartialEq>(items: &[T], x: &T) -> Option<(usize, usize)> {
12178    let (mut front, mut back) = (0, items.len());
12179    while front < back {
12180        if items[front] == *x {
12181            return Some((front, 2 * front + 1));
12182        }
12183        back -= 1;
12184        if items[back] == *x {
12185            return Some((back, 2 * (items.len() - back)));
12186        }
12187        front += 1;
12188    }
12189    None
12190}
12191
12192/// Where `x` is in `items`, looked for outward from `near` (or the last
12193/// item, past the end), and how many items were looked at: few when it is
12194/// near.
12195fn position_near<T: PartialEq>(items: &[T], x: &T, near: usize) -> Option<(usize, usize)> {
12196    let near = near.min(items.len().checked_sub(1)?);
12197    let mut looked = 0;
12198    // Every item is at most `len - 1` from `near`.
12199    for distance in 0..items.len() {
12200        let below = near.checked_sub(distance);
12201        let above = (distance > 0)
12202            .then_some(near + distance)
12203            .filter(|&i| i < items.len());
12204        for i in [below, above].into_iter().flatten() {
12205            looked += 1;
12206            if items[i] == *x {
12207                return Some((i, looked));
12208            }
12209        }
12210    }
12211    None
12212}
12213
12214/// The content box (inside padding and border) of a laid-out node.
12215/// Taffy's rounding of a coordinate, to the nearest device pixel of
12216/// `ratio` pixels per point rather than to whole points: on a display whose
12217/// ratio is not a whole number (Android's 2.625) whole points fall between
12218/// pixels, so the platform rounding each view's frame to pixels in its parent
12219/// would make a child a pixel taller than its parent (a scroll view then cuts
12220/// its last row of pixels off).
12221fn round(value: f32, ratio: f32) -> f32 {
12222    (pixel(value, ratio) / f64::from(ratio)) as f32
12223}
12224
12225/// The device pixel [`round`] puts `value` on, counted from the root's
12226/// origin. `value` is an `f32` sum of offsets, a hair off the position it
12227/// stands for, and `/ ratio` is never exact at a fractional ratio: snapped
12228/// to a 64th of a pixel first, an edge on a half pixel (a 28 point row at
12229/// 2.625 is 73.5 pixels) always rounds the same way, wherever a scroll put
12230/// it, instead of taking one pixel or the next by that hair.
12231fn pixel(value: f32, ratio: f32) -> f64 {
12232    (snapped(value, ratio) + 0.5).floor()
12233}
12234
12235/// `value` in device pixels, snapped to a 64th of a pixel ([`pixel`]).
12236fn snapped(value: f32, ratio: f32) -> f64 {
12237    let p = f64::from(value) * f64::from(ratio);
12238    (p * 64.0).round() / 64.0
12239}
12240
12241/// The device pixels the edges of a box from `start`, `len` long, are on:
12242/// each edge's [`pixel`], but for a box under a pixel thick whose edges
12243/// both round to one pixel. It would take none (half a point at one pixel
12244/// per point vanished wherever it ended on a half pixel), and takes the
12245/// pixel on the side of that edge most of it is on instead: a rule against
12246/// its parent's edge stays inside the parent, and no other box's edge
12247/// moves, so neighbours still meet (the rule covers a pixel of one). A
12248/// length under a 64th of a pixel (zero but for `f32`) still takes none.
12249fn edges(start: f32, len: f32, ratio: f32) -> (f64, f64) {
12250    let end = start + len;
12251    let (from, to) = (pixel(start, ratio), pixel(end, ratio));
12252    let (a, b) = (snapped(start, ratio), snapped(end, ratio));
12253    if from != to || b <= a {
12254        (from, to)
12255    } else if a + b < 2.0 * from {
12256        (from - 1.0, from)
12257    } else {
12258        (from, from + 1.0)
12259    }
12260}
12261
12262/// Where the box a node is placed in (the view around it, or its
12263/// containing block) is in its layout root: unrounded, as Taffy's rounding
12264/// carries it down ([`Core::layout_origin`]), and whether [`edges`] put a
12265/// leading edge on the pixel before the one that position rounds to (a box
12266/// under a pixel thick mostly before it). A node's frame is from those
12267/// edges, so the children of such a box are on it.
12268#[derive(Clone, Copy, Debug, Default, PartialEq)]
12269struct Origin {
12270    at: taffy::Point<f32>,
12271    back: taffy::Point<bool>,
12272}
12273
12274impl Origin {
12275    /// The box at `at`, `size` large, rounded to `ratio`.
12276    fn of(at: taffy::Point<f32>, size: taffy::Size<f32>, ratio: taffy::Size<f32>) -> Origin {
12277        let back =
12278            |start: f32, len: f32, ratio: f32| edges(start, len, ratio).0 < pixel(start, ratio);
12279        Origin {
12280            at,
12281            back: taffy::Point {
12282                x: back(at.x, size.width, ratio.width),
12283                y: back(at.y, size.height, ratio.height),
12284            },
12285        }
12286    }
12287
12288    /// The device pixels its leading edges are on.
12289    fn lead(self, ratio: taffy::Size<f32>) -> taffy::Point<f64> {
12290        taffy::Point {
12291            x: pixel(self.at.x, ratio.width) - f64::from(u8::from(self.back.x)),
12292            y: pixel(self.at.y, ratio.height) - f64::from(u8::from(self.back.y)),
12293        }
12294    }
12295
12296    /// The offset in points from its leading edges to `to`'s, from the
12297    /// whole pixels between them ([`span`]).
12298    fn to(self, to: Origin, ratio: taffy::Size<f32>) -> taffy::Point<f32> {
12299        let (from, to) = (self.lead(ratio), to.lead(ratio));
12300        taffy::Point {
12301            x: ((to.x - from.x) / f64::from(ratio.width)) as f32,
12302            y: ((to.y - from.y) / f64::from(ratio.height)) as f32,
12303        }
12304    }
12305}
12306
12307/// The distance in points from `from` to `to`, each rounded to a device
12308/// pixel ([`round`]): computed from the whole pixels between them, so the
12309/// same pixels give the same `f32` wherever they are. The difference of two
12310/// rounded points (`round(to) - round(from)`) would differ in its last bits
12311/// as a scroll moves the edges, and every frame in a scrolled region would
12312/// be sent again unchanged.
12313fn span(from: f32, to: f32, ratio: f32) -> f32 {
12314    ((pixel(to, ratio) - pixel(from, ratio)) / f64::from(ratio)) as f32
12315}
12316
12317/// The width a text block is typeset in: the width Taffy measured its lines
12318/// in (`measured`, its unrounded content box), when its box rounded to
12319/// device pixels (`rounded`) is within a pixel of it. A box whose edges fall
12320/// between pixels can round a pixel narrower than the text was measured in
12321/// (a list item's content 21 points in, 57.75 pixels at 2.75): typeset in
12322/// that, a line that fit by less than the pixel wrapped once more than its
12323/// box was made tall for, and its last line ran over the block after it (a
12324/// browser) or was cut (a platform that clips text to its view). Typeset in
12325/// the width it was measured in, the lines are the ones its height has; the
12326/// text reaches less than a pixel past its rounded box.
12327fn typeset_width(rounded: Points, measured: Points, ratio: f32) -> Points {
12328    if measured.0.is_finite() && ((measured.0 - rounded.0) * ratio).abs() < 1.0 {
12329        measured
12330    } else {
12331        rounded
12332    }
12333}
12334
12335/// `value` rounded up to a device pixel of `ratio` pixels per point. A
12336/// value that is a whole pixel but for `f32` (`56.0 / 2.625 * 2.625` is
12337/// `56.000004`) stays that pixel; a value really over one gets the next
12338/// pixel even when it is over by less than the tolerance: a text measured
12339/// `78.000_49` points wide (a PingFang glyph's 1020 / 1028 em beside SF's
12340/// 1/128 point advances) wraps in a box of 78.
12341fn ceil_to_pixel(value: Points, ratio: f32) -> Points {
12342    let up = (value.0 * ratio - 1.0e-3).ceil().max(0.0) / ratio;
12343    Points(if up < value.0 { up + 1.0 / ratio } else { up })
12344}
12345
12346/// A scroll view's scrollable extent from its rounded layout. The overflow
12347/// rectangle is CSS's scrollable overflow, measured from the padding box
12348/// origin: a scroll container's in-flow content reaches its trailing
12349/// padding there (an empty one is its padding), and an absolutely
12350/// positioned child its own box, so only the leading border is added. The
12351/// cross axis keeps the viewport's length, which the content spans (a
12352/// vertical scroll view's width, a horizontal one's height). The main axis
12353/// is the content's own extent, below the viewport too: a platform adds its
12354/// own insets around the viewport (iOS's bars under a large title), and a
12355/// floor there gives it a range to scroll over content that fits.
12356fn scroll_extent(l: &taffy::Layout, horizontal: bool) -> Size<Points> {
12357    let o = l.scrollable_overflow_rect;
12358    let (width, height) = (l.border.left + o.right(), l.border.top + o.bottom());
12359    if horizontal {
12360        size_pt(width, height.max(l.size.height))
12361    } else {
12362        size_pt(width.max(l.size.width), height)
12363    }
12364}
12365
12366/// `layout` rounded as Taffy's rounding pass (`taffy::round_layout`) rounds
12367/// it, to device pixels of `ratio` pixels per point on each axis
12368/// ([`round`]; on a grid surface a Cell is a pixel: [`terminal_layout::Grid::ratio`]),
12369/// `origin` being the node around it in its layout root (its containing
12370/// block): edges are rounded where they are in the root, so adjacent
12371/// views stay adjacent, and a box under a pixel thick keeps one ([`edges`]).
12372/// The location is from the leading edges of the box around it as they
12373/// were rounded. The core rounds itself: Taffy's pass reaches the
12374/// absolutely positioned nodes through their containing block's list,
12375/// which it can leave holding removed nodes (a panic) or never fill (a
12376/// hidden subtree's), while here every node is reached through its parent,
12377/// its logical parent; out-of-flow offsets use their Taffy containing block.
12378fn rounded(layout: &taffy::Layout, origin: Origin, ratio: taffy::Size<f32>) -> taffy::Layout {
12379    let mut out = *layout;
12380    let (x, y) = (
12381        origin.at.x + layout.location.x,
12382        origin.at.y + layout.location.y,
12383    );
12384    let (rx, ry) = (ratio.width, ratio.height);
12385    let (x0, x1) = edges(x, layout.size.width, rx);
12386    let (y0, y1) = edges(y, layout.size.height, ry);
12387    let lead = origin.lead(ratio);
12388    let points = |pixels: f64, ratio: f32| (pixels / f64::from(ratio)) as f32;
12389    out.location.x = points(x0 - lead.x, rx);
12390    out.location.y = points(y0 - lead.y, ry);
12391    out.size.width = points(x1 - x0, rx);
12392    out.size.height = points(y1 - y0, ry);
12393    out.scrollbar_size.width = round(layout.scrollbar_size.width, rx);
12394    out.scrollbar_size.height = round(layout.scrollbar_size.height, ry);
12395    out.border.left = span(x, x + layout.border.left, rx);
12396    out.border.right = span(
12397        x + layout.size.width - layout.border.right,
12398        x + layout.size.width,
12399        rx,
12400    );
12401    out.border.top = span(y, y + layout.border.top, ry);
12402    out.border.bottom = span(
12403        y + layout.size.height - layout.border.bottom,
12404        y + layout.size.height,
12405        ry,
12406    );
12407    // Padding is rounded from the border's inner edge, not from the outer
12408    // edge as the border is: rounded each from the outer edge, a border and
12409    // a padding of 1.5 and 6 points at 1.1 pixels per point took 2 + 7
12410    // pixels where their 8.25 pixels round to 8, and a text measured to fit
12411    // its content box (a label as wide as its content) wrapped in the pixel
12412    // or two its insets took from it. Rounded at its edges, the content box
12413    // is as many pixels as the text was measured.
12414    let (left, right) = (
12415        x + layout.border.left,
12416        x + layout.size.width - layout.border.right,
12417    );
12418    let (top, bottom) = (
12419        y + layout.border.top,
12420        y + layout.size.height - layout.border.bottom,
12421    );
12422    out.padding.left = span(left, left + layout.padding.left, rx);
12423    out.padding.right = span(right - layout.padding.right, right, rx);
12424    out.padding.top = span(top, top + layout.padding.top, ry);
12425    out.padding.bottom = span(bottom - layout.padding.bottom, bottom, ry);
12426    let o = layout.scrollable_overflow_rect;
12427    // Taffy packs the scroll-origin directions into the rectangle's signs;
12428    // keep them, and keep the origin inside the rounded rectangle.
12429    out.scrollable_overflow_rect = taffy::ScrollableOverflow::new(
12430        taffy::Rect {
12431            left: points(pixel(x + o.left(), rx) - x0, rx).min(0.0),
12432            right: points(pixel(x + o.right(), rx) - x0, rx).max(0.0),
12433            top: points(pixel(y + o.top(), ry) - y0, ry).min(0.0),
12434            bottom: points(pixel(y + o.bottom(), ry) - y0, ry).max(0.0),
12435        },
12436        o.is_reversed(),
12437    );
12438    out
12439}
12440
12441fn content_box(l: &taffy::Layout) -> Bounds<Points> {
12442    rect(
12443        l.padding.left + l.border.left,
12444        l.padding.top + l.border.top,
12445        (l.size.width - l.padding.left - l.padding.right - l.border.left - l.border.right).max(0.0),
12446        (l.size.height - l.padding.top - l.padding.bottom - l.border.top - l.border.bottom)
12447            .max(0.0),
12448    )
12449}
12450
12451/// An image's minimum and maximum content-box sizes ([`image_size`]).
12452#[derive(Default)]
12453struct ImageLimits {
12454    min: taffy::Size<Option<f32>>,
12455    max: taffy::Size<Option<f32>>,
12456}
12457
12458impl ImageLimits {
12459    fn width(&self, w: f32) -> f32 {
12460        clamp_side(w, self.min.width, self.max.width)
12461    }
12462
12463    fn height(&self, h: f32) -> f32 {
12464        clamp_side(h, self.min.height, self.max.height)
12465    }
12466}
12467
12468fn clamp_side(v: f32, min: Option<f32>, max: Option<f32>) -> f32 {
12469    let v = max.map_or(v, |max| v.min(max));
12470    min.map_or(v, |min| v.max(min))
12471}
12472
12473/// Size of an image with a known natural size: fill a known dimension and
12474/// keep the aspect ratio for the other, within `limits`.
12475fn image_size(
12476    natural: Size<Points>,
12477    w: Option<f32>,
12478    h: Option<f32>,
12479    limits: &ImageLimits,
12480) -> taffy::Size<f32> {
12481    let ratio = if natural.height > Points::ZERO {
12482        natural.width / natural.height
12483    } else {
12484        1.0
12485    };
12486    let (width, height) = match (w, h) {
12487        (Some(w), None) => (w, limits.height(w / ratio)),
12488        (None, Some(h)) => (limits.width(h * ratio), h),
12489        (Some(w), Some(h)) => (w, h),
12490        (None, None) => {
12491            let width = limits.width(natural.width.0);
12492            let height = width / ratio;
12493            let clamped = limits.height(height);
12494            if clamped == height {
12495                (width, height)
12496            } else {
12497                (limits.width(clamped * ratio), clamped)
12498            }
12499        }
12500    };
12501    taffy::Size { width, height }
12502}
12503
12504/// Measures a text block: per-node cache, then the shared content-addressed
12505/// cache, then the platform engine.
12506/// Keeps a Rust component's text block's final layout for its
12507/// [`crate::Text::on_text_layout`] listener, which hears it with the
12508/// block's `TextLayout` event ([`Core::component_event`]). Only the core's
12509/// nodes (odd ids, the components'): JS hears the lines.
12510fn keep_geometry(
12511    engine: &Option<Rc<dyn crate::text::GeometryEngine>>,
12512    geometries: &mut rustc_hash::FxHashMap<NodeId, crate::text::TextGeometry>,
12513    id: NodeId,
12514    layout: &TextLayout,
12515    text: &Arc<AttributedText>,
12516    spacers: &[u32],
12517) {
12518    if let Some(engine) = engine.as_ref().filter(|_| id % 2 == 1) {
12519        geometries.insert(
12520            id,
12521            crate::text::TextGeometry::new(engine.clone(), layout.clone(), text.clone(), spacers),
12522        );
12523    }
12524}
12525
12526/// The lines of `layout` with their characters.
12527fn text_lines<M: TextEngine>(
12528    engine: &M,
12529    text: &AttributedText,
12530    layout: &TextLayout,
12531) -> EventPayload {
12532    let units: Vec<u16> = text.text.encode_utf16().collect();
12533    let mut lines = engine.lines(layout);
12534    for line in &mut lines {
12535        let (start, end) = (line.start as usize, (line.end as usize).min(units.len()));
12536        if start < end {
12537            line.text = String::from_utf16_lossy(&units[start..end]);
12538        }
12539    }
12540    EventPayload::TextLayout(lines)
12541}
12542
12543/// `text` with its fonts scaled down (to at least `min`) until it fits
12544/// `size` within its line limit: the largest scale that fits, by
12545/// bisection.
12546fn fitted<M: TextEngine>(
12547    engine: &M,
12548    text: &AttributedText,
12549    alignments: &crate::AttachmentAlignments,
12550    options: &crate::TextOptions,
12551    size: Size<Points>,
12552    min: f32,
12553) -> AttributedText {
12554    let scaled = |scale: f32| {
12555        let mut t = text.clone();
12556        if let Some(strut) = &mut t.paragraph_strut {
12557            strut.font_size *= scale;
12558            strut.line_height *= scale;
12559        }
12560        for span in &mut t.spans {
12561            span.style.font_size *= scale;
12562            span.style.line_height *= scale;
12563            span.style.letter_spacing *= scale;
12564        }
12565        t
12566    };
12567    let fits = |t: &AttributedText| {
12568        // Untruncated, the text must be no taller than its truncated self
12569        // (nothing cut) and than the box.
12570        let all = AttributedText {
12571            max_lines: 0,
12572            ..t.clone()
12573        };
12574        let full = engine.measure(
12575            &engine.prepare_with(&all, alignments, options),
12576            Some(size.width),
12577        );
12578        let limited = if t.max_lines > 0 {
12579            engine
12580                .measure(
12581                    &engine.prepare_with(t, alignments, options),
12582                    Some(size.width),
12583                )
12584                .height
12585        } else {
12586            Points(f32::INFINITY)
12587        };
12588        full.height <= size.height.min(limited) + Points(0.5)
12589            && full.width <= size.width + Points(0.5)
12590    };
12591    if fits(text) {
12592        return text.clone();
12593    }
12594    let (mut lo, mut hi) = (min, 1.0f32);
12595    if !fits(&scaled(lo)) {
12596        return scaled(lo);
12597    }
12598    for _ in 0..7 {
12599        let mid = (lo + hi) / 2.0;
12600        if fits(&scaled(mid)) {
12601            lo = mid;
12602        } else {
12603            hi = mid;
12604        }
12605    }
12606    scaled(lo)
12607}
12608
12609/// Min-content keeps every unbreakable segment intact. Measure the styled
12610/// segments with the platform engine rather than estimating glyph advances.
12611/// The size a text far from the screen is laid out at until it is
12612/// measured (`cull.rs`): its characters at an average advance of its
12613/// largest font, broken into lines at `max_width`, each line as high as
12614/// its line height.
12615fn estimate_text(text: &AttributedText, max_width: Option<f32>) -> Size<Points> {
12616    let (_, line) = text_metrics(text);
12617    let mut width = 0.0f32;
12618    let mut lines = 0u32;
12619    for paragraph in text.text.split('\n') {
12620        let w = estimate_line(text, paragraph).0;
12621        width = width.max(match max_width {
12622            Some(max) => w.min(max),
12623            None => w,
12624        });
12625        lines += match max_width {
12626            Some(max) if max > 0.0 && !text.no_wrap => (w / max).ceil().max(1.0) as u32,
12627            _ => 1,
12628        };
12629    }
12630    if text.max_lines > 0 {
12631        lines = lines.min(text.max_lines);
12632    }
12633    Size::new(Points(width.ceil()), Points((lines as f32 * line).ceil()))
12634}
12635
12636/// The estimated advance of `run`, in `text`'s largest font: wide
12637/// characters (CJK, emoji) a font size each, others a little over half.
12638fn estimate_line(text: &AttributedText, run: &str) -> Points {
12639    let (size, _) = text_metrics(text);
12640    Points(
12641        run.chars()
12642            .map(|c| {
12643                if c as u32 >= 0x2e80 {
12644                    size
12645                } else {
12646                    size * 0.55
12647                }
12648            })
12649            .sum(),
12650    )
12651}
12652
12653/// `text`'s largest font size and the line height it gives (the style's,
12654/// or 1.2 of the font size).
12655fn text_metrics(text: &AttributedText) -> (f32, f32) {
12656    let (font, line) = text.approx_metrics();
12657    (font.0, line.0)
12658}
12659
12660fn min_content_width<M: TextEngine>(
12661    engine: &M,
12662    cache: &mut MeasureCache,
12663    cx: &mut TextContext<M::Prepared>,
12664) -> Points {
12665    if let Some(width) = cx.min_content {
12666        return width;
12667    }
12668    if cx.deferred {
12669        // Its longest word, estimated (not kept: measured once it is made).
12670        return cx
12671            .text
12672            .text
12673            .split_whitespace()
12674            .map(|word| estimate_line(&cx.text, word))
12675            .fold(Points::ZERO, Points::max);
12676    }
12677    let text = &cx.text;
12678    let mut offsets = Vec::with_capacity(text.text.chars().count() + 1);
12679    let mut utf16 = 0u32;
12680    for (byte, ch) in text.text.char_indices() {
12681        offsets.push((utf16, byte));
12682        utf16 += ch.len_utf16() as u32;
12683    }
12684    offsets.push((utf16, text.text.len()));
12685    let byte_at = |offset: u32| {
12686        offsets[offsets
12687            .binary_search_by_key(&offset, |&(at, _)| at)
12688            .unwrap()]
12689        .1
12690    };
12691    let mut start = 0usize;
12692    let mut width = Points::ZERO;
12693    for (end, _) in unicode_linebreak::linebreaks(&text.text) {
12694        let word = text.text[start..end].trim_end_matches([' ', '\t', '\n', '\r', '\u{000c}']);
12695        let from = offsets[offsets
12696            .binary_search_by_key(&start, |&(_, byte)| byte)
12697            .unwrap()]
12698        .0;
12699        let to = from + word.encode_utf16().count() as u32;
12700        if from < to {
12701            let mut part = AttributedText {
12702                no_wrap: true,
12703                rtl: text.rtl,
12704                writing_direction: text.writing_direction,
12705                ..Default::default()
12706            };
12707            for span in &text.spans {
12708                let (lo, hi) = (from.max(span.start), to.min(span.end));
12709                if lo < hi {
12710                    part.push(&text.text[byte_at(lo)..byte_at(hi)], span.style);
12711                }
12712            }
12713            for attachment in &text.attachments {
12714                if (from..to).contains(&attachment.index) {
12715                    let mut attachment = *attachment;
12716                    attachment.index -= from;
12717                    part.attachments.push(attachment);
12718                }
12719            }
12720            let hash = part.layout_hash();
12721            let measured = cache.get(hash, None).unwrap_or_else(|| {
12722                let measured = engine.measure(&engine.prepare(&part), None);
12723                cache.insert(hash, None, measured);
12724                measured
12725            });
12726            width = width.max(measured.width);
12727        }
12728        start = end;
12729    }
12730    cx.min_content = Some(width);
12731    width
12732}
12733
12734/// What measures the leaves in every layout pass ([`measure_leaf`]): one
12735/// closure type for all of them, so Taffy's algorithms, generic over it,
12736/// are made once.
12737fn leaf_measure<'a, M: TextEngine>(
12738    engine: &'a M,
12739    cache: &'a mut MeasureCache,
12740) -> impl FnMut(
12741    taffy::LayoutInput,
12742    LayoutId,
12743    Option<&mut LeafContext<M::Prepared>>,
12744    &taffy::Style,
12745    layout_tree::Aligned,
12746) -> taffy::LayoutOutput
12747+ 'a {
12748    move |input, _, cx, style, aligned| measure_leaf(engine, cache, input, cx, style, aligned)
12749}
12750
12751/// A leaf's layout (`taffy::compute_leaf_layout`): Taffy resolves its
12752/// style's sizes, padding, border, minimums, maximums and aspect ratio;
12753/// only its content (a text, an image's natural size, a native
12754/// component's own size) is measured here. A text aligned by baseline gives
12755/// its first line's baseline too ([`text_baseline`]): Taffy aligns a flex
12756/// row's items by baseline (`align-items: baseline`) with it, and by their
12757/// bottom edges without it.
12758fn measure_leaf<M: TextEngine>(
12759    engine: &M,
12760    cache: &mut MeasureCache,
12761    input: taffy::LayoutInput,
12762    mut cx: Option<&mut LeafContext<M::Prepared>>,
12763    style: &taffy::Style,
12764    aligned: layout_tree::Aligned,
12765) -> taffy::LayoutOutput {
12766    let mut output = measure_leaf_size(engine, cache, input, cx.as_deref_mut(), style);
12767    // Taffy asks for baselines by laying the items out (its baseline pass),
12768    // so measuring alone typesets nothing more.
12769    if aligned == layout_tree::Aligned::Baseline
12770        && input.run_mode == taffy::RunMode::PerformLayout
12771        && let Some(LeafContext::Text(cx)) = cx
12772    {
12773        use taffy::util::ResolveOrZero;
12774        let resolve = |_: taffy::CalcHandle, _: f32| 0.0;
12775        let padding = style
12776            .padding
12777            .resolve_or_zero(input.parent_size.width, resolve);
12778        let border = style
12779            .border
12780            .resolve_or_zero(input.parent_size.width, resolve);
12781        let width = output.size.width - padding.left - padding.right - border.left - border.right;
12782        if let Some(baseline) = text_baseline(engine, cx, width.max(0.0)) {
12783            output.baselines.first = Some(padding.top + border.top + baseline.0);
12784        }
12785    }
12786    output
12787}
12788
12789/// How far below the top of `cx`'s text its first line's baseline is, laid
12790/// out `width` wide ([`TextEngine::first_baseline`]); none for a text
12791/// measured by an estimate (`cull.rs`), which is not typeset.
12792fn text_baseline<M: TextEngine>(
12793    engine: &M,
12794    cx: &mut TextContext<M::Prepared>,
12795    width: f32,
12796) -> Option<Points> {
12797    if cx.deferred {
12798        return None;
12799    }
12800    if let Some((w, baseline)) = cx.baseline
12801        && w == width
12802    {
12803        return baseline;
12804    }
12805    let prepared = cx
12806        .prepared
12807        .get_or_insert_with(|| engine.prepare_with(&cx.text, &cx.alignments, &cx.options));
12808    let baseline = engine.first_baseline(prepared, Points(width));
12809    cx.baseline = Some((width, baseline));
12810    baseline
12811}
12812
12813/// A leaf's size ([`measure_leaf`]).
12814fn measure_leaf_size<M: TextEngine>(
12815    engine: &M,
12816    cache: &mut MeasureCache,
12817    input: taffy::LayoutInput,
12818    cx: Option<&mut LeafContext<M::Prepared>>,
12819    style: &taffy::Style,
12820) -> taffy::LayoutOutput {
12821    use taffy::{MaybeResolve as _, ResolveOrZero as _};
12822    // An input's text scrolls within its maximum height: its content is
12823    // never taller than its content box can be. Taffy leaves the maximum out
12824    // of the content size it asks for a flex basis (`SizingMode::ContentSize`)
12825    // and a column container sizes itself from the flex bases, so without
12826    // this a long value grew the input's parent past the input.
12827    let input_max_height = match &cx {
12828        Some(LeafContext::Text(cx)) if cx.field.is_some() => {
12829            let parent = input.parent_size;
12830            let max: Option<f32> = style
12831                .max_size
12832                .height
12833                .maybe_resolve(parent.height, |_, _| 0.0);
12834            max.map(|max| {
12835                let inset = (style.padding.resolve_or_zero(parent.width, |_, _| 0.0)
12836                    + style.border.resolve_or_zero(parent.width, |_, _| 0.0))
12837                .vertical_axis_sum();
12838                match style.box_sizing {
12839                    taffy::BoxSizing::BorderBox => (max - inset).max(0.0),
12840                    taffy::BoxSizing::ContentBox => max,
12841                }
12842            })
12843        }
12844        _ => None,
12845    };
12846    // Taffy hands a size it asks for (`RunMode::ComputeSize`) the known
12847    // sizes of the border box, as a stretched item's width is, and the
12848    // available space of the content box. What is measured fits the
12849    // content box: a text measured as wide as its border box wraps fewer
12850    // lines than it is laid out in, and the platforms cut the rest.
12851    let inset = {
12852        let parent = input.parent_size.width;
12853        let mut inset = (style.padding.resolve_or_zero(parent, |_, _| 0.0)
12854            + style.border.resolve_or_zero(parent, |_, _| 0.0))
12855        .sum_axes();
12856        // Scroll bars' gutters, as Taffy reserves them.
12857        if style.overflow.y == taffy::Overflow::Scroll {
12858            inset.width += style.scrollbar_width;
12859        }
12860        if style.overflow.x == taffy::Overflow::Scroll {
12861            inset.height += style.scrollbar_width;
12862        }
12863        inset
12864    };
12865    let image = matches!(cx, Some(LeafContext::Image(_)));
12866    // An image with a natural size keeps its aspect ratio within its
12867    // minimum and maximum sizes, as CSS's replaced elements do: a 60 × 30
12868    // image with a 40 point maximum width is 40 × 20, not 40 × 30. Taffy
12869    // clamps the measured size afterwards, one axis at a time.
12870    let image_limits = match &cx {
12871        Some(LeafContext::Image(Some(_))) => {
12872            let parent = input.parent_size;
12873            let content = |v: Option<f32>, inset: f32| {
12874                v.map(|v| match style.box_sizing {
12875                    taffy::BoxSizing::BorderBox => (v - inset).max(0.0),
12876                    taffy::BoxSizing::ContentBox => v,
12877                })
12878            };
12879            let inset = (style.padding.resolve_or_zero(parent.width, |_, _| 0.0)
12880                + style.border.resolve_or_zero(parent.width, |_, _| 0.0))
12881            .sum_axes();
12882            let min: taffy::Size<Option<f32>> = style.min_size.maybe_resolve(parent, |_, _| 0.0);
12883            let max: taffy::Size<Option<f32>> = style.max_size.maybe_resolve(parent, |_, _| 0.0);
12884            ImageLimits {
12885                min: taffy::Size {
12886                    width: content(min.width, inset.width),
12887                    height: content(min.height, inset.height),
12888                },
12889                max: taffy::Size {
12890                    width: content(max.width, inset.width),
12891                    height: content(max.height, inset.height),
12892                },
12893            }
12894        }
12895        _ => ImageLimits::default(),
12896    };
12897    let mut output = taffy::compute_leaf_layout(
12898        input,
12899        style,
12900        |_, _| 0.0,
12901        |known, available| {
12902            let known = taffy::Size {
12903                width: known.width.map(|w| (w - inset.width).max(0.0)),
12904                height: known.height.map(|h| (h - inset.height).max(0.0)),
12905            };
12906            // The space Taffy offers the content box is the space around
12907            // the box less its padding and border, negative where that
12908            // space is narrower than they are (a column squeezed while it
12909            // resizes). The content then has no room, as with a known
12910            // size: an input measured as wide as that negative space gave
12911            // Taffy a negative overflow, which its debug assertions reject.
12912            let available = taffy::Size {
12913                width: available.width.map_definite_value(|w| w.max(0.0)),
12914                height: available.height.map_definite_value(|h| h.max(0.0)),
12915            };
12916            if let Some(LeafContext::Image(Some(natural))) = cx {
12917                return image_size(*natural, known.width, known.height, &image_limits);
12918            }
12919            measure_content(engine, cache, cx, known, available, input_max_height)
12920        },
12921    );
12922    // An image is drawn inside its box whatever its fit (CSS's replaced
12923    // elements have no scrollable overflow). Taffy lays a leaf out without
12924    // the sizes its style gives it (`RunMode::PerformLayout`), so what was
12925    // measured is the natural size: a 24 point icon in a 14 point box
12926    // would give the scroll view around it 10 points to scroll.
12927    if image {
12928        let o = output.scrollable_overflow_rect;
12929        let mut rect = o.rect();
12930        rect.right = rect.right.min(output.size.width);
12931        rect.bottom = rect.bottom.min(output.size.height);
12932        output.scrollable_overflow_rect = taffy::ScrollableOverflow::new(rect, o.is_reversed());
12933    }
12934    output
12935}
12936
12937/// The size of a leaf's content: `known` and `available` are its content
12938/// box's ([`measure_leaf_size`]).
12939fn measure_content<M: TextEngine>(
12940    engine: &M,
12941    cache: &mut MeasureCache,
12942    cx: Option<&mut LeafContext<M::Prepared>>,
12943    known: taffy::Size<Option<f32>>,
12944    available: taffy::Size<AvailableSpace>,
12945    input_max_height: Option<f32>,
12946) -> taffy::Size<f32> {
12947    match cx {
12948        Some(LeafContext::Text(cx)) => {
12949            // An input's text scrolls in it (or wraps at its width):
12950            // the input's width does not come from the text.
12951            let field = cx
12952                .field
12953                .as_deref_mut()
12954                .map(|field| measure_text(engine, cache, field, None));
12955            let field_width = field.map(|size| size.width.0);
12956            let max_width = if cx.text.no_wrap {
12957                None
12958            } else {
12959                known.width.or(match (available.width, field_width) {
12960                    (AvailableSpace::Definite(w), Some(field)) => Some(field.min(w)),
12961                    (AvailableSpace::Definite(w), None) => Some(w),
12962                    (_, Some(field)) => Some(field),
12963                    (AvailableSpace::MinContent, None) => {
12964                        Some(min_content_width(engine, cache, cx).0)
12965                    }
12966                    (AvailableSpace::MaxContent, None) => None,
12967                })
12968            };
12969            let width = known.width.or(field_width.and(max_width));
12970            // A single-line input uses the field sample's width. When its font
12971            // determines the line height too, shaping the edited value would
12972            // change neither dimension.
12973            let measured = match field {
12974                Some(sample)
12975                    if width.is_some()
12976                        && cx.text.max_lines == 1
12977                        && engine.uniform_input_line_height() =>
12978                {
12979                    sample
12980                }
12981                _ => measure_text(engine, cache, cx, max_width),
12982            };
12983            taffy::Size {
12984                width: width.unwrap_or(measured.width.0),
12985                height: known.height.unwrap_or(match input_max_height {
12986                    Some(max) => measured.height.0.min(max),
12987                    None => measured.height.0,
12988                }),
12989            }
12990        }
12991        Some(LeafContext::Image(Some(natural))) => {
12992            image_size(*natural, known.width, known.height, &ImageLimits::default())
12993        }
12994        Some(LeafContext::Native(Some(own))) => taffy::Size {
12995            width: known.width.unwrap_or(own.width.0),
12996            height: known.height.unwrap_or(own.height.0),
12997        },
12998        _ => taffy::Size::ZERO,
12999    }
13000}
13001
13002fn measure_text<M: TextEngine>(
13003    engine: &M,
13004    cache: &mut MeasureCache,
13005    cx: &mut TextContext<M::Prepared>,
13006    max_width: Option<f32>,
13007) -> Size<Points> {
13008    if let Some((w, size)) = cx.cache
13009        && w == max_width
13010    {
13011        return size;
13012    }
13013    let typed = max_width.map(Points);
13014    // Far from the screen with no view: estimated, unless the size is
13015    // known (`cull.rs`).
13016    if cx.deferred {
13017        let size = cache.get(cx.layout_hash, typed).unwrap_or_else(|| {
13018            cx.estimated = true;
13019            estimate_text(&cx.text, max_width)
13020        });
13021        cx.cache = Some((max_width, size));
13022        return size;
13023    }
13024    if let (Some(width), Some(same)) = (max_width, cx.same_lines)
13025        && (same.narrowest..=same.widest).contains(&width)
13026    {
13027        cx.cache = Some((max_width, same.size));
13028        return same.size;
13029    }
13030    // A limit on lines cuts the last one to the width.
13031    let greedy = engine.breaks_lines_greedily() && cx.text.max_lines == 0;
13032    let size = match cache.get(cx.layout_hash, typed) {
13033        Some(size) => size,
13034        None => {
13035            // Far from the screen during a resize: it keeps its height for
13036            // now ([`Core::set_resizing`]).
13037            if let (Some(commit), Some((_, last))) = (cache.resizing, cx.cache)
13038                && cx.near_screen != commit
13039            {
13040                cx.held = true;
13041                return Size::new(
13042                    max_width.map_or(last.width, |w| last.width.min(Points(w))),
13043                    last.height,
13044                );
13045            }
13046            let prepared = cx
13047                .prepared
13048                .get_or_insert_with(|| engine.prepare_with(&cx.text, &cx.alignments, &cx.options));
13049            // Round up so rendering never truncates the last glyph, to a
13050            // device pixel: to a whole point the box grows past the text by
13051            // up to a point, all of it below the last line.
13052            let ratio = cache.pixel_ratio();
13053            let on_pixels = |size: Size<Points>| {
13054                cache
13055                    .on_cells(size)
13056                    .unwrap_or_else(|| size.map(|v| ceil_to_pixel(v, ratio)))
13057            };
13058            // Growing: measured a little wider, the next widths are known
13059            // too, unless a line takes another word by then.
13060            let ahead = max_width.filter(|width| {
13061                greedy && !cx.no_ahead && cx.same_lines.is_some_and(|same| *width > same.widest)
13062            });
13063            let ahead = ahead.and_then(|width| {
13064                let wider = Points(width + SAME_LINES_AHEAD);
13065                let size = on_pixels(engine.measure(prepared, Some(wider)));
13066                cx.no_ahead = size.width.0 > width;
13067                (size.width.0 <= width).then_some((wider.0, size))
13068            });
13069            let (measured, size) = match ahead {
13070                Some(found) => found,
13071                None => (
13072                    max_width.unwrap_or(f32::INFINITY),
13073                    on_pixels(engine.measure(prepared, typed)),
13074                ),
13075            };
13076            cache.insert(cx.layout_hash, typed, size);
13077            if greedy && size.width.0 <= measured {
13078                cx.same_lines = Some(SameLines {
13079                    narrowest: size.width.0,
13080                    widest: measured,
13081                    size,
13082                });
13083            }
13084            size
13085        }
13086    };
13087    cx.cache = Some((max_width, size));
13088    size
13089}
13090
13091/// Whether `laid`, the layout of `cx`'s text, stands for a box of `size`:
13092/// both widths break its lines the same ([`SameLines`]) and its lines start
13093/// at the box's left, wherever its right is.
13094/// The width `text-pretty` breaks a text's lines at in a box `width` wide:
13095/// narrower when its last line would hold less than a quarter of it (a
13096/// word or two left alone below a paragraph), as narrow as it takes for
13097/// that line to hold a quarter of the width without adding a line. The
13098/// platform's own line breaking decides where the lines break at it; a
13099/// text that cannot do better keeps the box's width.
13100fn pretty_width<M: TextEngine>(
13101    engine: &M,
13102    cx: &mut TextContext<M::Prepared>,
13103    width: Points,
13104) -> Points {
13105    if let Some(&(w, out)) = cx.pretty.as_deref()
13106        && w == width.0
13107    {
13108        return out;
13109    }
13110    let out = narrower_lines(engine, cx, width).unwrap_or(width);
13111    if let Some(p) = &mut cx.pretty {
13112        **p = (width.0, out);
13113    }
13114    out
13115}
13116
13117/// How short a last line `text-pretty` leaves alone: a quarter of the box.
13118const PRETTY_LAST_LINE: f32 = 0.25;
13119
13120fn narrower_lines<M: TextEngine>(
13121    engine: &M,
13122    cx: &mut TextContext<M::Prepared>,
13123    width: Points,
13124) -> Option<Points> {
13125    let text = &cx.text;
13126    if text.no_wrap || text.max_lines > 0 || width <= Points::ZERO || text.text.contains('\n') {
13127        return None;
13128    }
13129    let prepared = cx
13130        .prepared
13131        .get_or_insert_with(|| engine.prepare_with(&cx.text, &cx.alignments, &cx.options));
13132    let height = engine.measure(prepared, Some(width)).height;
13133    // How short the last line is at `w`, `None` past a line more.
13134    let short = |w: Points| -> Option<bool> {
13135        let size = engine.measure(prepared, Some(w));
13136        if size.height > height {
13137            return None;
13138        }
13139        let lines = engine.lines(&engine.layout(prepared, Size { width: w, height }));
13140        let last = lines.last()?;
13141        Some(lines.len() > 1 && last.width < w * PRETTY_LAST_LINE)
13142    };
13143    if short(width) != Some(true) {
13144        return None;
13145    }
13146    // Narrowing moves words down to the last line: find the widest width
13147    // whose last line is no longer short, between the box and the
13148    // narrowest width with as many lines.
13149    let lines = engine
13150        .lines(&engine.layout(prepared, Size { width, height }))
13151        .len();
13152    let (mut lo, mut hi) = (width * ((lines - 1) as f32 / lines as f32), width);
13153    let mut found = None;
13154    for _ in 0..8 {
13155        let mid = (lo + hi) * 0.5;
13156        match short(mid) {
13157            Some(false) => {
13158                found = Some(mid);
13159                lo = mid;
13160            }
13161            Some(true) => hi = mid,
13162            None => lo = mid,
13163        }
13164        if hi - lo < Points(1.0) {
13165            break;
13166        }
13167    }
13168    found
13169}
13170
13171fn keeps_lines<P>(cx: &TextContext<P>, laid: &LaidText, size: Size<Points>) -> bool {
13172    let Some(same) = cx.same_lines else {
13173        return false;
13174    };
13175    let widths = same.narrowest..=same.widest;
13176    laid.content.size.height == size.height
13177        && widths.contains(&laid.content.size.width.0)
13178        && widths.contains(&size.width.0)
13179        && Arc::ptr_eq(&laid.text, &cx.text)
13180        && lines_start_left(&cx.text)
13181}
13182
13183/// Whether every line of `text` starts at the left of its box. A paragraph's
13184/// direction may come from its first strong character, so `auto` alignment
13185/// with a character of a right-to-left script does not count.
13186fn lines_start_left(text: &AttributedText) -> bool {
13187    match text.align {
13188        TextAlign::Left => !text.text.chars().any(is_right_to_left),
13189        TextAlign::Auto => {
13190            !text.rtl
13191                && text.writing_direction != Some(true)
13192                && !text.text.chars().any(is_right_to_left)
13193        }
13194        TextAlign::Center | TextAlign::Right | TextAlign::Justify => false,
13195    }
13196}
13197
13198/// Whether `c` is in a block of a right-to-left script.
13199fn is_right_to_left(c: char) -> bool {
13200    matches!(
13201        c as u32,
13202        0x0590..=0x08FF | 0xFB1D..=0xFDFF | 0xFE70..=0xFEFF | 0x10800..=0x10FFF | 0x1E800..=0x1EFFF
13203    )
13204}
13205
13206fn definite(size: Size<Points>) -> taffy::Size<AvailableSpace> {
13207    taffy::Size {
13208        width: AvailableSpace::Definite(size.width.0),
13209        height: AvailableSpace::Definite(size.height.0),
13210    }
13211}
13212
13213/// The message for a refused URL.
13214/// The URL a web view prop loads at or resolves against, when it is one.
13215fn web_url(prop: &Prop) -> Option<&str> {
13216    match prop {
13217        Prop::Native(
13218            NativeProp::Src(Some(url))
13219            | NativeProp::BaseUrl(Some(url))
13220            | NativeProp::Source(
13221                crate::WebSource::Uri(url)
13222                | crate::WebSource::Html {
13223                    base_url: Some(url),
13224                    ..
13225                },
13226            ),
13227        ) => Some(url),
13228        _ => None,
13229    }
13230}
13231
13232fn not_granted(what: &str, uri: &str, capability: &str) -> String {
13233    let advice = crate::access::grant_advice(uri, capability);
13234    format!("{what} {uri} is not granted: {advice}")
13235}
13236
13237/// The message for a refused media source, read against `base` as
13238/// `Access::media_url` reads it.
13239fn media_not_granted(what: &str, uri: &str, base: Option<&str>) -> String {
13240    let advice = crate::access::media_grant_advice(uri, base);
13241    format!("{what} {uri} is not granted: {advice}")
13242}
13243
13244/// A page with nothing to load and no scripts: what a web view whose manual
13245/// Applies one property to a control.
13246fn apply_native(control: &mut NativeProps, prop: NativeProp) {
13247    use NativeProp as P;
13248    match (control, prop) {
13249        (NativeProps::WebView(p), P::Source(v)) => p.source = v,
13250        // `src`, `html` and `baseUrl` make one source: `html` shows over
13251        // `src`, with the base URL set before or after it.
13252        (NativeProps::WebView(p), P::Src(Some(url))) => {
13253            if !matches!(p.source, crate::WebSource::Html { .. }) {
13254                p.source = crate::WebSource::Uri(url.clone());
13255            }
13256            p.src = Some(url);
13257        }
13258        (NativeProps::WebView(p), P::Src(None)) => {
13259            p.src = None;
13260            if matches!(p.source, crate::WebSource::Uri(_)) {
13261                p.source = crate::WebSource::None;
13262            }
13263        }
13264        (NativeProps::WebView(p), P::Html(Some(html))) => {
13265            p.source = crate::WebSource::Html {
13266                html,
13267                base_url: p.base_url.clone(),
13268            };
13269        }
13270        (NativeProps::WebView(p), P::Html(None)) => {
13271            if matches!(p.source, crate::WebSource::Html { .. }) {
13272                p.source = match &p.src {
13273                    Some(url) => crate::WebSource::Uri(url.clone()),
13274                    None => crate::WebSource::None,
13275                };
13276            }
13277        }
13278        (NativeProps::WebView(p), P::BaseUrl(url)) => {
13279            if let crate::WebSource::Html { base_url, .. } = &mut p.source {
13280                base_url.clone_from(&url);
13281            }
13282            p.base_url = url;
13283        }
13284        (NativeProps::WebView(p), P::AllowOrigin(v)) => {
13285            p.allow_origin = v.and_then(|o| crate::access::WebOrigin::parse(&o).ok());
13286        }
13287        (NativeProps::WebView(p), P::AllowNavigation(v)) => {
13288            p.allow_navigation = v.and_then(|h| crate::access::WebHosts::parse(&h).ok());
13289        }
13290        (NativeProps::WebView(p), P::InjectedJavaScript(v)) => p.injected_js = v,
13291        (NativeProps::WebView(p), P::InjectedJavaScriptBefore(v)) => p.injected_js_before = v,
13292        (NativeProps::WebView(p), P::UserAgent(v)) => p.user_agent = v,
13293        (NativeProps::WebView(p), P::Scrollable(v)) => p.scrollable = v,
13294        (NativeProps::WebView(p), P::JavaScriptEnabled(v)) => p.javascript_enabled = v,
13295        (NativeProps::WebView(p), P::BackForwardGestures(v)) => p.back_forward_gestures = v,
13296        (NativeProps::WebView(p), P::Incognito(v)) => p.incognito = v,
13297        (NativeProps::WebView(p), P::Zoomable(v)) => p.zoomable = v,
13298        (NativeProps::WebView(p), P::UrlSchemes(v)) => p.url_schemes = v,
13299        (NativeProps::WebView(p), P::DeferDownloads(v)) => p.defer_downloads = v,
13300        (NativeProps::Video(p), P::Source(v)) => {
13301            p.source = match v {
13302                crate::WebSource::Uri(uri) => Some(uri),
13303                _ => None,
13304            }
13305        }
13306        (NativeProps::Video(p), P::Src(v)) => p.source = v,
13307        (NativeProps::Video(p), P::Poster(v)) => p.poster = v,
13308        (NativeProps::Video(p), P::Paused(v)) => p.paused = v,
13309        (NativeProps::Video(p), P::Muted(v)) => p.muted = v,
13310        (NativeProps::Video(p), P::Volume(v)) => p.volume = v.clamp(0.0, 1.0),
13311        (NativeProps::Video(p), P::Rate(v)) => p.rate = v.max(0.0),
13312        (NativeProps::Video(p), P::Repeat(v)) => p.repeat = v,
13313        (NativeProps::Video(p), P::VideoResizeMode(v)) => p.resize_mode = v,
13314        (NativeProps::Video(p), P::Controls(v)) => p.controls = v,
13315        (NativeProps::Video(p), P::ProgressInterval(v)) => p.progress_interval_ms = v.max(16.0),
13316        (NativeProps::Video(p), P::AudioSession(v)) => p.audio_session = v,
13317        _ => {}
13318    }
13319}
13320
13321/// `style` with its font metrics multiplied for the user's text size.
13322fn scaled(mut style: ResolvedTextStyle, multiplier: f32) -> ResolvedTextStyle {
13323    if multiplier != 1.0 {
13324        style.font_size *= multiplier;
13325        style.line_height *= multiplier;
13326    }
13327    style
13328}
13329
13330fn root_style(viewport: Size<Points>) -> taffy::Style {
13331    let mut style = taffy::Style {
13332        size: taffy::Size {
13333            width: taffy::Dimension::length(viewport.width.0),
13334            height: taffy::Dimension::length(viewport.height.0),
13335        },
13336        ..Style::default().layout
13337    };
13338    crate::style::resolve_normal_alignment(&mut style);
13339    style
13340}
13341
13342/// The hash of a text context's content, attachments and options: it keys
13343/// the measurement caches.
13344fn text_layout_hash(
13345    alignments: &crate::AttachmentAlignments,
13346    text: &crate::AttributedText,
13347    options: &crate::TextOptions,
13348) -> u64 {
13349    use std::hash::{Hash as _, Hasher as _};
13350    let mut h = std::collections::hash_map::DefaultHasher::new();
13351    alignments.layout_hash(text).hash(&mut h);
13352    options.indent.map(|indent| indent.0.to_bits()).hash(&mut h);
13353    h.finish()
13354}
13355
13356/// `align` in a layout of direction `rtl`: left and right trade places
13357/// right to left, as all left / right properties do.
13358fn directed_align(align: TextAlign, rtl: bool) -> TextAlign {
13359    match (align, rtl) {
13360        (TextAlign::Left, true) => TextAlign::Right,
13361        (TextAlign::Right, true) => TextAlign::Left,
13362        (align, _) => align,
13363    }
13364}
13365
13366/// The press events.
13367/// The gestures and touches a view handles besides presses: one with a
13368/// handler of them is something the user moves (a draggable ball), which a
13369/// terminal keeps (`terminal_layout::Role::interactive`).
13370const HANDLED: [EventKind; 7] = [
13371    EventKind::PanStart,
13372    EventKind::PanEnd,
13373    EventKind::PinchStart,
13374    EventKind::PinchEnd,
13375    EventKind::RotationStart,
13376    EventKind::RotationEnd,
13377    EventKind::Touch,
13378];
13379
13380const PRESSES: [EventKind; 4] = [
13381    EventKind::Press,
13382    EventKind::LongPress,
13383    EventKind::PressDown,
13384    EventKind::PressUp,
13385];
13386
13387/// The events a `disabled` view does not mount ([`Node::mounted_events`]).
13388const DISABLED_OFF: [EventKind; 8] = [
13389    EventKind::Press,
13390    EventKind::LongPress,
13391    EventKind::PressDown,
13392    EventKind::PressUp,
13393    EventKind::ContextMenu,
13394    EventKind::FileDragEnter,
13395    EventKind::FileDragLeave,
13396    EventKind::FileDrop,
13397];
13398
13399/// Whether `disabled` changes what a view with `events` mounts.
13400fn disabling_changes(events: EventMask) -> bool {
13401    DISABLED_OFF.iter().any(|&e| events.contains(e))
13402}
13403
13404/// A span's horizontal padding at its first and last character, in
13405/// points (its block is right to left when `rtl`). Percentages, of no box
13406/// a span has, count as none.
13407fn span_padding(node: &Node, rtl: bool) -> (f32, f32) {
13408    let Some(style) = node.base_layout.as_deref() else {
13409        return (0.0, 0.0);
13410    };
13411    let len = |p: taffy::LengthPercentage| match p.into_raw().tag() {
13412        taffy::CompactLength::LENGTH_TAG => p.into_raw().value().max(0.0),
13413        _ => 0.0,
13414    };
13415    let (left, right) = (len(style.padding.left), len(style.padding.right));
13416    if rtl { (right, left) } else { (left, right) }
13417}
13418
13419/// A span's top and bottom padding, which only its background takes (as
13420/// a CSS inline box's): the line keeps its height. Percentages count as
13421/// none.
13422fn span_vertical_padding(node: &Node) -> (Points, Points) {
13423    let Some(style) = node.base_layout.as_deref() else {
13424        return (Points::ZERO, Points::ZERO);
13425    };
13426    let len = |p: taffy::LengthPercentage| match p.into_raw().tag() {
13427        taffy::CompactLength::LENGTH_TAG => Points(p.into_raw().value().max(0.0)),
13428        _ => Points::ZERO,
13429    };
13430    (len(style.padding.top), len(style.padding.bottom))
13431}
13432
13433/// The background a nested text's view style gives its characters.
13434fn span_background(style: &ViewStyle, node: NodeId) -> Option<crate::text::TextBackground> {
13435    (style.background_color.0 & 0xff != 0).then_some(crate::text::TextBackground {
13436        color: style.background_color,
13437        radius: style.border_radius.max(Points::ZERO),
13438        node,
13439        top: Points::ZERO,
13440        bottom: Points::ZERO,
13441    })
13442}
13443
13444/// Whether a span with `events` takes presses (a link in its text block).
13445fn pressable(events: EventMask) -> bool {
13446    PRESSES.iter().any(|&e| events.contains(e))
13447}
13448
13449/// `content` with a line break after every [`MEASURED_RUN`] characters of
13450/// a run without a line-break opportunity, as a multiline input's value is measured.
13451///
13452/// Line breakers search back over the whole run for a break opportunity
13453/// at the end of every line they lay out (CoreText through ICU), so one
13454/// long run (minified JSON, Base64) costs time quadratic in its length:
13455/// 13 s to measure a 474 KB minified JSON on an Apple silicon Mac, on the
13456/// engine thread, at every edit. Broken into runs of 1024 it takes 47 ms. The
13457/// input shows and reports its own text; the measured height can only
13458/// grow by a line per break, and text without such runs is measured as is.
13459fn broken_runs(content: &str) -> std::borrow::Cow<'_, str> {
13460    let mut broken: Option<String> = None;
13461    let (mut start, mut from) = (0, 0);
13462    for (end, _) in unicode_linebreak::linebreaks(content) {
13463        let mut run = 0;
13464        for (offset, c) in content[start..end].char_indices() {
13465            let i = start + offset;
13466            // The final character may itself provide the break (space or
13467            // newline). Do not introduce another line immediately before it.
13468            if run == MEASURED_RUN && i + c.len_utf8() < end {
13469                let broken = broken.get_or_insert_with(|| {
13470                    String::with_capacity(content.len() + content.len() / MEASURED_RUN)
13471                });
13472                broken.push_str(&content[from..i]);
13473                broken.push('\n');
13474                (run, from) = (0, i);
13475            }
13476            run += 1;
13477        }
13478        start = end;
13479    }
13480    match broken {
13481        Some(mut broken) => {
13482            broken.push_str(&content[from..]);
13483            broken.into()
13484        }
13485        None => content.into(),
13486    }
13487}
13488
13489/// A visual style being installed on a node ([`Core::install_style`]):
13490/// resolved for it alone (`T`, [`Core::set_style`]) or shared with the nodes
13491/// whose classes resolved alike (`Option<Rc<T>>`, `None` the default,
13492/// [`classes::ResolvedClassStyle`]). Generic rather than an enum so that a
13493/// shared style moves as a pointer, not as large as an owned one.
13494trait StyleSlot<T: SharedDefault>: Sized {
13495    fn get(&self) -> &T;
13496    /// Whether `held` holds it already (by pointer first for a shared one).
13497    fn same(&self, held: &Sparse<T>) -> bool;
13498    fn install(self, held: &mut Sparse<T>);
13499}
13500
13501impl<T: SharedDefault + Clone> StyleSlot<T> for T {
13502    fn get(&self) -> &T {
13503        self
13504    }
13505
13506    fn same(&self, held: &Sparse<T>) -> bool {
13507        **held == *self
13508    }
13509
13510    fn install(self, held: &mut Sparse<T>) {
13511        held.set(self);
13512    }
13513}
13514
13515impl<T: SharedDefault + Clone> StyleSlot<T> for Option<Rc<T>> {
13516    fn get(&self) -> &T {
13517        self.as_deref().unwrap_or_else(|| T::shared_default())
13518    }
13519
13520    fn same(&self, held: &Sparse<T>) -> bool {
13521        match (&held.0, self) {
13522            (None, None) => true,
13523            (Some(a), Some(b)) => Rc::ptr_eq(a, b) || **a == **b,
13524            (Some(a), None) => **a == *T::shared_default(),
13525            (None, Some(b)) => *T::shared_default() == **b,
13526        }
13527    }
13528
13529    fn install(self, held: &mut Sparse<T>) {
13530        held.0 = self;
13531    }
13532}
13533
13534/// The layout style being installed on a node, [`StyleSlot`]'s
13535/// counterpart: `taffy::Style` or a shared `Rc<taffy::Style>`.
13536trait LayoutSlot: Sized {
13537    fn get(&self) -> &taffy::Style;
13538    /// The node's own copy to adjust (`env()`, insets).
13539    fn to_mut(&mut self) -> &mut taffy::Style;
13540    fn into_owned(self) -> taffy::Style;
13541    /// Makes it `node`'s style in `tree`; whether that changed it.
13542    fn set_on<C>(self, tree: &mut LayoutTree<C>, node: LayoutId) -> bool;
13543}
13544
13545impl LayoutSlot for taffy::Style {
13546    fn get(&self) -> &taffy::Style {
13547        self
13548    }
13549
13550    fn to_mut(&mut self) -> &mut taffy::Style {
13551        self
13552    }
13553
13554    fn into_owned(self) -> taffy::Style {
13555        self
13556    }
13557
13558    fn set_on<C>(self, tree: &mut LayoutTree<C>, node: LayoutId) -> bool {
13559        tree.set_style(node, self)
13560    }
13561}
13562
13563impl LayoutSlot for Rc<taffy::Style> {
13564    fn get(&self) -> &taffy::Style {
13565        self
13566    }
13567
13568    fn to_mut(&mut self) -> &mut taffy::Style {
13569        Rc::make_mut(self)
13570    }
13571
13572    fn into_owned(self) -> taffy::Style {
13573        Rc::unwrap_or_clone(self)
13574    }
13575
13576    fn set_on<C>(self, tree: &mut LayoutTree<C>, node: LayoutId) -> bool {
13577        tree.set_style_shared(node, self)
13578    }
13579}
13580
13581/// What [`Core::install_style`] makes a node's style: a resolved
13582/// [`Style`] after [`prepare_layout`] and [`clip_overflow`].
13583struct StyleRecord<L, V, X> {
13584    layout: L,
13585    view: V,
13586    text: X,
13587    paint: Option<Rc<PaintStyle>>,
13588    animated: Vec<(AnimationProp, crate::animation::NodeId)>,
13589    /// A sticky box's insets, taken out of its layout.
13590    sticky: Option<taffy::Rect<taffy::LengthPercentageAuto>>,
13591    perspective: Option<Points>,
13592    object_fit: Option<ResizeMode>,
13593    wants_fixed: bool,
13594    env: crate::style::EnvEdges,
13595    z_index: i32,
13596    vertical_align: crate::style::VerticalAlign,
13597    has_logical: bool,
13598    rtl: bool,
13599}
13600
13601/// What a resolved layout takes before it is installed, for `rtl`
13602/// ([`Core::set_style`], [`Core::resolved_styles`]): CSS's `normal`
13603/// alignment resolved and its start / end sides placed. A sticky box's insets
13604/// say where it sticks, not where it is laid out: they are taken out and
13605/// returned.
13606fn prepare_layout(
13607    layout: &mut taffy::Style,
13608    view: &mut ViewStyle,
13609    logical: &crate::style::Logical,
13610    rtl: bool,
13611    sticky: bool,
13612) -> Option<taffy::Rect<taffy::LengthPercentageAuto>> {
13613    crate::style::resolve_normal_alignment(layout);
13614    crate::style::apply_direction(layout, view, logical, rtl);
13615    sticky.then(|| {
13616        let auto = taffy::LengthPercentageAuto::auto();
13617        std::mem::replace(
13618            &mut layout.inset,
13619            taffy::Rect {
13620                left: auto,
13621                right: auto,
13622                top: auto,
13623                bottom: auto,
13624            },
13625        )
13626    })
13627}
13628
13629/// `overflow: "hidden"` clips in layout as well as in paint: what a box
13630/// clips away must not reach an enclosing scroll view's content size, or a
13631/// child laid out wider than its box and scaled down with a transform
13632/// (transforms do not affect layout) leaves the scroll view scrollable across
13633/// its own axis. `Clip`, not `Hidden`: both stop the overflow from
13634/// propagating, but `Hidden` is a scroll container in CSS and would also make
13635/// the box's automatic minimum size as a flex or grid item 0, which clipping
13636/// the paint must not do. Set here rather than while parsing the style so that
13637/// what `overflow` sets as a style stays what it was.
13638fn clip_overflow(layout: &mut taffy::Style, clip: bool) {
13639    let clip = if clip {
13640        taffy::Overflow::Clip
13641    } else {
13642        taffy::Overflow::Visible
13643    };
13644    layout.overflow = taffy::Point { x: clip, y: clip };
13645}
13646
13647/// `Rc` equality, by pointer first.
13648fn opt_rc_eq<T: PartialEq>(a: Option<&Rc<T>>, b: Option<&Rc<T>>) -> bool {
13649    match (a, b) {
13650        (None, None) => true,
13651        (Some(a), Some(b)) => Rc::ptr_eq(a, b) || **a == **b,
13652        _ => false,
13653    }
13654}
13655
13656/// What a leaf of `kind` measures with, if anything: texts and inputs (an
13657/// input measures like a text block holding its text or placeholder) their
13658/// text, images their image, native components the size they report.
13659fn leaf_context<P>(kind: Kind) -> Option<LeafContext<P>> {
13660    match kind {
13661        Kind::Text | Kind::Input => Some(LeafContext::Text(Box::new(TextContext::new(
13662            Arc::default(),
13663        )))),
13664        Kind::Image => Some(LeafContext::Image(None)),
13665        Kind::Native => Some(LeafContext::Native(None)),
13666        _ => None,
13667    }
13668}
13669
13670/// What a mount item changed of what shows, for the shaders that read what
13671/// is behind them ([`Core::mark_shader_inputs`]).
13672enum Shown {
13673    /// Nothing that shows: input, accessibility, the pictures' own marks,
13674    /// animated values (they reach the views on the UI thread, whose
13675    /// platform pictures the backdrops again), views leaving (their old
13676    /// parents stand in for them: `unlinked_from`).
13677    Nothing,
13678    /// What a view shows, or where.
13679    View(NodeId),
13680    /// Anything, anywhere: the appearance, the order of the tree, a
13681    /// transition. An item not known here is one, to be safe.
13682    Everywhere,
13683}
13684
13685fn shown_by(item: &MountItem) -> Shown {
13686    use MountItem as M;
13687    match item {
13688        M::Events { .. }
13689        | M::Keymap(_)
13690        | M::Gestures { .. }
13691        | M::AccessibilityLabel { .. }
13692        | M::ShaderInput { .. }
13693        | M::LayoutAnimation(_)
13694        | M::Animation(_)
13695        | M::ComponentPropSlots { .. }
13696        | M::TrackStates { .. }
13697        | M::InputContent { .. }
13698        | M::Remove { .. }
13699        | M::Delete { .. } => Shown::Nothing,
13700        M::Insert { child, .. } => Shown::View(*child),
13701        M::ProjectStates { id, .. }
13702        | M::ScrollConfig { id, .. }
13703        | M::ScrollBy { id, .. }
13704        | M::StickyCells { id, .. }
13705        | M::ScrollBehavior { id, .. }
13706        | M::Refreshing { id, .. }
13707        | M::AnimationBindings { id, .. }
13708        | M::ScreenConfig { id, .. }
13709        | M::ModalConfig { id, .. } => Shown::View(*id),
13710        M::Command { id, command } => {
13711            use crate::ops::Command as C;
13712            match command {
13713                // Outside the window's content: the system's, the app's,
13714                // another program's.
13715                C::ExitApp
13716                | C::PostMessage { .. }
13717                | C::SendInput { .. }
13718                | C::SetJsResponder { .. }
13719                | C::ClearJsResponder
13720                | C::Announce { .. }
13721                | C::ImageInfo { .. }
13722                | C::AccessibilityFocus
13723                | C::Measure { .. }
13724                | C::MeasureScrollPosition { .. }
13725                | C::SetClipboard { .. }
13726                | C::SetClipboardItem(_)
13727                | C::ReadClipboard { .. }
13728                | C::SetClipboardImage { .. }
13729                | C::ReadClipboardImage { .. }
13730                | C::ReadClipboardFiles { .. }
13731                | C::PickImages { .. }
13732                | C::PickFiles { .. }
13733                | C::OpenUrl { .. }
13734                | C::OpenAppSettings { .. }
13735                | C::PickScreenColor { .. }
13736                | C::RenderCanvas { .. }
13737                | C::FileRequest { .. }
13738                | C::Audio { .. }
13739                | C::Notification { .. }
13740                | C::Desktop { .. }
13741                | C::HostCall { .. }
13742                | C::HostPost { .. } => Shown::Nothing,
13743                // The design tokens: every view's colors.
13744                C::Tokens { .. } => Shown::Everywhere,
13745                _ => Shown::View(*id),
13746            }
13747        }
13748        item => item.view().map_or(Shown::Everywhere, Shown::View),
13749    }
13750}
13751
13752/// What collecting a text block's text gathers about its attachments, and
13753/// what it places them by.
13754struct TextAttachments<'a> {
13755    /// Where each sits in its line.
13756    alignments: crate::AttachmentAlignments,
13757    /// The empty attachments standing for spans' horizontal padding.
13758    spacers: Vec<u32>,
13759    /// The baselines of their own the views holding text stand by
13760    /// ([`Core::attachment_baselines`]).
13761    baselines: &'a [(Key, Points)],
13762    /// The first of `baselines` not met yet: they are in the attachments'
13763    /// order ([`Core::attachments_of`]).
13764    next_baseline: usize,
13765}