Skip to main content

nsh_core/core/
components.rs

1//! Rust components in the core ([`crate::element`]): creating instances,
2//! expanding their views into nodes (once: what changes later comes as
3//! patches, [`super::views`]), placing JS children and slots, and routing
4//! events.
5//!
6//! A component's host node is the root of its expansion: the root element's
7//! props and styles apply to it, its other elements become nodes with odd
8//! ids (JS uses even ones) owned by the host. Ops from JS on a host are
9//! intercepted ([`Core::apply`]): its `class` goes after the root's styles,
10//! its children are placed where the view's `Children` is. Views are made
11//! at the start of a commit, so a view starts with all the props set in
12//! the JS turn before.
13
14use std::{any::Any, cell::RefCell, rc::Rc, sync::Arc};
15
16use rustc_hash::{FxHashMap, FxHashSet};
17
18use super::{Core, Key, Kind, NO_KEY, views::Anchor};
19use crate::{
20    ApplyError, Command, EdgeInsets, EventKind, EventMask, EventPayload, NodeId, Op, Prop, ROOT_ID,
21    Tag, TextEngine,
22    element::{
23        Action, AnswerSlot, AnyInstance, AnyValue, Attrs, Child, ClipboardRead, ComponentError,
24        ComponentSpec, ElKind, ElNode, Environment, Executor, FileAnswer, ImageSize, IntoElement,
25        JsEvent, JsResult, ListConfig, Listener, ModuleCx, ParentElement, PlaceFn, Position, Posts,
26        Reactive, Registry, Root, RustCall, RustOp, SharedString, StyleRefinement, Task, Tokens,
27        caught,
28        responder::ResponderEl,
29        services::FetchFailure,
30        view,
31        virtual_list::{self, RowFn, SeparatorFn, VirtualListEl},
32    },
33    geometry::Points,
34    list_diff::ListDiff,
35    tailwind::ClassList,
36};
37
38/// Lowered styles kept for reuse (many elements have the same styles);
39/// cleared when full.
40const STYLE_CACHE: usize = 4096;
41
42/// Rounds of polls and updates per run of the tasks, at most.
43const MAX_TASK_ROUNDS: u32 = 64;
44
45/// A component made by name whose part is not registered yet.
46struct ByName {
47    id: std::any::TypeId,
48    props: Box<dyn crate::element::builder::AnyProps>,
49    /// Where it was made: its context comes from there.
50    owner: crate::element::Owner,
51}
52
53thread_local! {
54    /// What asks the platform for the part that registers a component
55    /// made by name ([`set_part_requester`]).
56    static PART_REQUESTER: std::cell::Cell<Option<fn(&str)>> = const { std::cell::Cell::new(None) };
57}
58
59/// Sets what asks the platform for the code of a component made by name
60/// that no UI set registers yet (a web runtime loads the side module of
61/// its part, then calls its gate): it gets the component's registered
62/// name. Without one, such a component shows nothing until a set
63/// registers it.
64#[doc(hidden)]
65pub fn set_part_requester(request: fn(&str)) {
66    PART_REQUESTER.with(|r| r.set(Some(request)));
67}
68
69/// What renders on a host node.
70enum Inner {
71    /// Nothing is registered under the name: renders nothing.
72    Missing,
73    Component(Box<dyn AnyInstance>),
74    /// A list cell of a component's list: the component's row function
75    /// wraps the row the app rendered.
76    Row {
77        place: PlaceFn,
78        index: usize,
79    },
80    /// A cell of a component's own list ([`crate::element::virtual_list`]): it
81    /// renders row `index` with the list's row function.
82    VirtualRow {
83        list: NodeId,
84        index: usize,
85    },
86}
87
88/// A list's row count and keys.
89type Rows = (u32, Option<Rc<[u64]>>);
90
91/// The parts of a view's list cells that show rows: the index each one's
92/// content reads, and the content's owner.
93type CellRows = Rc<RefCell<CellRowMap>>;
94
95/// The index and owner of each part of a list's cells showing a row.
96type CellRowMap = FxHashMap<NodeId, (crate::element::Signal<usize>, crate::element::Owner)>;
97
98/// A component's own list.
99struct VirtualListState {
100    /// The component whose view it is in (its rows' handlers are its).
101    owner: NodeId,
102    /// The owner of the run that made the list, if any: its rows are made
103    /// under it and disposed with it. Shared with the cleanup each run
104    /// registers, which disposes the rows only while the list is still
105    /// that run's.
106    scope: Rc<std::cell::Cell<Option<crate::element::Owner>>>,
107    row: RowFn,
108    count: u32,
109    keys: Option<Rc<[u64]>>,
110    separator: Option<SeparatorFn>,
111    /// The cells, by recycling slot.
112    cells: Vec<NodeId>,
113    /// In a view: the live parts of its cells (cells and contents) with the
114    /// index their content reads and its owner, for its rows' binding.
115    rows: CellRows,
116    /// The memo of a bound count or keys, which moves the cells' indices
117    /// as the rows change: their positions run it before they are read.
118    moves: Option<crate::element::reactive::Node>,
119    /// The rows of another component's `Items` prop
120    /// ([`crate::element::ComponentElement::items`]): each cell is that
121    /// component's wrapper (`place`, its row function: an [`Inner::Row`])
122    /// around a node rendering the row (an [`Inner::VirtualRow`], in
123    /// `contents` by slot), so each part's handlers run with its own
124    /// component.
125    items: bool,
126    place: Option<PlaceFn>,
127    contents: Vec<NodeId>,
128    /// Viewable rows: how long they must stay, the range reported last and
129    /// the latest, and the report waiting for the time to pass.
130    min_view: Option<std::time::Duration>,
131    reported: Option<(u32, u32)>,
132    latest: Option<(u32, u32)>,
133    report: Option<Task<()>>,
134}
135
136/// Where a host's JS children are.
137#[derive(Debug, Clone, Copy, PartialEq)]
138pub(super) enum Placement {
139    /// Out of the tree (the view has no place for them).
140    None,
141    /// In this node, before what the view puts after its `Children` (their
142    /// anchor: a node, or a region, whose nodes may come later).
143    At(NodeId, Anchor),
144    /// Each in its own wrapper ([`ParentElement::children_each`]): placed
145    /// by the view's region of wrappers.
146    Each,
147    /// Passed on as the children of the nested component hosted by this
148    /// node (`<Inset>{children}</Inset>`), before the content after them
149    /// (their anchor, as [`Self::At`]'s): its view places them.
150    Nested(NodeId, Anchor),
151}
152
153/// A view's handlers of native events, by node, each node's in the order
154/// its element was given them. A view can have thousands of nodes with
155/// handlers (a rich editor's blocks, each with its layout listener), and
156/// an event, a node made again and a check for a node's listener each
157/// look at that node's handlers only: a list of the whole view would be
158/// scanned for each, so mounting such a view would grow with its square.
159#[derive(Default)]
160pub(super) struct Handlers {
161    by_node: FxHashMap<NodeId, Vec<(EventKind, Listener<EventPayload>)>>,
162}
163
164impl Handlers {
165    /// Node `node`'s handlers, in order.
166    pub(super) fn of(&self, node: NodeId) -> &[(EventKind, Listener<EventPayload>)] {
167        self.by_node.get(&node).map_or(&[], Vec::as_slice)
168    }
169
170    /// Adds `listener` of `kind` to node `node`'s, after the ones it has.
171    pub(super) fn push(&mut self, node: NodeId, kind: EventKind, listener: Listener<EventPayload>) {
172        self.by_node.entry(node).or_default().push((kind, listener));
173    }
174
175    /// Drops node `node`'s handlers.
176    pub(super) fn remove(&mut self, node: NodeId) {
177        self.by_node.remove(&node);
178    }
179
180    /// Keeps the handlers of the nodes `keep` keeps.
181    pub(super) fn retain_nodes(&mut self, mut keep: impl FnMut(&NodeId) -> bool) {
182        self.by_node.retain(|node, _| keep(node));
183    }
184
185    /// Moves node `old`'s handlers to node `new` (a slot's target moving to
186    /// another node), after the ones `new` has.
187    pub(super) fn rename(&mut self, old: NodeId, new: NodeId) {
188        if old == new {
189            return;
190        }
191        if let Some(moved) = self.by_node.remove(&old) {
192            self.by_node.entry(new).or_default().extend(moved);
193        }
194    }
195
196    pub(super) fn clear(&mut self) {
197        self.by_node.clear();
198    }
199
200    /// How many handlers there are, on all nodes.
201    #[cfg(test)]
202    pub(super) fn len(&self) -> usize {
203        self.by_node.values().map(Vec::len).sum()
204    }
205}
206
207/// A component instance on its host node.
208pub(super) struct Instance {
209    inner: Inner,
210    spec: Option<Arc<ComponentSpec>>,
211    /// The app's `class` and `classList` on the host.
212    pub(super) class: Box<str>,
213    pub(super) class_list: Vec<Box<str>>,
214    /// The app's classes, or the styles the view this one is in gives it:
215    /// applied after the root's own.
216    pub(super) user: Option<std::rc::Rc<ClassList>>,
217    /// Events JS listens to on the host.
218    js_events: EventMask,
219    /// The listeners the view this one is in gives its element
220    /// (`.on_mouse_enter(..)` on a nested component's element), run by
221    /// that view's component after the root's own, as JS's on a host are.
222    given_handlers: Vec<(EventKind, Listener<EventPayload>)>,
223    /// The events of `given_handlers`.
224    given_events: EventMask,
225    /// The view, expanded (its root is the host); a list cell's row as
226    /// built last.
227    root: Option<Expanded>,
228    /// The host's JS children, in order.
229    pub(super) js_children: Vec<NodeId>,
230    /// Those of `js_children` that are text (a string, a `Text`), which
231    /// `children_each` tells its wrappers ([`Child::is_text`]).
232    js_texts: FxHashSet<NodeId>,
233    pub(super) children_at: Placement,
234    /// Lazy children (`#[prop(lazy)]`): whether JS was told to make them.
235    children_wanted: bool,
236    /// The glue's node of each slot the app passes.
237    slots: Vec<(&'static str, NodeId)>,
238    /// The view's handlers of native events, by node.
239    pub(super) handlers: Handlers,
240    /// The events of nested components, by their host (a handful: a list
241    /// beats a map).
242    pub(super) event_handlers: Vec<(NodeId, Listener<dyn Any>)>,
243    /// The view's parts in the touch responder, by node.
244    pub(super) responders: Vec<(NodeId, Rc<ResponderEl>)>,
245    /// The app's `style` on the host, applied after the root's own inline
246    /// style and animated values.
247    pub(super) app_style: Option<crate::StylePatch>,
248    dirty: bool,
249    /// Its view is made again, in place of the one it showed (a component
250    /// made by name, made when its part is registered).
251    remake: bool,
252    /// The nodes of its view with bindings: what was applied last. Boxed:
253    /// a record is large, and a map's free slots are as large as its
254    /// entries.
255    pub(super) bound: FxHashMap<NodeId, Box<super::views::BoundNode>>,
256    /// In a view placing its JS children one by one: them, each with
257    /// whether it is text, as a signal.
258    pub(super) js_kids: Option<crate::element::Signal<Vec<(NodeId, bool)>>>,
259    /// A cell of a view's list: the owner of the row it shows.
260    cell_owner: Option<crate::element::Owner>,
261    /// ... and the index its content reads (its [`Position`]): a cell
262    /// that shows another row sets it instead of being built again.
263    row_index: Option<crate::element::Signal<usize>>,
264    /// Lazy children a view passes: whether it places them, which what
265    /// passes them reads.
266    lazy_wanted: Option<crate::element::Signal<bool>>,
267    /// In a view: the owner where it places its JS children (a region's),
268    /// which the components JS made among them are under.
269    children_owner: Option<crate::element::Owner>,
270    /// It joined a host as its children or a slot's fill (content a view
271    /// passed a nested component, `tabs().child(tab())`,
272    /// `sub_menu().trigger(label())`, or inside plain views of that
273    /// content): its view waits, as one JS made does, to be in the tree
274    /// under where that host's view places it, so it reads the context
275    /// there.
276    joined: bool,
277    /// The component its view's root is, made on this host (its alias,
278    /// [`Core::alias`]): its view makes the host's node.
279    rooted: Option<NodeId>,
280    /// On such a component: the host (or alias) whose view's root it is.
281    pub(super) above: Option<NodeId>,
282    /// What the view this one is in fills its slots with ([`Fill`]).
283    pub(super) fills: Vec<Fill>,
284    /// What the view this one is in gives its element besides styles (its
285    /// inline style, animated values, insets): they apply to its root,
286    /// after the root's own, as the styles do.
287    pub(super) given: Option<Box<Attrs>>,
288    /// `given` changed since its root last took it.
289    given_changed: bool,
290    /// The insets its root's node has (its own, or given it).
291    pub(super) root_insets_applied: (Option<crate::EdgeInsets>, Option<crate::EdgeInsets>),
292    /// The host attributes its root's node was given over its own
293    /// ([`RootContext::host`]).
294    pub(super) root_host_applied: Vec<Prop>,
295    /// The host attributes JS sets on its host ([`js_host_attribute`]):
296    /// its root's node takes them over its own and over what views give
297    /// it, as the outermost.
298    pub(super) js_host: Vec<Prop>,
299}
300
301/// Whether `prop`, set by JS on a component's host, is a host attribute its
302/// root's node takes over its own ([`RootContext::host`]): its test id,
303/// tooltip, focus stop and what assistive technologies read of it but its
304/// role and state, which say what the component is and stay its root's.
305pub(super) fn js_host_attribute(prop: &Prop) -> bool {
306    use crate::AccessibilityProp as A;
307    match prop {
308        Prop::TestId(_) | Prop::Tooltip(_) | Prop::Focusable(_) => true,
309        Prop::Accessibility(a) => !matches!(a, A::Role(_) | A::State(_) | A::Orientation(_)),
310        _ => false,
311    }
312}
313
314/// Adds the host attributes of a nested component's root that `given` (a
315/// component element's attributes) sets to `host`, over the ones of the
316/// same kind there: its test id, tooltip, focus stop and the screen
317/// readers' label, description, value, actions (added up), active
318/// descendant and controlled element ([`crate::element::ComponentElement`]).
319/// A `None` among them is none given: the root keeps its own.
320pub(super) fn given_host(given: &Attrs, host: &mut Vec<Prop>) {
321    use crate::AccessibilityProp as A;
322    for prop in &given.props {
323        if matches!(
324            prop,
325            Prop::TestId(Some(_))
326                | Prop::Tooltip(_)
327                | Prop::Focusable(_)
328                | Prop::Accessibility(
329                    A::Actions(_) | A::ActiveDescendant(Some(_)) | A::Controls(Some(_))
330                )
331        ) {
332            give_host(host, prop.clone());
333        }
334    }
335    if let Some(label) = &given.label {
336        give_host(host, Prop::Accessibility(A::Label(Some(label.to_arc()))));
337    }
338    if let Some(rare) = &given.rare {
339        if let Some(description) = &rare.description {
340            give_host(
341                host,
342                Prop::Accessibility(A::Description(Some(description.to_arc()))),
343            );
344        }
345        if let Some(value) = &rare.value {
346            give_host(host, Prop::Accessibility(A::Value(Some(value.clone()))));
347        }
348    }
349}
350
351/// Sets host attribute `prop` among `props`: over the one of its kind, or
352/// for accessibility actions after the ones there, replacing those of the
353/// same names.
354fn give_host(props: &mut Vec<Prop>, prop: Prop) {
355    use crate::AccessibilityProp as A;
356    let Prop::Accessibility(A::Actions(given)) = prop else {
357        return crate::element::host::set_in(props, prop);
358    };
359    let own = props.iter_mut().find_map(|p| match p {
360        Prop::Accessibility(A::Actions(own)) => Some(own),
361        _ => None,
362    });
363    let Some(own) = own else {
364        return props.push(Prop::Accessibility(A::Actions(given)));
365    };
366    for action in given {
367        match own.iter_mut().find(|a| a.name == action.name) {
368            Some(same) => *same = action,
369            None => own.push(action),
370        }
371    }
372}
373
374/// `attrs` (a root's own) with the host attributes `host` given it
375/// ([`given_host`]), as its node has them.
376pub(super) fn with_host(mut attrs: Attrs, host: &[Prop]) -> Attrs {
377    use crate::AccessibilityProp as A;
378    for prop in host {
379        match prop {
380            Prop::Accessibility(A::Label(label)) => {
381                attrs.label = label.clone().map(SharedString::from);
382            }
383            Prop::Accessibility(A::Description(description)) => {
384                attrs.rare_mut().description = description.clone().map(SharedString::from);
385            }
386            Prop::Accessibility(A::Value(value)) => attrs.rare_mut().value = value.clone(),
387            Prop::Accessibility(A::Hint(hint)) => {
388                attrs.rare_mut().hint = hint.clone().map(SharedString::from);
389            }
390            Prop::Accessibility(A::Accessible(accessible)) => {
391                attrs.rare_mut().accessible = *accessible;
392            }
393            prop => give_host(&mut attrs.props, prop.clone()),
394        }
395    }
396    attrs
397}
398
399/// What a component's root takes from the components above it on its host
400/// and the views that place them ([`Core::root_context`]).
401pub(super) struct RootContext {
402    /// Their styles, after the root's (the outer last).
403    pub(super) user: Option<std::rc::Rc<ClassList>>,
404    /// Whether `app` is what goes after the root's inline style (else the
405    /// component's own app style is).
406    pub(super) combined: bool,
407    /// The inline styles and animated values they give it (the inner
408    /// first), then the app's style on the top host.
409    pub(super) app: Option<crate::StylePatch>,
410    /// JS's events on the top host.
411    pub(super) js: Option<EventMask>,
412    /// The events of the listeners the views above give it (and the
413    /// components whose root it is).
414    pub(super) given_events: EventMask,
415    /// The insets given it (the outer wins).
416    inset_padding: Option<crate::EdgeInsets>,
417    inset_margin: Option<crate::EdgeInsets>,
418    /// The host attributes given it ([`given_host`]: the outer wins, JS's
419    /// on the top host the outermost), over the root's own.
420    pub(super) host: Vec<Prop>,
421    /// Whether any view gives it anything besides styles.
422    given: bool,
423}
424
425impl RootContext {
426    /// `attrs` (a root's) with the insets given it.
427    pub(super) fn over(&self, mut attrs: Attrs) -> Attrs {
428        if let Some(insets) = self.inset_padding {
429            attrs.rare_mut().inset_padding = Some(insets);
430        }
431        if let Some(insets) = self.inset_margin {
432            attrs.rare_mut().inset_margin = Some(insets);
433        }
434        with_host(attrs, &self.host)
435    }
436}
437
438/// What a view fills a nested component's slot with (`.fill(name, el)`, a
439/// tag's slot method): nodes of that view, which the nested view places as
440/// they are where it places the slot (a node of its own around them only
441/// where it styles the slot). A slot JS fills has a holder node instead
442/// (`Instance::slots`).
443pub(super) struct Fill {
444    pub(super) name: &'static str,
445    /// Its parts in order: nodes, regions whose nodes come and go, and
446    /// what fills the placing view's own slots.
447    parts: Vec<FillPart>,
448    /// The host of the view that fills it.
449    from: NodeId,
450    /// Where the nested view places them.
451    pub(super) at: Placement,
452    /// The slot of a component in the nested view whose fill places this
453    /// one (`.fill(name, props.slot.place(|s| s))`): its nodes go there.
454    forwarded: Option<(NodeId, &'static str)>,
455}
456
457/// A part of a [`Fill`].
458#[derive(Debug, Clone, Copy, PartialEq)]
459pub(super) enum FillPart {
460    Node(NodeId),
461    Region(u32),
462    /// What fills the placing view's own slot of this name, passed on.
463    Filled(&'static str),
464}
465
466impl Instance {
467    fn new(
468        inner: Inner,
469        spec: Option<Arc<ComponentSpec>>,
470        js_children: Vec<NodeId>,
471        app_style: Option<crate::StylePatch>,
472    ) -> Self {
473        Self {
474            inner,
475            spec,
476            class: "".into(),
477            class_list: Vec::new(),
478            user: None,
479            js_events: EventMask::default(),
480            given_handlers: Vec::new(),
481            given_events: EventMask::default(),
482            root: None,
483            js_children,
484            js_texts: FxHashSet::default(),
485            children_at: Placement::None,
486            children_wanted: false,
487            slots: Vec::new(),
488            handlers: Handlers::default(),
489            event_handlers: Vec::new(),
490            responders: Vec::new(),
491            app_style,
492            dirty: false,
493            remake: false,
494            bound: FxHashMap::default(),
495            js_kids: None,
496            cell_owner: None,
497            row_index: None,
498            lazy_wanted: None,
499            children_owner: None,
500            joined: false,
501            rooted: None,
502            above: None,
503            fills: Vec::new(),
504            given: None,
505            given_changed: false,
506            root_insets_applied: (None, None),
507            root_host_applied: Vec::new(),
508            js_host: Vec::new(),
509        }
510    }
511
512    /// Its JS children changed: the view placing them one by one follows.
513    fn js_children_changed(&self) {
514        if let Some(children) = self.js_kids {
515            // A nested component's view goes with the run that made it,
516            // which can go in this commit before the region holding the
517            // component is reconciled and releases it: a region in the
518            // component's content and the list row it is in changed
519            // together. Its content still leaves it, but its view, and so
520            // what read the signal, is gone.
521            children.try_set(self.js_kids());
522        }
523    }
524
525    /// Its JS children, each with whether it is text.
526    fn js_kids(&self) -> Vec<(NodeId, bool)> {
527        self.js_children
528            .iter()
529            .map(|&c| (c, self.js_texts.contains(&c)))
530            .collect()
531    }
532
533    /// Node `child` left its JS children.
534    fn forget_js_child(&mut self, child: NodeId) {
535        self.js_children.retain(|&c| c != child);
536        self.js_texts.remove(&child);
537    }
538}
539
540#[derive(Debug, Clone, Copy, PartialEq, Eq)]
541pub(super) enum Part {
542    Node,
543    /// A slot's node: JS's, never released by the core.
544    Slot,
545    /// Where the JS children are (no node of its own).
546    Children,
547    /// A nested component.
548    Component(&'static str),
549    /// A list of the component's own rows; its cells are the core's.
550    VirtualList,
551    /// One of the JS children (no node of its own).
552    JsChild,
553    /// A piece of a text's content: a raw text node.
554    Raw,
555    /// A region of a view's children (no node of its own:
556    /// [`super::views`]).
557    Region(u32),
558    /// What this view fills a nested component's slot with (no node of
559    /// its own: its children are the nodes).
560    Fill(&'static str),
561    /// Where this view places what fills its slot (no node of its own).
562    Filled(&'static str),
563    /// The tooltip this view gives a nested component's root (no node of
564    /// its own: its child is the element, which that root's node shows).
565    Tooltip,
566}
567
568/// A node's app classes ([`Components::app_classes`]): its own rules, the
569/// classes, and what goes after them.
570pub(super) type AppClass = (
571    Option<std::rc::Rc<ClassList>>,
572    SharedString,
573    Option<std::rc::Rc<ClassList>>,
574);
575
576/// The node's classes: its styles lowered, and what was merged after them.
577pub(super) type Classes = (
578    Option<std::rc::Rc<ClassList>>,
579    Option<std::rc::Rc<ClassList>>,
580);
581
582/// An element of a view, as it was applied.
583pub(super) struct Expanded {
584    pub(super) id: NodeId,
585    pub(super) tag: Tag,
586    pub(super) key: Option<SharedString>,
587    /// A text's content and its raw text node.
588    text: Option<(SharedString, NodeId)>,
589    attrs: Attrs,
590    style: StyleRefinement,
591    classes: Classes,
592    events: EventMask,
593    /// A list's layout, when this element is a `VirtualList`.
594    list: Option<Box<ListConfig>>,
595    pub(super) part: Part,
596    pub(super) children: Vec<Expanded>,
597}
598
599impl Expanded {
600    /// A node of JS's in the view (`id` 0: the place of the children).
601    pub(super) fn js(id: NodeId, part: Part) -> Self {
602        Self {
603            id,
604            tag: Tag::View,
605            key: None,
606            text: None,
607            attrs: Attrs::default(),
608            style: StyleRefinement::default(),
609            classes: (None, None),
610            events: EventMask::default(),
611            list: None,
612            part,
613            children: Vec::new(),
614        }
615    }
616}
617
618/// A child to match with a parent's old elements
619/// ([`Core::match_children`]).
620#[allow(
621    clippy::large_enum_variant,
622    reason = "elements are matched as they come: a box for each would allocate for every child"
623)]
624pub(super) enum NewChild {
625    /// An element, applied under its owner when it has one.
626    Made(Option<crate::element::Owner>, ElNode),
627    /// The old element of this key stays as it is: of an `Each` row that
628    /// was there before.
629    Kept(SharedString),
630}
631
632/// The keyed old elements of a parent by key ([`Core::match_children`]),
633/// indexed the first time one is looked up: a few elements are searched in
634/// order, many once, so a long keyed list moved or reversed is matched in
635/// linear time. Old elements are only ever taken (`None`) while matching,
636/// so the index stays valid.
637#[derive(Default)]
638pub(super) struct OldKeys {
639    /// The first old element of each key.
640    first: FxHashMap<SharedString, usize>,
641    /// The next old element of the same key after each one (`usize::MAX`
642    /// for none).
643    next: Vec<usize>,
644    indexed: bool,
645}
646
647impl OldKeys {
648    /// Up to this many old elements are searched rather than indexed.
649    const SEARCHED: usize = 16;
650
651    /// The first old element of key `key` left in `old` that is `ok`.
652    fn find(
653        &mut self,
654        old: &[Option<Expanded>],
655        key: &SharedString,
656        ok: impl Fn(&Expanded) -> bool,
657    ) -> Option<usize> {
658        let is = |o: &Option<Expanded>| {
659            o.as_ref()
660                .is_some_and(|o| o.key.as_ref() == Some(key) && ok(o))
661        };
662        if old.len() <= Self::SEARCHED {
663            return old.iter().position(is);
664        }
665        if !self.indexed {
666            self.indexed = true;
667            self.next = vec![usize::MAX; old.len()];
668            // From the end, so each key's first is the earliest.
669            for (at, o) in old.iter().enumerate().rev() {
670                if let Some(k) = o.as_ref().and_then(|o| o.key.as_ref())
671                    && let Some(next) = self.first.insert(k.clone(), at)
672                {
673                    self.next[at] = next;
674                }
675            }
676        }
677        // Those taken go from the front (duplicate keys taken in order are
678        // not walked again).
679        let first = self.first.get_mut(key)?;
680        while *first != usize::MAX && old[*first].is_none() {
681            *first = self.next[*first];
682        }
683        let mut at = *first;
684        while at != usize::MAX {
685            if is(&old[at]) {
686                return Some(at);
687            }
688            at = self.next[at];
689        }
690        None
691    }
692}
693
694/// Whether a slot's place only places it: no styles, props, listeners or
695/// children of its own (what fills it then needs no node around it).
696fn is_plain(el: &ElNode) -> bool {
697    el.attrs == Attrs::default()
698        && el.style.is_empty()
699        && !el.is_bound()
700        && el.handlers.is_empty()
701        && el.responder.is_none()
702        && el.children.is_empty()
703        && el.text.is_none()
704}
705
706/// What a component's task waits for from the animation graph.
707enum Awaited {
708    /// An animation's end: whether it finished.
709    End(AnswerSlot<bool>),
710    /// A value read ([`crate::element::AnimatedValue::value`]).
711    Value(AnswerSlot<f32>),
712}
713
714/// What the platform answered a clipboard read with (the root's
715/// `Clipboard` event).
716#[derive(Default)]
717pub(super) struct ClipboardAnswer {
718    /// Whether it holds what was asked.
719    pub(super) has: bool,
720    /// The text, for a text read.
721    pub(super) text: Option<String>,
722    /// Whether the person refused a text read (iOS's paste prompt): the
723    /// clipboard holds text, but none was read.
724    pub(super) denied: bool,
725    /// The image, for an image read.
726    pub(super) image: Option<crate::element::ClipboardImage>,
727    /// The size in encoded bytes of an image over
728    /// [`crate::platform::clipboard::MAX_IMAGE_BYTES`], left out of the
729    /// answer.
730    pub(super) too_large: Option<usize>,
731    /// The files' `file:` URLs, for a files read.
732    pub(super) files: Vec<String>,
733}
734
735impl ClipboardAnswer {
736    pub(super) fn from_payload(payload: &EventPayload) -> ClipboardAnswer {
737        let mut answer = ClipboardAnswer::default();
738        let EventPayload::Map(entries) = payload else {
739            return answer;
740        };
741        let (mut uri, mut width, mut height) = (None, 0.0, 0.0);
742        for (k, v) in entries {
743            match (*k, v) {
744                ("has", crate::PayloadValue::Bool(b)) => answer.has = *b,
745                ("text", crate::PayloadValue::Str(t)) => answer.text = Some(t.clone()),
746                ("denied", crate::PayloadValue::Bool(b)) => answer.denied = *b,
747                ("uri", crate::PayloadValue::Str(u)) => uri = Some(u.clone()),
748                ("width", crate::PayloadValue::Number(n)) => width = *n,
749                ("height", crate::PayloadValue::Number(n)) => height = *n,
750                ("tooLarge", crate::PayloadValue::Number(n)) => {
751                    answer.too_large = Some(*n as usize)
752                }
753                ("files", crate::PayloadValue::Str(f)) => {
754                    answer.files = f
755                        .lines()
756                        .filter(|l| !l.is_empty())
757                        .map(str::to_owned)
758                        .collect()
759                }
760                _ => {}
761            }
762        }
763        // Only an image NSH can show, a `data:` URI, and only one the VM
764        // can hold (the web's player encodes its own).
765        let uri = uri.filter(|u| u.starts_with("data:"));
766        let bytes = uri.as_deref().map(crate::platform::clipboard::data_uri_len);
767        if let Some(bytes) = bytes.filter(|&b| b > crate::platform::clipboard::MAX_IMAGE_BYTES) {
768            answer.too_large = Some(bytes);
769        } else {
770            answer.image = uri.map(|url| crate::element::ClipboardImage {
771                url,
772                size: crate::geometry::Size::new(pixels(width), pixels(height)),
773            });
774        }
775        answer
776    }
777}
778
779/// An HTTP request of a task in flight ([`Core::fetch_event`]).
780struct PendingFetch {
781    /// What arrived so far.
782    response: crate::element::HttpResponse,
783    answer: AnswerSlot<Result<crate::element::HttpResponse, FetchFailure>>,
784}
785
786/// What notifications wait for ([`crate::notifications`]).
787#[derive(Default)]
788struct Notifications {
789    /// The next request's id.
790    next: u32,
791    /// Permission requests waiting for the platform's answer.
792    permissions: FxHashMap<u32, AnswerSlot<crate::notifications::NotificationPermission>>,
793    /// Notifications waiting for the platform's answer.
794    shows: FxHashMap<u32, AnswerSlot<bool>>,
795    /// The platform was told to report presses.
796    listening: bool,
797    /// Presses no listener took yet.
798    presses: std::collections::VecDeque<String>,
799    /// The listener waiting for a press.
800    next_press: Option<AnswerSlot<String>>,
801}
802
803/// The links that open the app ([`crate::url_scheme`]).
804#[derive(Default)]
805struct UrlScheme {
806    /// The links the app claims: its schemes and web links.
807    links: crate::url_scheme::AppLinks,
808    /// The links some listener has yet to hear, by number, at most
809    /// [`crate::url_scheme::MAX_PENDING`]: those no listener took yet (from
810    /// [`Self::unheard`] on), and those a listener missed between two calls.
811    recent: std::collections::VecDeque<(u64, String)>,
812    /// The number of the next link.
813    next_number: u64,
814    /// The first link that came while nothing listened and no listener
815    /// took yet, which the next new listener gets.
816    unheard: u64,
817    /// The tasks that listen, each with the number of the next link it is
818    /// to hear: a task awaiting links in a loop is not waiting between two
819    /// calls, and hears the links that came meanwhile at its next call.
820    listeners: Vec<(u64, u64)>,
821    /// The calls waiting for a link, with their task: each gets the next
822    /// one.
823    next: Vec<(Option<u64>, AnswerSlot<String>)>,
824    /// The waits for a link of one scheme (lowered), in the order they
825    /// came: the first takes the next link of its scheme, which no other
826    /// listener gets ([`crate::element::next_url_scheme_open_for`]).
827    next_of_scheme: Vec<(String, AnswerSlot<String>)>,
828    /// Address moves no listener took yet
829    /// ([`crate::url_scheme::AppUrlChange`]), kept once something listened
830    /// ([`Self::hears_changes`]), at most [`crate::url_scheme::MAX_PENDING`].
831    changes: std::collections::VecDeque<crate::url_scheme::AppUrlChange>,
832    /// The listener waiting for an address move.
833    next_change: Option<AnswerSlot<crate::url_scheme::AppUrlChange>>,
834    /// Something listens to address moves: those before it are stale (the
835    /// address has them), those after it wait between its answers.
836    hears_changes: bool,
837    /// The app's address: the last link taken, the page's on the web, or
838    /// what the app set (`UrlScheme.setUrl`, `set_app_url`). The one copy,
839    /// which every VM's `System` shares ([`Core::app_url_cell`]).
840    address: crate::url_scheme::AppUrlCell,
841}
842
843impl UrlScheme {
844    /// Hands `url`, a link for the app's listeners, to those waiting, and
845    /// keeps it for those that are not (and for the next new listener when
846    /// none was waiting).
847    fn open(&mut self, url: String, alive: impl Fn(u64) -> bool) {
848        let number = self.next_number;
849        self.next_number += 1;
850        self.listeners.retain(|&(task, _)| alive(task));
851        if self.recent.len() == crate::url_scheme::MAX_PENDING
852            && let Some((dropped, _)) = self.recent.pop_front()
853            && dropped >= self.unheard
854        {
855            log::warn!(
856                "link dropped: {} came while nothing listened",
857                crate::url_scheme::MAX_PENDING
858            );
859            self.unheard = dropped + 1;
860        }
861        self.recent.push_back((number, url.clone()));
862        // A listener whose answer went (its task ended, or it lost a
863        // `select!`) leaves the link to the others.
864        self.next
865            .retain(|(_, answer)| crate::element::task::awaited(answer));
866        // Came while something listened: the listeners between two calls
867        // hear it at their next, and a listener that starts later does not
868        // (only links that came while nothing listened wait for one).
869        if !self.next.is_empty() || !self.listeners.is_empty() {
870            self.unheard = number + 1;
871        }
872        if !self.next.is_empty() {
873            for (task, answer) in std::mem::take(&mut self.next) {
874                if let Some(task) = task {
875                    self.heard(task, number);
876                }
877                answer.borrow_mut().deliver(url.clone());
878            }
879        }
880        self.trim();
881    }
882
883    /// Answers a call of `task` (none: outside a task) waiting for a link:
884    /// with the first link the task has not heard, a new listener's being
885    /// the first no listener took; else with the next one to come.
886    fn listen(
887        &mut self,
888        task: Option<u64>,
889        answer: AnswerSlot<String>,
890        alive: impl Fn(u64) -> bool,
891    ) {
892        self.listeners.retain(|&(task, _)| alive(task));
893        let known = task.and_then(|task| {
894            self.listeners
895                .iter()
896                .find(|&&(listener, _)| listener == task)
897                .map(|&(_, next)| next)
898        });
899        let from = known.unwrap_or(self.unheard);
900        if let Some((number, url)) = self.recent.iter().find(|(n, _)| *n >= from).cloned() {
901            self.unheard = self.unheard.max(number + 1);
902            if let Some(task) = task {
903                self.heard(task, number);
904            }
905            answer.borrow_mut().deliver(url);
906        } else {
907            if let Some(task) = task
908                && known.is_none()
909            {
910                self.listeners.push((task, self.next_number));
911            }
912            self.next
913                .retain(|(_, answer)| crate::element::task::awaited(answer));
914            self.next.push((task, answer));
915        }
916        self.trim();
917    }
918
919    /// `task` heard link `number`.
920    fn heard(&mut self, task: u64, number: u64) {
921        match self
922            .listeners
923            .iter_mut()
924            .find(|(listener, _)| *listener == task)
925        {
926            Some((_, next)) => *next = number + 1,
927            None => self.listeners.push((task, number + 1)),
928        }
929    }
930
931    /// Lets go of the links every listener heard.
932    fn trim(&mut self) {
933        let keep = self
934            .listeners
935            .iter()
936            .map(|&(_, next)| next)
937            .fold(self.unheard, u64::min);
938        while self
939            .recent
940            .front()
941            .is_some_and(|&(number, _)| number < keep)
942        {
943            self.recent.pop_front();
944        }
945    }
946}
947
948/// Files the system opened the app with ([`crate::file_type`]).
949#[derive(Default)]
950struct OpenFiles {
951    /// Files no listener took yet, at most [`crate::file_type::MAX_PENDING`].
952    pending: std::collections::VecDeque<std::path::PathBuf>,
953    /// The listener waiting for files.
954    next: Option<AnswerSlot<Vec<std::path::PathBuf>>>,
955}
956
957/// Later launches of the app ([`crate::single_instance`]).
958#[derive(Default)]
959struct SecondInstances {
960    /// Launches no listener took yet, at most
961    /// [`crate::single_instance::MAX_PENDING`].
962    pending: std::collections::VecDeque<crate::single_instance::SecondInstance>,
963    /// The listener waiting for a launch.
964    next: Option<AnswerSlot<crate::single_instance::SecondInstance>>,
965}
966
967/// The core's component state.
968pub(super) struct Components {
969    pub(super) web_evaluations: super::web_evaluation::Evaluations,
970    pub(super) canvas_renders: super::canvas_render::Renders,
971    registry: Registry,
972    /// The specs of the components made by type (not by name from the
973    /// registry), one per type.
974    specs: FxHashMap<&'static str, Arc<ComponentSpec>>,
975    /// The design tokens drawn with.
976    pub(super) tokens: Arc<Tokens>,
977    /// The app's tokens (a UI set's defaults, `nsh.json`'s theme, a Rust
978    /// app's root): drawn with while the embedding app sets none
979    /// ([`Core::set_host_tokens`]).
980    app_tokens: Arc<Tokens>,
981    /// The embedding app's tokens: win over [`Self::app_tokens`].
982    host_tokens: Option<Arc<Tokens>>,
983    /// Boxed: making a view (or applying its patches) takes its instance
984    /// out of the map and back.
985    pub(super) instances: FxHashMap<NodeId, Box<Instance>>,
986    /// Hosts of components made by name whose part is not registered yet
987    /// ([`crate::element::ComponentElement::by_name`]): made when it is.
988    by_name: FxHashMap<NodeId, ByName>,
989    /// Expanded node -> the host of the component whose view made it.
990    pub(super) owners: FxHashMap<NodeId, NodeId>,
991    /// Changes when reconciliation releases an expanded element or raw
992    /// node. A region that only populates or retains nodes needs no sweep
993    /// of its host's listeners and bindings.
994    pub(super) release_generation: u64,
995    /// Region hosts to clean before the next binding/event round. Several
996    /// regions of one view can release nodes in the same patch batch.
997    pub(super) released_hosts: FxHashSet<NodeId>,
998    #[cfg(test)]
999    pub(super) cleanup_work: super::views::CleanupWork,
1000    /// The handlers dispatches looked at to find a node's (for a probe that
1001    /// the count stays with the node's, whatever the view's size).
1002    #[cfg(test)]
1003    pub(super) handler_visits: std::cell::Cell<usize>,
1004    /// Siblings and overlays looked at to place views among them
1005    /// ([`Core::preceding`], `native_before_at`, `first_overlay_in`).
1006    #[cfg(test)]
1007    pub(super) placing_work: std::cell::Cell<usize>,
1008    /// Siblings looked at to find children's positions among them
1009    /// ([`Core::positions_changed`], `position_bits`).
1010    #[cfg(test)]
1011    pub(super) position_work: std::cell::Cell<usize>,
1012    /// Watched nodes looked at to tell which start and stop listening to
1013    /// touches or the pointer for the overlays (`Core::rewatch`).
1014    #[cfg(test)]
1015    pub(super) watch_work: std::cell::Cell<usize>,
1016    /// Mount items looked at when views take the kind of their
1017    /// component's root ([`Core::retag`]).
1018    #[cfg(test)]
1019    pub(super) retag_work: std::cell::Cell<usize>,
1020    /// Rounds of renders in which views took the kind of their
1021    /// component's root ([`Core::end_retags`]).
1022    #[cfg(test)]
1023    pub(super) retag_rounds: std::cell::Cell<usize>,
1024    /// Slot nodes (`componentSlot`) -> their slot's name.
1025    slot_names: FxHashMap<NodeId, Arc<str>>,
1026    /// Slot nodes in a host -> the host.
1027    pub(super) slot_hosts: FxHashMap<NodeId, NodeId>,
1028    /// Slot nodes whose element gives them more than styles -> where that
1029    /// goes ([`super::slots`]).
1030    pub(super) slot_targets: FxHashMap<NodeId, super::slots::SlotTarget>,
1031    /// The app's elements a slot's props go to -> their slot node.
1032    pub(super) adopted: FxHashMap<NodeId, NodeId>,
1033    /// The nodes views wrap a slot's fill in (the place gives it more than
1034    /// itself): slot nodes as JS's are, their props going to the fill's one
1035    /// element ([`Core::reconcile_wrapper`]).
1036    pub(super) fill_holders: FxHashSet<NodeId>,
1037    styles: FxHashMap<StyleRefinement, std::rc::Rc<ClassList>>,
1038    /// The styles a component on another's host gets from each above it,
1039    /// merged (by the lists', which the entry keeps).
1040    pub(super) merges: FxHashMap<(usize, usize), [std::rc::Rc<ClassList>; 3]>,
1041    /// While a view's slot content is matched: the nested component's host
1042    /// and the slot (its regions are the slot's).
1043    pub(super) filling: Option<(NodeId, &'static str)>,
1044    /// The parents nodes moved out of and into since the order watches
1045    /// last looked (`core/watch.rs`), as an app's keyed reorder moves its
1046    /// rows: only a watch whose elements share one of them (or an ancestor
1047    /// of one) looks again.
1048    pub(super) moved: Vec<NodeId>,
1049    /// The lists components place (the glue's, of `Items` props) -> the
1050    /// row function the component's view gave last, and the number of rows
1051    /// its wrappers last saw.
1052    lists: FxHashMap<NodeId, (PlaceFn, u32)>,
1053    pub(super) environment: Environment,
1054    /// Runs the components' async tasks and timers.
1055    pub(super) executor: Rc<Executor>,
1056    /// Windows JS opened (`<Window>`) -> the owner and ref the Rust
1057    /// components inside them render under ([`Core::js_window_owner`]).
1058    js_windows: FxHashMap<NodeId, (crate::element::Owner, crate::element::desktop::WindowRef)>,
1059    /// What the platform last reported of the windows of the app's own:
1060    /// their state and title bar area, for the refs made after it.
1061    window_reports: FxHashMap<
1062        NodeId,
1063        (
1064            Option<crate::desktop::WindowState>,
1065            crate::geometry::Edges<Points>,
1066        ),
1067    >,
1068    /// The status bar's settings, shared by components, modules and tasks.
1069    pub(super) status_bars: crate::element::status_bar::StatusBars,
1070    /// Dialogs components show, by id: their answers.
1071    dialogs: FxHashMap<u32, AnswerSlot<crate::element::DialogReply>>,
1072    next_dialog: u32,
1073    /// Image sizes asked for (`Image.getSize`), by request id: their answers.
1074    image_infos: FxHashMap<u32, AnswerSlot<Result<ImageSize, String>>>,
1075    next_image_info: u32,
1076    /// Clipboard reads (`Clipboard.readText` / `hasText`), by request
1077    /// id: their answers.
1078    clipboard_reads: FxHashMap<u32, ClipboardRead>,
1079    next_clipboard_read: u32,
1080    /// Picks waiting for the platform's picker, by request.
1081    #[allow(clippy::type_complexity)]
1082    picks: FxHashMap<
1083        u32,
1084        (
1085            crate::picker::Pick,
1086            AnswerSlot<Vec<crate::picker::PickedFile>>,
1087        ),
1088    >,
1089    next_pick: u32,
1090    /// The sounds and players open, by id: where their events go.
1091    audio: FxHashMap<u32, crate::audio::AudioSink>,
1092    /// What notifications wait for ([`crate::notifications`]).
1093    notifications: Notifications,
1094    /// The links that open the app ([`crate::url_scheme`]).
1095    url_schemes: UrlScheme,
1096    second_instances: SecondInstances,
1097    open_files: OpenFiles,
1098    /// Calls of the embedding app's functions (`nsh/host`), by request id:
1099    /// their answers.
1100    host_calls:
1101        FxHashMap<u64, AnswerSlot<Result<crate::JsonValue, crate::host_channel::HostError>>>,
1102    next_host_call: u64,
1103    /// The calls and posts not handed to the engine yet
1104    /// ([`Core::take_host_requests`]).
1105    host_requests: Vec<crate::host_channel::HostRequest>,
1106    /// The host's events no Rust listener heard, until one of their names
1107    /// is added ([`Core::release_host_events`]).
1108    host_inbox: crate::host_channel::HostInbox,
1109    /// URLs being opened (`openUrl`), by request id: their answers.
1110    url_opens: FxHashMap<u32, AnswerSlot<bool>>,
1111    /// The clipboard writes sent to the platform waiting for its result,
1112    /// in the order sent ([`crate::EventKind::ClipboardWrite`]).
1113    pub(super) clipboard_writes:
1114        std::collections::VecDeque<AnswerSlot<crate::element::ClipboardWrite>>,
1115    /// Those not handed to the engine yet ([`Core::take_url_opens`]).
1116    url_requests: Vec<(u32, String)>,
1117    /// The language the app asked to show in (`Some(None)`: the user's
1118    /// again), for the engine ([`Core::take_locale_request`]).
1119    pub(super) locale_request: Option<Option<crate::platform::Locale>>,
1120    /// The language of the app's text last sent to an iOS or Android
1121    /// platform ([`Command::TextLocale`]).
1122    text_locale: Option<crate::platform::Locale>,
1123    /// The app listened to quit requests at the last commit: the platform
1124    /// was told its quit requests go to the app
1125    /// ([`crate::desktop::DesktopCommand::SetQuitOnRequest`]).
1126    asks_quit: bool,
1127    /// Functions for the platform's main thread, for the engine
1128    /// ([`Core::take_main_thread_tasks`]).
1129    main_thread: Vec<crate::main_thread::MainThreadTask>,
1130    next_url_open: u32,
1131    /// The app's settings pages being opened (`AppSettings.open`), by
1132    /// request id: their answers.
1133    app_settings_opens: FxHashMap<u32, AnswerSlot<Result<bool, crate::mobile::AppSettingsError>>>,
1134    next_app_settings_open: u32,
1135    /// Colors being picked on the screen, by request id: their answers.
1136    screen_colors: FxHashMap<u32, AnswerSlot<Option<crate::Hsla>>>,
1137    next_screen_color: u32,
1138    /// Requests on local paths (`pick_paths`, `open_path`, ...), by
1139    /// request id: their answers.
1140    file_requests: FxHashMap<u32, FileAnswer>,
1141    next_file_request: u32,
1142    /// HTTP requests of tasks (`ui::fetch`), by request id: what arrived
1143    /// so far and the answer.
1144    fetches: FxHashMap<u32, PendingFetch>,
1145    /// Requests not handed to the engine's network stack yet.
1146    fetch_requests: Vec<(u32, crate::platform::HttpRequest)>,
1147    next_fetch: u32,
1148    /// The ends of the animations components started and the values they
1149    /// read, by id.
1150    animations: FxHashMap<crate::animation::AnimationId, Awaited>,
1151    /// Elements to measure once this commit is laid out
1152    /// ([`crate::element::ElementRef::measure`]).
1153    pub(super) measures: Vec<(NodeId, AnswerSlot<Option<crate::Measurement>>)>,
1154    /// Lists to tell where their viewports start once this commit is laid
1155    /// out ([`crate::element::ElementRef::measure_scroll_position`]).
1156    pub(super) scroll_positions: Vec<(NodeId, AnswerSlot<Option<crate::ListScrollPosition>>)>,
1157    /// Elements whose transitions' time to tell once this commit is
1158    /// styled ([`crate::element::ElementRef::transition_time`]).
1159    pub(super) transition_times: Vec<(NodeId, AnswerSlot<std::time::Duration>)>,
1160    /// Elements whose text to tell once this commit is applied
1161    /// ([`crate::element::ElementRef::text_content`]).
1162    pub(super) text_contents: Vec<(NodeId, AnswerSlot<String>)>,
1163    /// Presses to pass on inside elements once this commit is laid out
1164    /// ([`crate::element::ElementRef::press_at`]).
1165    pub(super) presses: Vec<(NodeId, crate::PressEvent, AnswerSlot<bool>)>,
1166    /// Pointers to pass on inside elements as the next commit starts
1167    /// ([`crate::element::ElementRef::hover_at`]); `None`: it left.
1168    pub(super) hovers: Vec<(NodeId, Option<crate::MouseEvent>)>,
1169    /// The web views' downloads ([`crate::webview::downloads`]): the
1170    /// sessions, their files and the platform's replies.
1171    pub(super) downloads: crate::webview::downloads::Downloads,
1172    /// The next id of a platform command answering a web view request
1173    /// (shared by the downloads' commands).
1174    next_webview_request: u64,
1175    /// The components' own lists, by node.
1176    virtual_lists: FxHashMap<NodeId, VirtualListState>,
1177    /// Views JS made, waiting to be in the tree to make their view.
1178    waiting: Vec<NodeId>,
1179    /// Calls of components' methods made before their view was (a ref is
1180    /// given as its component is made, and the view registers what the
1181    /// methods act on): host, promise, call; run once the view is made.
1182    parked_methods: Vec<(NodeId, u32, crate::element::MethodCall)>,
1183    /// The row counts the cells of views' lists read (their positions), by
1184    /// list, each under a root of its own that goes with the list.
1185    list_counts: FxHashMap<NodeId, (crate::element::Owner, crate::element::Signal<usize>)>,
1186    /// The layouts of views' lists with bound parts, as applied last.
1187    pub(super) list_layouts: FxHashMap<NodeId, ListConfig>,
1188    /// The insets screens and modals reported (`onInsets`).
1189    insets: FxHashMap<NodeId, EdgeInsets>,
1190    /// JS listens to the back button (`BackHandler`) on the root.
1191    js_back: bool,
1192    /// JS listens to the back gesture's steps (`BackHandler.on("progress",
1193    /// ..)`) on the root.
1194    js_back_progress: bool,
1195    /// The app's listeners follow the back gesture under way: decided as it
1196    /// starts, so a gesture an overlay takes stays the overlay's to its end.
1197    back_gesture: bool,
1198    /// JS's keyboard shortcuts (`nsh/keymap`: the root's `Prop::Keymap`),
1199    /// which the root's table joins with the views'.
1200    js_keymap: Arc<crate::keymap::Keymap>,
1201    /// JS listens to the root's `KeyCommand`.
1202    js_keys: bool,
1203    /// The touches the components hear and their responder.
1204    pub(super) touch: super::touch::TouchState,
1205    /// Display frames and the layout direction.
1206    pub(super) services: super::services::Services,
1207    next_id: NodeId,
1208    dirty: Vec<NodeId>,
1209    /// A reused buffer.
1210    props: Vec<Prop>,
1211    /// The reactive graph of the components that run once.
1212    pub(super) runtime: crate::element::Runtime,
1213    /// What their bindings queued.
1214    pub(super) patches: super::views::Patches,
1215    /// Their views' regions, by id.
1216    pub(super) regions: FxHashMap<u32, super::views::RegionState>,
1217    pub(super) next_region: u32,
1218    /// The JS calls Rust posts (the engine's queue, shared with the
1219    /// script): a call posted during a synchronous call from JS waits for
1220    /// its op ([`RustCall::Post`]).
1221    posts: Posts,
1222    /// What the app's JS functions render for the views
1223    /// ([`crate::element::Renderer`]).
1224    pub(super) renders: super::renders::Renders,
1225    /// Nodes of views with the app's classes (`Element::app_class`): their
1226    /// own rules, the classes and what goes after them, resolved again
1227    /// when the tokens change.
1228    pub(super) app_classes: FxHashMap<NodeId, AppClass>,
1229}
1230
1231impl Default for Components {
1232    fn default() -> Self {
1233        Self {
1234            registry: Registry::default(),
1235            specs: FxHashMap::default(),
1236            tokens: Arc::new(Tokens::default()),
1237            app_tokens: Arc::new(Tokens::default()),
1238            host_tokens: None,
1239            instances: FxHashMap::default(),
1240            by_name: FxHashMap::default(),
1241            owners: FxHashMap::default(),
1242            release_generation: 0,
1243            released_hosts: FxHashSet::default(),
1244            #[cfg(test)]
1245            cleanup_work: Default::default(),
1246            #[cfg(test)]
1247            handler_visits: Default::default(),
1248            #[cfg(test)]
1249            placing_work: Default::default(),
1250            #[cfg(test)]
1251            position_work: Default::default(),
1252            #[cfg(test)]
1253            watch_work: Default::default(),
1254            #[cfg(test)]
1255            retag_work: Default::default(),
1256            #[cfg(test)]
1257            retag_rounds: Default::default(),
1258            slot_names: FxHashMap::default(),
1259            slot_hosts: FxHashMap::default(),
1260            slot_targets: FxHashMap::default(),
1261            adopted: FxHashMap::default(),
1262            fill_holders: FxHashSet::default(),
1263            styles: FxHashMap::default(),
1264            merges: FxHashMap::default(),
1265            filling: None,
1266            moved: Vec::new(),
1267            lists: FxHashMap::default(),
1268            environment: Environment::default(),
1269            executor: Rc::new(Executor::default()),
1270            js_windows: FxHashMap::default(),
1271            window_reports: FxHashMap::default(),
1272            status_bars: Default::default(),
1273            dialogs: FxHashMap::default(),
1274            next_dialog: 1,
1275            image_infos: FxHashMap::default(),
1276            next_image_info: 1,
1277            clipboard_reads: FxHashMap::default(),
1278            url_opens: FxHashMap::default(),
1279            clipboard_writes: Default::default(),
1280            url_requests: Vec::new(),
1281            locale_request: None,
1282            text_locale: None,
1283            asks_quit: false,
1284            main_thread: Vec::new(),
1285            next_url_open: 0,
1286            app_settings_opens: FxHashMap::default(),
1287            next_app_settings_open: 1,
1288            screen_colors: FxHashMap::default(),
1289            next_screen_color: 1,
1290            file_requests: FxHashMap::default(),
1291            next_file_request: 1,
1292            next_clipboard_read: 1,
1293            picks: FxHashMap::default(),
1294            next_pick: 1,
1295            audio: FxHashMap::default(),
1296            notifications: Notifications::default(),
1297            url_schemes: UrlScheme::default(),
1298            second_instances: SecondInstances::default(),
1299            open_files: OpenFiles::default(),
1300            host_calls: FxHashMap::default(),
1301            next_host_call: 1,
1302            host_requests: Vec::new(),
1303            host_inbox: Default::default(),
1304            web_evaluations: Default::default(),
1305            canvas_renders: Default::default(),
1306            fetches: FxHashMap::default(),
1307            fetch_requests: Vec::new(),
1308            next_fetch: 1,
1309            animations: FxHashMap::default(),
1310            measures: Vec::new(),
1311            scroll_positions: Vec::new(),
1312            transition_times: Vec::new(),
1313            text_contents: Vec::new(),
1314            presses: Vec::new(),
1315            hovers: Vec::new(),
1316            downloads: crate::webview::downloads::Downloads::default(),
1317            next_webview_request: 1,
1318            virtual_lists: FxHashMap::default(),
1319            list_counts: FxHashMap::default(),
1320            waiting: Vec::new(),
1321            parked_methods: Vec::new(),
1322            list_layouts: FxHashMap::default(),
1323            insets: FxHashMap::default(),
1324            js_back: false,
1325            js_back_progress: false,
1326            back_gesture: false,
1327            js_keymap: Arc::new(crate::keymap::Keymap::default()),
1328            js_keys: false,
1329            touch: super::touch::TouchState::default(),
1330            services: Default::default(),
1331            // Odd: JS allocates the even ids (1 is the root).
1332            next_id: 3,
1333            dirty: Vec::new(),
1334            props: Vec::new(),
1335            runtime: crate::element::Runtime::default(),
1336            patches: super::views::Patches::default(),
1337            regions: FxHashMap::default(),
1338            next_region: 1,
1339            posts: Posts::default(),
1340            renders: Default::default(),
1341            app_classes: FxHashMap::default(),
1342        }
1343    }
1344}
1345
1346impl Components {
1347    /// Whether `list` is one of the components' own lists (bound in the
1348    /// core).
1349    pub(super) fn is_virtual_list(&self, list: NodeId) -> bool {
1350        self.virtual_lists.contains_key(&list)
1351    }
1352
1353    pub(super) fn for_viewport(viewport: crate::Size<crate::Points>) -> Self {
1354        let mut components = Self::default();
1355        components.environment.window = viewport;
1356        // What components that run once read of the core.
1357        components.runtime.set_services(components.executor.clone());
1358        components
1359            .runtime
1360            .set_app_url(components.url_schemes.address.clone());
1361        components.runtime.set_environment(components.environment);
1362        components.runtime.set_tokens(components.tokens.clone());
1363        components
1364    }
1365
1366    pub(super) fn alloc(&mut self) -> NodeId {
1367        let id = self.next_id;
1368        self.next_id += 2;
1369        id
1370    }
1371
1372    pub(super) fn mark(&mut self, host: NodeId) {
1373        if let Some(inst) = self.instances.get_mut(&host)
1374            && !inst.dirty
1375        {
1376            inst.dirty = true;
1377            self.dirty.push(host);
1378        }
1379    }
1380
1381    /// `style` as rules, shared between the elements that have it (its
1382    /// static declarations: bound parts are applied by bindings).
1383    pub(super) fn lowered(&mut self, style: &StyleRefinement) -> std::rc::Rc<ClassList> {
1384        if style.is_bound() {
1385            return self.lowered(&style.static_part());
1386        }
1387        if let Some(list) = self.styles.get(style) {
1388            return list.clone();
1389        }
1390        if self.styles.len() >= STYLE_CACHE {
1391            self.styles.clear();
1392        }
1393        let list = std::rc::Rc::new(style.lower());
1394        self.styles.insert(style.clone(), list.clone());
1395        list
1396    }
1397}
1398
1399/// The inline style of `id`: the declarations of its `Style` prop, then
1400/// the animated values bound to it, then (on a host) the app's style.
1401fn inline_style(
1402    id: NodeId,
1403    inline: Option<&crate::StylePatch>,
1404    animated: &[(crate::StyleDecl, crate::element::LiveNode)],
1405    app: Option<&crate::StylePatch>,
1406) -> Op {
1407    let mut style = Box::<crate::Style>::default();
1408    let mut patch = crate::StylePatch::default();
1409    let inline = inline.map(|p| p.decls()).unwrap_or_default();
1410    let app = app.map(|p| p.decls()).unwrap_or_default();
1411    for decl in inline
1412        .iter()
1413        .chain(animated.iter().map(|(d, _)| d))
1414        .chain(app)
1415    {
1416        let _ = patch.push(&mut style, decl.clone());
1417    }
1418    Op::SetStyle { id, style, patch }
1419}
1420
1421fn same(a: &Option<std::rc::Rc<ClassList>>, b: &Option<std::rc::Rc<ClassList>>) -> bool {
1422    match (a, b) {
1423        (Some(a), Some(b)) => std::rc::Rc::ptr_eq(a, b),
1424        (None, None) => true,
1425        _ => false,
1426    }
1427}
1428
1429impl Components {
1430    /// The GPU renderer the sets registered as `name`.
1431    pub(super) fn gpu_renderer(&self, name: &str) -> Option<crate::gpu::GpuSource> {
1432        self.registry.registered_gpu_renderer(name).cloned()
1433    }
1434}
1435
1436impl<M: TextEngine> Core<M> {
1437    /// The components this core can render (from `nsh-base` and the
1438    /// like), and the design tokens their sets bring
1439    /// ([`Registry::tokens_from`]); set before the first op. Runs the
1440    /// sets' setup functions ([`Registry::setup`]).
1441    pub fn set_components(&mut self, registry: Registry) {
1442        if let Some(Ok((tokens, _))) = registry.tokens(None) {
1443            self.set_tokens(tokens);
1444        }
1445        {
1446            let _entered = self.components.runtime.enter();
1447            registry.run_setups();
1448        }
1449        self.components.registry = registry;
1450    }
1451
1452    /// Replaces the components of a running core with `registry`, a
1453    /// superset of what it had (a UI set registered after the app started:
1454    /// a web runtime's late `nsh_part_*`). What is mounted from then on may
1455    /// use the new components; the tokens stay the app's, and only the
1456    /// setup functions the old sets did not bring run.
1457    pub fn extend_components(&mut self, registry: Registry) {
1458        {
1459            let _entered = self.components.runtime.enter();
1460            registry.run_setups_not_in(&self.components.registry);
1461        }
1462        self.components.registry = registry;
1463        self.make_by_name();
1464    }
1465
1466    /// Makes the components made by name whose part is registered now.
1467    fn make_by_name(&mut self) {
1468        if self.components.by_name.is_empty() {
1469            return;
1470        }
1471        let _entered = self.components.runtime.enter();
1472        let hosts: Vec<NodeId> = self.components.by_name.keys().copied().collect();
1473        for host in hosts {
1474            let Some(waiting) = self.components.by_name.get(&host) else {
1475                continue;
1476            };
1477            let still = self
1478                .components
1479                .instances
1480                .get(&host)
1481                .is_some_and(|i| matches!(i.inner, Inner::Missing));
1482            if !still {
1483                self.components.by_name.remove(&host);
1484                continue;
1485            }
1486            let Some((spec, mut inner)) = self.components.registry.make_type(waiting.id) else {
1487                continue;
1488            };
1489            let waiting = self.components.by_name.remove(&host).expect("waiting");
1490            inner.place(host, waiting.owner);
1491            inner.set_props(waiting.props.as_any());
1492            // Its view is made in place of the empty one it showed.
1493            if let Some(inst) = self.components.instances.get_mut(&host) {
1494                inst.inner = Inner::Component(inner);
1495                inst.spec = Some(spec);
1496                inst.remake = true;
1497            }
1498            self.components.mark(host);
1499        }
1500    }
1501
1502    /// Makes `host` the host of component element `c`: by its type, or
1503    /// by its registered name ([`crate::element::ComponentElement::by_name`]).
1504    fn create_instance_for(&mut self, host: NodeId, c: &crate::element::builder::ComponentEl) {
1505        let Some(id) = c.by_name else {
1506            self.create_instance_of(host, c.name, c.make, c.spec);
1507            return;
1508        };
1509        if self.is_host(host) {
1510            return;
1511        }
1512        match self.components.registry.make_type(id) {
1513            Some((spec, inner)) => self.insert_instance(host, Some(spec), Inner::Component(inner)),
1514            None => {
1515                self.insert_instance(host, None, Inner::Missing);
1516                self.components.by_name.insert(
1517                    host,
1518                    ByName {
1519                        id,
1520                        props: c.props.clone_box(),
1521                        owner: crate::element::Owner::current(),
1522                    },
1523                );
1524                let name = crate::element::component::export_name(c.name);
1525                match PART_REQUESTER.with(|r| r.get()) {
1526                    Some(request) => request(name),
1527                    None => log::debug!("`{name}` waits for the part that registers it"),
1528                }
1529            }
1530        }
1531    }
1532
1533    /// Sets the props of `host`'s component from its element.
1534    fn set_element_props(&mut self, host: NodeId, props: &dyn crate::element::builder::AnyProps) {
1535        if let Some(waiting) = self.components.by_name.get_mut(&host) {
1536            waiting.props = props.clone_box();
1537            return;
1538        }
1539        if let Some(inst) = self.components.instances.get_mut(&host)
1540            && let Inner::Component(inner) = &mut inst.inner
1541        {
1542            inner.set_props(props.as_any());
1543        }
1544    }
1545
1546    /// `uiTheme` on the root: the app's theme file (`nsh.json`, `setTheme`),
1547    /// which the UI set that reads themes makes tokens of. What it cannot
1548    /// read is left out and the rest applies, so a bundle made by a newer
1549    /// NSH keeps its theme here.
1550    pub(super) fn set_ui_theme(&mut self, json: &str) {
1551        match self.components.registry.tokens(Some(json)) {
1552            Some(Ok((tokens, left_out))) => {
1553                for what in left_out {
1554                    log::warn!("theme: {what}, ignored");
1555                }
1556                self.set_tokens(tokens);
1557            }
1558            Some(Err(e)) => log::warn!("theme: {e}"),
1559            None => log::warn!("theme: no UI set reads themes"),
1560        }
1561    }
1562
1563    /// The app's design tokens; it is drawn with them unless the
1564    /// embedding app set its own ([`Core::set_host_tokens`]).
1565    pub fn set_tokens(&mut self, tokens: Tokens) {
1566        self.components.app_tokens = Arc::new(tokens);
1567        self.tokens_changed();
1568    }
1569
1570    /// The app's translations ([`crate::i18n`]): what `t!` and TS's `t`
1571    /// read from now on.
1572    pub fn set_translations(&mut self, translations: crate::i18n::Translations) {
1573        let _entered = self.components.runtime.enter();
1574        let stored = crate::element::global::<crate::i18n::Translations>();
1575        let env = self.components.environment;
1576        let before =
1577            crate::i18n::text_locale(&stored.get(), env.locale, env.locale_settings.languages);
1578        stored.set(translations);
1579        if crate::i18n::text_locale(&stored.get(), env.locale, env.locale_settings.languages)
1580            != before
1581        {
1582            self.localize_platform();
1583        }
1584    }
1585
1586    /// Merges `map` into this surface's translations and updates menus if the
1587    /// selected language changed.
1588    pub(crate) fn add_translations(
1589        &mut self,
1590        map: std::collections::HashMap<String, std::collections::HashMap<String, String>>,
1591    ) {
1592        if map.is_empty() {
1593            return;
1594        }
1595        let next = {
1596            let _entered = self.components.runtime.enter();
1597            crate::element::global::<crate::i18n::Translations>()
1598                .get_untracked()
1599                .extend(map)
1600        };
1601        self.set_translations(next);
1602    }
1603
1604    /// Re-localizes menus when translations updated in place changed the
1605    /// selected language.
1606    fn translations_changed(&mut self, before: &crate::i18n::Translations) {
1607        let _entered = self.components.runtime.enter();
1608        let current = crate::element::global::<crate::i18n::Translations>().get_untracked();
1609        let env = self.components.environment;
1610        if crate::i18n::text_locale(&current, env.locale, env.locale_settings.languages)
1611            != crate::i18n::text_locale(before, env.locale, env.locale_settings.languages)
1612        {
1613            self.localize_platform();
1614        }
1615    }
1616
1617    /// What NSH says itself on the platform uses the same language
1618    /// selection as the app's text: the menus it owns (macOS, Windows) and
1619    /// the screen reader's state words (iOS, Android).
1620    fn localize_platform(&mut self) {
1621        use crate::platform::Os;
1622        let _entered = self.components.runtime.enter();
1623        let env = self.components.environment;
1624        let desktop = matches!(env.os, Os::MacOs | Os::Windows)
1625            && env.idiom != crate::platform::Idiom::Terminal;
1626        if !desktop && !matches!(env.os, Os::Ios | Os::Android) {
1627            return;
1628        }
1629        let translations = crate::element::global::<crate::i18n::Translations>().get();
1630        let locale =
1631            crate::i18n::text_locale(&translations, env.locale, env.locale_settings.languages);
1632        if !desktop {
1633            if self.components.text_locale != Some(locale) {
1634                self.components.text_locale = Some(locale);
1635                self.commands
1636                    .push((crate::ROOT_ID, Command::TextLocale(locale)));
1637            }
1638            return;
1639        }
1640        let labels = crate::desktop::MenuLabels::for_locale(
1641            locale,
1642            self.components.environment.os == crate::platform::Os::MacOs,
1643        );
1644        let _ = self.apply_op(crate::Op::Command {
1645            id: crate::ROOT_ID,
1646            command: crate::Command::Desktop(Box::new(
1647                crate::desktop::DesktopCommand::SetMenuLabels(Box::new(labels)),
1648            )),
1649        });
1650    }
1651
1652    /// The language the app asked to show in since the last call
1653    /// (`Some(None)`: the user's again), which the engine applies to the
1654    /// environment it gives the core and JS.
1655    pub fn take_locale_request(&mut self) -> Option<Option<crate::platform::Locale>> {
1656        self.components.locale_request.take()
1657    }
1658
1659    /// The functions components, tasks and module functions asked to run
1660    /// on the platform's main thread since the last call
1661    /// ([`crate::element::run_on_main_thread`]), in order: the engine hands
1662    /// them to its sink after the commit.
1663    #[doc(hidden)]
1664    pub fn take_main_thread_tasks(&mut self) -> Vec<crate::main_thread::MainThreadTask> {
1665        std::mem::take(&mut self.components.main_thread)
1666    }
1667
1668    /// The embedding app's design tokens (`None`: the app's again): an app
1669    /// embedded in a native app looks like it, whatever the app sets.
1670    /// Text inherits its `foreground` token unless it sets its own color.
1671    pub fn set_host_tokens(&mut self, tokens: Option<Tokens>) {
1672        self.components.host_tokens = tokens.map(Arc::new);
1673        self.tokens_changed();
1674        // Embedded content inherits the host's foreground unless it sets its own.
1675        let classes = if self.components.host_tokens.is_some() {
1676            vec!["text-foreground".into()]
1677        } else {
1678            Vec::new()
1679        };
1680        self.set_classes(self.root, None, Some(classes));
1681    }
1682
1683    /// What [`Core::tokens`] become when the root's `uiTheme` (the app's
1684    /// theme file) is set, with the embedding app's tokens of now: JS reads
1685    /// them in the turn that sends the theme, before it reaches the core.
1686    pub fn theme_tokens(&self) -> crate::element::ThemeTokens {
1687        crate::element::ThemeTokens::new(
1688            self.components.registry.token_source(),
1689            self.components.host_tokens.clone(),
1690        )
1691    }
1692
1693    /// The design tokens the app is drawn with now: the app's, under the
1694    /// embedding app's. A new value (not the same `Arc`) when they change.
1695    pub fn tokens(&self) -> &Arc<Tokens> {
1696        &self.components.tokens
1697    }
1698
1699    /// The tokens drawn with now: a signal of the surface, so only the
1700    /// bindings that read them run again, and only when they changed.
1701    fn tokens_changed(&mut self) {
1702        let tokens = match &self.components.host_tokens {
1703            // The app's own tokens the host's do not have stay.
1704            Some(host) => Arc::new(host.over(&self.components.app_tokens)),
1705            None => self.components.app_tokens.clone(),
1706        };
1707        if *tokens == *self.components.tokens {
1708            self.components.tokens = tokens;
1709            return;
1710        }
1711        {
1712            let _entered = self.components.runtime.enter();
1713            self.components.tokens = tokens;
1714            self.components
1715                .runtime
1716                .set_tokens(self.components.tokens.clone());
1717        }
1718        // The platform's own controls (menus, Android's alerts) take their
1719        // colors from them.
1720        self.commands.push((
1721            crate::ROOT_ID,
1722            Command::Tokens(self.components.tokens.clone()),
1723        ));
1724        let font = self
1725            .components
1726            .tokens
1727            .font(crate::element::FONT_SANS)
1728            .map(|f| crate::style::FontFamily::new(f));
1729        self.set_default_font(font);
1730        self.class_tokens_changed();
1731    }
1732
1733    /// Mounts a Rust app's root component as the content of the root view;
1734    /// its view is made in the next commit.
1735    pub fn mount_root(&mut self, root: &Root) {
1736        if let Some(setting) = root.status_bar_ref() {
1737            self.components.status_bars.set_base(setting);
1738        }
1739        let _entered = self.components.runtime.enter();
1740        let Some(id) = self.make_component(root.element(), |_, _| {}) else {
1741            return log::error!("the root is not a component");
1742        };
1743        let _ = self.apply_op(Op::Insert {
1744            parent: ROOT_ID,
1745            child: id,
1746            before: None,
1747        });
1748        self.mount_opened_windows();
1749        self.own_direction();
1750    }
1751
1752    /// Mounts what renders the windows `open_window` opens, beside the
1753    /// app's root (desktops): a Rust app's ([`Self::mount_root`]) or a TSX
1754    /// app's, whose built-in windows (the update prompt) open the same way.
1755    pub fn mount_opened_windows(&mut self) {
1756        let _entered = self.components.runtime.enter();
1757        if !crate::element::os().is_desktop() {
1758            return;
1759        }
1760        use crate::element::Component as _;
1761        let host = crate::element::desktop::OpenedWindowsHost::element(()).into_element();
1762        if let Some(host) = self.make_component(host, |_, _| {}) {
1763            let _ = self.apply_op(Op::Insert {
1764                parent: ROOT_ID,
1765                child: host,
1766                before: None,
1767            });
1768        }
1769    }
1770
1771    /// Makes the host of component element `el` (`None`: `el` is not a
1772    /// component), out of the tree; `made` sees its node first, before it
1773    /// renders.
1774    pub(super) fn make_component(
1775        &mut self,
1776        el: crate::element::AnyElement,
1777        made: impl FnOnce(&mut Self, NodeId),
1778    ) -> Option<NodeId> {
1779        let mut el = el.0;
1780        let ElKind::Component(c) = std::mem::replace(&mut el.kind, ElKind::Plain) else {
1781            return None;
1782        };
1783        let id = self.components.alloc();
1784        let _ = self.apply_op(Op::Create { id, tag: el.tag });
1785        made(self, id);
1786        self.create_instance_for(id, &c);
1787        self.set_element_props(id, c.props.as_ref());
1788        Some(id)
1789    }
1790
1791    /// How the sets make the views' built-in scroll bars.
1792    pub(super) fn scrollbar_source(&self) -> Option<crate::element::ScrollbarSource> {
1793        self.components.registry.scrollbar_source()
1794    }
1795
1796    /// The environment components read ([`crate::element::window`]
1797    /// and the like), as the platform reports it: what read a part that
1798    /// changed runs again. `dark` is the system's: the app's
1799    /// appearance wins over it ([`Core::set_appearance`]).
1800    pub fn set_environment(&mut self, mut environment: Environment) {
1801        let _entered = self.components.runtime.enter();
1802        environment.rtl = self.surface_rtl(environment.rtl);
1803        self.system_dark = environment.dark;
1804        environment.dark = self.shown_dark();
1805        self.apply_environment(environment);
1806    }
1807
1808    /// Whether the platform's performance monitor measures
1809    /// (`fpsEnabled()`): what read it runs again.
1810    pub fn set_perf_monitor(&mut self, enabled: bool) {
1811        self.components.runtime.set_perf_monitor(enabled);
1812    }
1813
1814    /// What the performance monitor measured last (`perfStats()`; `None`
1815    /// while it does not measure): what read it runs again.
1816    pub fn set_perf_stats(&mut self, stats: Option<crate::platform::PerfStats>) {
1817        self.components.runtime.set_perf_stats(stats);
1818    }
1819
1820    /// The displays components read ([`crate::element::desktop::displays`]),
1821    /// as the platform reports them: what read them runs again.
1822    pub fn set_displays(&mut self, displays: Arc<[crate::desktop::Display]>) {
1823        self.components.runtime.set_displays(displays);
1824    }
1825
1826    /// The environment components read is now `environment`.
1827    pub(super) fn apply_environment(&mut self, environment: Environment) {
1828        let _entered = self.components.runtime.enter();
1829        let changed = self.components.environment != environment;
1830        let language_changed = self.components.environment.idiom != environment.idiom
1831            || self.components.environment.os != environment.os
1832            || self.components.environment.locale != environment.locale
1833            || self.components.environment.locale_settings.languages
1834                != environment.locale_settings.languages;
1835        let keyboard_moved =
1836            self.components.environment.keyboard_height != environment.keyboard_height;
1837        self.keyboard_moved |= keyboard_moved;
1838        // The room the root view's anchored overlays keep to leaves the
1839        // keyboard out (`Core::overlay_area`): laid out and placed again.
1840        if keyboard_moved && self.root_overlay_shown() {
1841            self.needs_layout = true;
1842        }
1843        let ratio = self.components.environment.pixel_ratio;
1844        let window = self.components.environment.window;
1845        self.components.environment = environment;
1846        // Width and orientation variants follow the window `windowSize()`
1847        // reports (`Core::class_window`).
1848        if window != environment.window {
1849            self.restyle_where(crate::tailwind::deps::WIDTH | crate::tailwind::deps::HEIGHT);
1850        }
1851        if ratio != environment.pixel_ratio {
1852            self.repick_images(ratio, environment.pixel_ratio);
1853        }
1854        // Frames and text measurements are rounded to device pixels.
1855        self.pixel_ratio_changed(environment.pixel_ratio);
1856        // On a grid surface, lengths and frames are put on its Cells.
1857        self.cell_changed(environment.cell, environment.dark);
1858        if changed {
1859            // What reads a part that changed runs again.
1860            self.components.runtime.set_environment(environment);
1861        }
1862        if language_changed {
1863            self.localize_platform();
1864        }
1865        // A main window that keeps its placement saves it as it changes.
1866        if let Some(state) = environment.window_state {
1867            self.keep_window_placement(crate::ROOT_ID, &state);
1868        }
1869    }
1870
1871    /// The surface's size changed (the environment's window).
1872    pub(super) fn components_viewport(&mut self, size: crate::Size<crate::Points>) {
1873        let environment = Environment {
1874            window: size,
1875            ..self.components.environment
1876        };
1877        self.apply_environment(environment);
1878    }
1879
1880    /// Drops `ops` without applying them (the script was stopped): the
1881    /// calls into Rust among them are not made, and the promises waiting
1882    /// for them reject (their replies are in the next events); a JS call
1883    /// parked behind one is dropped.
1884    pub fn discard_ops(&mut self, ops: impl IntoIterator<Item = Op>) {
1885        for op in ops {
1886            if let Op::Rust(RustOp { call, run }) = op {
1887                // What the call holds (a post's place: released) (its arguments: instances, callbacks)
1888                // goes now.
1889                drop_caught(run);
1890                self.settle(call, Err("the script stopped before the call ran".into()));
1891            }
1892        }
1893    }
1894
1895    /// The queue of the JS calls Rust posts: the one the engine hands the
1896    /// script too.
1897    pub fn set_posts(&mut self, posts: Posts) {
1898        self.components.posts = posts;
1899    }
1900
1901    /// Wakes the engine when a component's task is woken (from any
1902    /// thread): it then calls [`Self::run_component_tasks`].
1903    pub fn set_task_notify(&mut self, notify: Arc<dyn Fn() + Send + Sync>) {
1904        self.components.executor.set_notify(notify.clone());
1905        self.components.downloads.set_notify(notify);
1906    }
1907
1908    /// Where a platform's last stop acknowledgement goes after this core's
1909    /// engine is gone: the engine's control handle keeps it, and the core
1910    /// registers its staging directories and cancel requests with it.
1911    #[doc(hidden)]
1912    pub fn set_download_cleanup(&mut self, cleanup: crate::webview::downloads::DownloadCleanup) {
1913        self.components.downloads.set_cleanup(cleanup);
1914    }
1915
1916    /// The tokio runtime the components' tasks are polled in the context
1917    /// of (their timers, IO and background work run on it).
1918    pub fn set_task_runtime(&mut self, runtime: tokio::runtime::Handle) {
1919        self.components.executor.set_runtime(runtime);
1920    }
1921
1922    /// When the components' soonest timer is due ([`crate::element::timer`]):
1923    /// the engine wakes then and runs their tasks.
1924    pub fn next_task_timer(&self) -> Option<crate::time::Instant> {
1925        self.components.executor.next_timer()
1926    }
1927
1928    /// Runs the components' woken tasks, with the state changes they ask
1929    /// for, until they all wait.
1930    pub fn run_component_tasks(&mut self) {
1931        let _entered = self.components.runtime.enter();
1932        let executor = self.components.executor.clone();
1933        executor.fire_timers(crate::time::now());
1934        // A task that keeps waking itself cannot hold the engine.
1935        for _ in 0..MAX_TASK_ROUNDS {
1936            let polled = executor.poll_ready();
1937            let actions = executor.take_actions();
1938            if !polled && actions.is_empty() {
1939                return;
1940            }
1941            for action in actions {
1942                self.apply_action(action);
1943            }
1944            for (host, message) in executor.take_failures() {
1945                self.component_failed(host, message);
1946            }
1947        }
1948    }
1949
1950    /// Whether something runs as the app quits ([`crate::element::desktop::on_app_quit`],
1951    /// `Application.on("quit")`): the engine gives it time to.
1952    pub fn has_quit_listeners(&self) -> bool {
1953        !self.components.executor.quit.borrow().is_empty()
1954    }
1955
1956    /// The app quits: starts each quit listener's work, oldest first, as
1957    /// tasks the engine runs ([`Core::run_component_tasks`]) until
1958    /// [`Core::quit_pending`] is false or
1959    /// [`QUIT_TIMEOUT`](crate::element::desktop::QUIT_TIMEOUT) has passed.
1960    /// Whether any started.
1961    pub fn start_quit(&mut self) -> bool {
1962        let _entered = self.components.runtime.enter();
1963        let executor = self.components.executor.clone();
1964        let listeners = executor.quit.borrow().all();
1965        for listener in listeners {
1966            match caught(|| listener()) {
1967                Ok(future) => {
1968                    let pending = crate::element::quit::Pending::new(&executor.quitting);
1969                    // Detached: it runs until it ends or the engine stops.
1970                    drop(crate::element::task::spawn_future(&executor, async move {
1971                        future.await;
1972                        drop(pending);
1973                    }));
1974                }
1975                Err(message) => log::error!(target: "js", "a quit listener failed: {message}"),
1976            }
1977        }
1978        self.apply_actions();
1979        self.quit_pending()
1980    }
1981
1982    /// The user asked to quit while the app listens to quit requests:
1983    /// each listener hears it, oldest first.
1984    fn quit_requested(&mut self) {
1985        let _entered = self.components.runtime.enter();
1986        let listeners = self.components.executor.quit_requests.borrow().all();
1987        for listener in listeners {
1988            if let Err(message) = caught(|| listener()) {
1989                log::error!(target: "js", "a quit request listener failed: {message}");
1990            }
1991        }
1992        self.apply_actions();
1993    }
1994
1995    /// The OS asked the app to show itself: each reopen listener hears it,
1996    /// oldest first. The app opens or focuses the window it wants.
1997    #[doc(hidden)]
1998    pub fn reopened(&mut self) {
1999        let _entered = self.components.runtime.enter();
2000        let listeners = self.components.executor.reopens.borrow().all();
2001        for listener in listeners {
2002            if let Err(message) = caught(|| listener()) {
2003                log::error!(target: "js", "a reopen listener failed: {message}");
2004            }
2005        }
2006        self.apply_actions();
2007    }
2008
2009    /// The app's last window went: each listener hears it, oldest first.
2010    pub(crate) fn last_window_closed(&mut self) {
2011        let _entered = self.components.runtime.enter();
2012        let listeners = self.components.executor.last_window_closed.borrow().all();
2013        for listener in listeners {
2014            if let Err(message) = caught(|| listener()) {
2015                log::error!(target: "js", "a last window closed listener failed: {message}");
2016            }
2017        }
2018        self.apply_actions();
2019    }
2020
2021    /// Tells the platform whether its quit requests go to the app, when
2022    /// that changed since the last call (a listener came or went): whether
2023    /// it did.
2024    pub(super) fn sync_quit_requests(&mut self) -> bool {
2025        let asks = !self.components.executor.quit_requests.borrow().is_empty();
2026        if asks == self.components.asks_quit {
2027            return false;
2028        }
2029        self.components.asks_quit = asks;
2030        let _ = self.apply_op(crate::Op::Command {
2031            id: crate::ROOT_ID,
2032            command: crate::Command::Desktop(Box::new(
2033                crate::desktop::DesktopCommand::SetQuitOnRequest(!asks),
2034            )),
2035        });
2036        true
2037    }
2038
2039    /// Whether the work quit listeners started is still running.
2040    pub fn quit_pending(&self) -> bool {
2041        self.components.executor.quitting.get() > 0
2042    }
2043
2044    /// Whether a JS call of an `async fn` into Rust (a native module's, a
2045    /// class's) has not answered yet: its answer comes from elsewhere (a
2046    /// request made in Rust, another thread), which nothing else counts.
2047    pub fn async_calls_pending(&self) -> bool {
2048        self.components.executor.calls.get() > 0
2049    }
2050
2051    /// Runs the closures that waited for the app's answer to the events
2052    /// handed to JS before this commit ([`crate::element::after_answer`]),
2053    /// each under its owner; one whose owner went is dropped unrun.
2054    pub(super) fn run_answers(&mut self) {
2055        let _entered = self.components.runtime.enter();
2056        for answer in self.components.executor.take_due_answers() {
2057            let crate::element::AfterAnswer { owner, f } = answer;
2058            let result = if owner == crate::element::Owner::detached() {
2059                caught(f)
2060            } else if owner.is_live() {
2061                caught(|| owner.scope(f))
2062            } else {
2063                drop_caught(f);
2064                continue;
2065            };
2066            if let Err(message) = result {
2067                match self.host_of_owner(owner) {
2068                    Some(host) => self.component_failed(host, message),
2069                    None => {
2070                        log::error!(target: "js", "a closure after the app's answer failed: {message}")
2071                    }
2072                }
2073            }
2074            self.apply_actions();
2075        }
2076    }
2077
2078    /// Whether `id` is a component's host.
2079    pub(super) fn is_host(&self, id: NodeId) -> bool {
2080        self.components.instances.contains_key(&id)
2081    }
2082
2083    /// Ops from JS on a component's host take its place; others pass
2084    /// (`Some`).
2085    pub(super) fn intercept(&mut self, op: Op) -> Result<Option<Op>, ApplyError> {
2086        // The app's elements that take a slot's props: their props combine
2087        // with the component's ([`super::slots`]).
2088        // A component's host among them takes them from its view: JS's
2089        // ops on it are its component's.
2090        if !self.components.adopted.is_empty()
2091            && let Op::SetProp { id, .. } | Op::Listen { id, .. } | Op::Release { id } = &op
2092            && self.components.adopted.contains_key(id)
2093            && !self.is_host(*id)
2094        {
2095            return Ok(self.js_slot_op(op));
2096        }
2097        match op {
2098            // The app's style on a host goes after the root's own.
2099            Op::SetStyle { id, patch, .. } if self.is_host(id) => {
2100                let inst = self.components.instances.get_mut(&id).expect("host");
2101                inst.app_style = (!patch.is_empty()).then_some(patch);
2102                // The node's own style is the view's that makes it, then
2103                // what is given it.
2104                let base = self.base_of(id);
2105                let cx = self.root_context_of(base).expect("a host");
2106                let app = if cx.combined {
2107                    cx.app
2108                } else {
2109                    self.components.instances[&base].app_style.clone()
2110                };
2111                let (inline, animated) = match &self.components.instances[&base].root {
2112                    Some(root) => (root.attrs.inline.clone(), root.attrs.animated().to_vec()),
2113                    None => (None, Vec::new()),
2114                };
2115                Ok(Some(inline_style(
2116                    id,
2117                    inline.as_deref(),
2118                    &animated,
2119                    app.as_ref(),
2120                )))
2121            }
2122            // A render's holder joins its host: placed in its placeholder.
2123            Op::Insert { parent, child, .. }
2124                if self.is_host(parent) && self.is_render_holder(child) =>
2125            {
2126                self.insert_render_holder(parent, child);
2127                Ok(None)
2128            }
2129            Op::Remove { parent, child }
2130                if self.is_host(parent) && self.is_render_holder(child) =>
2131            {
2132                self.remove_render_holder(child, false);
2133                Ok(None)
2134            }
2135            Op::Release { id } if self.is_render_holder(id) => {
2136                self.remove_render_holder(id, true);
2137                Ok(Some(Op::Release { id }))
2138            }
2139            // A slot's node joins its host: the view places it.
2140            Op::Insert { parent, child, .. }
2141                if self.is_host(parent) && self.components.slot_names.contains_key(&child) =>
2142            {
2143                let name = self.components.slot_names[&child].clone();
2144                let inst = self.components.instances.get_mut(&parent).expect("host");
2145                let Some(slot) = inst.spec.as_ref().and_then(|s| s.holder(&name)) else {
2146                    log::warn!(target: "js", "the component has no slot `{name}`");
2147                    self.detach_id(child);
2148                    return Ok(None);
2149                };
2150                inst.slots.retain(|(_, n)| *n != child);
2151                inst.slots.push((slot, child));
2152                self.components.slot_hosts.insert(child, parent);
2153                self.components.mark(parent);
2154                Ok(None)
2155            }
2156            Op::Remove { parent, child }
2157                if self.is_host(parent) && self.components.slot_names.contains_key(&child) =>
2158            {
2159                self.unslot(child);
2160                self.detach_id(child);
2161                Ok(None)
2162            }
2163            // A component's list gets a cell: the component wraps its rows.
2164            Op::Insert { parent, child, .. }
2165                if self.components.slot_hosts.contains_key(&parent) && self.is_list(parent) =>
2166            {
2167                self.apply_op(op)?;
2168                if let Some((place, _)) = self.components.lists.get(&parent).cloned() {
2169                    self.wrap_row(child, place);
2170                }
2171                Ok(None)
2172            }
2173            Op::Remove { parent, .. }
2174                if self.components.slot_hosts.contains_key(&parent) && self.is_list(parent) =>
2175            {
2176                Ok(Some(op))
2177            }
2178            // A slot filled or emptied: the component's slot prop follows
2179            // (it is marked).
2180            Op::Insert { parent, .. } | Op::Remove { parent, .. }
2181                if self.components.slot_hosts.contains_key(&parent) =>
2182            {
2183                let empty = |core: &Self| {
2184                    core.key(parent)
2185                        .map_or(true, |k| core.nodes[k as usize].children.is_empty())
2186                };
2187                let before = empty(self);
2188                self.apply_op(op)?;
2189                if empty(self) != before {
2190                    let host = self.components.slot_hosts[&parent];
2191                    self.components.mark(host);
2192                }
2193                // The slot's props follow its one element.
2194                self.retarget_slot(parent, None);
2195                Ok(None)
2196            }
2197            Op::Release { id } if self.components.slot_names.contains_key(&id) => {
2198                self.unslot(id);
2199                self.components.slot_names.remove(&id);
2200                self.components.lists.remove(&id);
2201                self.forget_list_count(id);
2202                Ok(Some(Op::Release { id }))
2203            }
2204            // The number of rows changed: the rows' wrappers may depend on
2205            // it (the last row). They read it from a signal; one that does
2206            // not bind its row is built again.
2207            Op::SetProp {
2208                id,
2209                prop: Prop::Count(count),
2210            } if self.components.lists.contains_key(&id) => {
2211                let key = self.key(id)?;
2212                self.apply_op(Op::SetProp {
2213                    id,
2214                    prop: Prop::Count(count),
2215                })?;
2216                // A splice before may have changed the list's count already.
2217                let seen = &mut self.components.lists.get_mut(&id).expect("list").1;
2218                if std::mem::replace(seen, count) != count {
2219                    // A view's wrappers read it.
2220                    if let Some(&(_, signal)) = self.components.list_counts.get(&id) {
2221                        signal.set(count as usize);
2222                    }
2223                    let cells: Vec<NodeId> = self.nodes[key as usize]
2224                        .children
2225                        .iter()
2226                        .map(|&c| self.nodes[c as usize].id)
2227                        .collect();
2228                    for cell in cells {
2229                        let binds = self.components.instances.get(&cell).is_some_and(|inst| {
2230                            inst.row_index.is_some() && inst.cell_owner.is_some_and(|o| o.is_live())
2231                        });
2232                        if !binds {
2233                            self.components.mark(cell);
2234                        }
2235                    }
2236                }
2237                Ok(None)
2238            }
2239            // A row cell shows another row: its wrapper's position follows
2240            // (one that does not bind its row is built again).
2241            Op::SetProp {
2242                id,
2243                prop: Prop::CellIndex(index),
2244            } if self.is_host(id) => {
2245                let inst = self.components.instances.get_mut(&id).expect("host");
2246                if let Inner::Row { index: current, .. } = &mut inst.inner
2247                    && *current != index as usize
2248                {
2249                    *current = index as usize;
2250                    match inst.row_index {
2251                        // A view's wrapper keeps its content.
2252                        Some(row) if inst.cell_owner.is_some_and(|o| o.is_live()) => {
2253                            row.set(index as usize);
2254                        }
2255                        _ => self.components.mark(id),
2256                    }
2257                }
2258                Ok(Some(op))
2259            }
2260            Op::Insert {
2261                parent,
2262                child,
2263                before,
2264            } if self.is_host(parent) => {
2265                // A raw text run (`<Button>Open</Button>`) has no node
2266                // until a use needs one: the view places it, so it does.
2267                let run = self.runs.contains_key(&child);
2268                self.materialize_run(child)?;
2269                let key = self.key(child)?;
2270                let is_text = matches!(self.nodes[key as usize].kind, Kind::Text | Kind::RawText);
2271                let inst = self.components.instances.get_mut(&parent).expect("host");
2272                let was_empty = inst.js_children.is_empty();
2273                let moved = inst.js_children.contains(&child);
2274                inst.forget_js_child(child);
2275                let at = before.and_then(|b| inst.js_children.iter().position(|&c| c == b));
2276                inst.js_children
2277                    .insert(at.unwrap_or(inst.js_children.len()), child);
2278                if is_text {
2279                    inst.js_texts.insert(child);
2280                }
2281                let place = inst.children_at;
2282                inst.js_children_changed();
2283                if was_empty || place == Placement::Each {
2284                    self.components.mark(parent);
2285                }
2286                self.join_content(child);
2287                match place {
2288                    // Before its next JS sibling, else before what the
2289                    // view puts after the children.
2290                    Placement::At(p, anchor) => {
2291                        let anchor = self.anchor_node(anchor);
2292                        self.apply_op(Op::Insert {
2293                            parent: p,
2294                            child,
2295                            before: at.and(before).or(anchor),
2296                        })?;
2297                        if run
2298                            && self
2299                                .key(p)
2300                                .is_ok_and(|k| self.nodes[k as usize].kind != Kind::Text)
2301                        {
2302                            let text = self.key(child).map_or("", |k| &self.nodes[k as usize].text);
2303                            log::warn!(
2304                                target: "js",
2305                                "text in a component's children is not shown: text shows in a <Text> (`<Text>{text}</Text>`)"
2306                            );
2307                        }
2308                    }
2309                    Placement::Nested(nested, anchor) => {
2310                        let anchor = self.anchor_node(anchor);
2311                        self.join_nested_at(nested, child, at.and(before).or(anchor));
2312                    }
2313                    // Its wrapper is the view's (a region of them, keyed
2314                    // by the child): a child moved among the others keeps
2315                    // its wrapper, which the region moves.
2316                    Placement::Each if moved => {}
2317                    Placement::Each => self.detach_id(child),
2318                    Placement::None => self.detach_id(child),
2319                }
2320                Ok(None)
2321            }
2322            Op::Remove { parent, child } if self.is_host(parent) => {
2323                let inst = self.components.instances.get_mut(&parent).expect("host");
2324                inst.forget_js_child(child);
2325                inst.js_children_changed();
2326                let place = inst.children_at;
2327                if inst.js_children.is_empty() || place == Placement::Each {
2328                    self.components.mark(parent);
2329                }
2330                self.unplace(place, child);
2331                Ok(None)
2332            }
2333            // A host attribute: its root's node takes it over its own.
2334            Op::SetProp { id, prop }
2335                if js_host_attribute(&prop)
2336                    && self
2337                        .components
2338                        .instances
2339                        .get(&id)
2340                        .is_some_and(|i| matches!(i.inner, Inner::Component(_))) =>
2341            {
2342                let inst = self.components.instances.get_mut(&id).expect("host");
2343                let before = inst.js_host.len();
2344                // Cleared (set to its default): none given, the root's own
2345                // come back.
2346                if crate::element::host::reset(&prop).as_ref() == Some(&prop) {
2347                    inst.js_host
2348                        .retain(|p| !crate::element::host::same_kind(p, &prop));
2349                    if inst.js_host.len() == before {
2350                        return Ok(None);
2351                    }
2352                } else if inst.js_host.contains(&prop) {
2353                    return Ok(None);
2354                } else {
2355                    crate::element::host::set_in(&mut inst.js_host, prop);
2356                }
2357                // Before its view is made, its first render takes them.
2358                if inst.root.is_some() {
2359                    inst.given_changed = true;
2360                    self.components.mark(id);
2361                }
2362                Ok(None)
2363            }
2364            Op::SetProp {
2365                id,
2366                prop: Prop::Class(class),
2367            } if self.is_host(id) => {
2368                let inst = self.components.instances.get_mut(&id).expect("host");
2369                inst.class = class;
2370                self.update_user_class(id);
2371                Ok(None)
2372            }
2373            Op::SetProp {
2374                id,
2375                prop: Prop::ClassList(list),
2376            } if self.is_host(id) => {
2377                let inst = self.components.instances.get_mut(&id).expect("host");
2378                inst.class_list = list;
2379                self.update_user_class(id);
2380                Ok(None)
2381            }
2382            // The root listens to the back button while JS or a component
2383            // does.
2384            Op::Listen {
2385                id: crate::ROOT_ID,
2386                event: EventKind::BackPress,
2387                enabled,
2388            } => {
2389                self.components.js_back = enabled;
2390                let rust = !self.components.executor.back.borrow().list.is_empty();
2391                Ok(Some(Op::Listen {
2392                    id: crate::ROOT_ID,
2393                    event: EventKind::BackPress,
2394                    enabled: enabled || rust,
2395                }))
2396            }
2397            // The root listens to the back gesture's steps while JS or a
2398            // component does.
2399            Op::Listen {
2400                id: crate::ROOT_ID,
2401                event: EventKind::BackProgress,
2402                enabled,
2403            } => {
2404                self.components.js_back_progress = enabled;
2405                let rust = !self
2406                    .components
2407                    .executor
2408                    .back_progress
2409                    .borrow()
2410                    .list
2411                    .is_empty();
2412                Ok(Some(Op::Listen {
2413                    id: crate::ROOT_ID,
2414                    event: EventKind::BackProgress,
2415                    enabled: enabled || rust,
2416                }))
2417            }
2418            // The surface's shortcuts are JS's and the views'.
2419            Op::SetProp {
2420                id: crate::ROOT_ID,
2421                prop: Prop::Keymap(keymap),
2422            } => {
2423                self.components.js_keymap = keymap;
2424                Ok(Some(Op::SetProp {
2425                    id: crate::ROOT_ID,
2426                    prop: Prop::Keymap(self.keymap()),
2427                }))
2428            }
2429            Op::Listen {
2430                id: crate::ROOT_ID,
2431                event: EventKind::KeyCommand,
2432                enabled,
2433            } => {
2434                self.components.js_keys = enabled;
2435                let rust = !self.components.executor.keys.borrow().list.is_empty();
2436                Ok(Some(Op::Listen {
2437                    id: crate::ROOT_ID,
2438                    event: EventKind::KeyCommand,
2439                    enabled: enabled || rust,
2440                }))
2441            }
2442            // The component's events come from the core, not from the view.
2443            Op::Listen {
2444                id,
2445                event: EventKind::NativeEvent,
2446                ..
2447            } if self.is_host(id) => Ok(None),
2448            Op::Listen { id, event, enabled } if self.is_host(id) => {
2449                let inst = self.components.instances.get_mut(&id).expect("host");
2450                inst.js_events.set(event, enabled);
2451                Ok(Some(self.host_listen(id, event)))
2452            }
2453            Op::Rust(op) => {
2454                self.run_rust(op);
2455                Ok(None)
2456            }
2457            Op::Release { id } if self.is_host(id) => {
2458                self.release_instance(id);
2459                Ok(Some(Op::Release { id }))
2460            }
2461            op => Ok(Some(op)),
2462        }
2463    }
2464
2465    /// Whether the host `id`'s node listens to `event` for someone outside
2466    /// its component's view: JS on the host, or a view above giving an
2467    /// element of this component (or of one whose root it is) a listener.
2468    fn outside_listens(&self, id: NodeId, event: EventKind) -> bool {
2469        let mut at = Some(self.base_of(id));
2470        while let Some(host) = at {
2471            let Some(inst) = self.components.instances.get(&host) else {
2472                break;
2473            };
2474            if inst.js_events.contains(event) || inst.given_events.contains(event) {
2475                return true;
2476            }
2477            at = inst.above;
2478        }
2479        false
2480    }
2481
2482    /// What the host `id`'s node listens to of `event`: its root's own,
2483    /// the slot whose props it takes and those outside its view.
2484    fn host_listen(&mut self, id: NodeId, event: EventKind) -> Op {
2485        let outside = self.outside_listens(id, event);
2486        let base = self.base_of(id);
2487        let own = self.components.instances[&base]
2488            .root
2489            .as_ref()
2490            .is_some_and(|r| r.events.contains(event));
2491        let slot = self.target_listens(base, event, outside || own);
2492        Op::Listen {
2493            id,
2494            event,
2495            enabled: outside || own || slot,
2496        }
2497    }
2498
2499    /// Gives the nested component on `id` the listeners `handlers` of the
2500    /// view it is in (in place of what that view gave it before): its node
2501    /// listens to their events as long as they are given.
2502    pub(super) fn set_given_handlers(
2503        &mut self,
2504        id: NodeId,
2505        handlers: Vec<(EventKind, Listener<EventPayload>)>,
2506    ) {
2507        let mut events = EventMask::default();
2508        for (kind, _) in &handlers {
2509            events.set(*kind, true);
2510        }
2511        let Some(inst) = self.components.instances.get_mut(&id) else {
2512            return;
2513        };
2514        let old = std::mem::replace(&mut inst.given_events, events);
2515        inst.given_handlers = handlers;
2516        let mut changed = old.bits() ^ events.bits();
2517        while changed != 0 {
2518            let kind = EventKind::ALL[changed.trailing_zeros() as usize];
2519            changed &= changed - 1;
2520            let op = self.host_listen(id, kind);
2521            let _ = self.apply_op(op);
2522        }
2523    }
2524
2525    /// Runs the listeners of `kind` the views above give the host `base`
2526    /// (and the components whose root it is), each in the component whose
2527    /// view gave it; false when none was given.
2528    fn handle_given(&mut self, base: NodeId, kind: EventKind, payload: &EventPayload) -> bool {
2529        let mut listeners = Vec::new();
2530        let mut at = Some(base);
2531        while let Some(host) = at {
2532            let Some(inst) = self.components.instances.get(&host) else {
2533                break;
2534            };
2535            if inst.given_events.contains(kind)
2536                && let Some(&owner) = self.components.owners.get(&host)
2537            {
2538                listeners.extend(
2539                    inst.given_handlers
2540                        .iter()
2541                        .filter(|(k, _)| *k == kind)
2542                        .map(|(_, l)| (owner, l.clone())),
2543                );
2544            }
2545            at = inst.above;
2546        }
2547        let mut handled = false;
2548        for (owner, listener) in listeners {
2549            handled |= self.run_listener(owner, &listener, payload);
2550        }
2551        handled
2552    }
2553
2554    /// Whether JS listens to `kind` on the host whose node `base` makes
2555    /// (the top one of its chain).
2556    fn js_listens(&self, base: NodeId, kind: EventKind) -> bool {
2557        let mut at = Some(base);
2558        while let Some(host) = at {
2559            let Some(inst) = self.components.instances.get(&host) else {
2560                break;
2561            };
2562            if inst.js_events.contains(kind) {
2563                return true;
2564            }
2565            at = inst.above;
2566        }
2567        false
2568    }
2569
2570    /// The number of rows of the list cell `cell` is in.
2571    fn rows_of_cell(&self, cell: NodeId) -> usize {
2572        let Ok(key) = self.key(cell) else { return 0 };
2573        self.nodes
2574            .get(self.nodes[key as usize].parent as usize)
2575            .and_then(|list| list.list.as_ref())
2576            .map_or(0, |list| list.count as usize)
2577    }
2578
2579    /// The number of rows of list `list`.
2580    fn rows_of_list(&self, list: NodeId) -> u32 {
2581        self.key(list)
2582            .ok()
2583            .and_then(|k| self.nodes[k as usize].list.as_ref())
2584            .map_or(0, |l| l.count)
2585    }
2586
2587    /// Whether `id` is a list.
2588    fn is_list(&self, id: NodeId) -> bool {
2589        self.key(id)
2590            .is_ok_and(|k| self.nodes[k as usize].list.is_some())
2591    }
2592
2593    /// Item cell `cell` of a component's list: its rows are wrapped by
2594    /// `place`, the row function the component's view gave last.
2595    fn wrap_row(&mut self, cell: NodeId, place: PlaceFn) {
2596        let Ok(key) = self.key(cell) else { return };
2597        let node = &self.nodes[key as usize];
2598        if !matches!(node.slot, Some(crate::CellSlot::Item(_))) {
2599            return;
2600        }
2601        if let Some(inst) = self.components.instances.get_mut(&cell) {
2602            if let Inner::Row { place: current, .. } = &mut inst.inner {
2603                *current = place;
2604            }
2605            self.components.mark(cell);
2606            return;
2607        }
2608        // The row's content is already in the cell: it moves into the
2609        // wrapper.
2610        let js_children = node
2611            .children
2612            .iter()
2613            .map(|&c| self.nodes[c as usize].id)
2614            .collect();
2615        let instance = Instance::new(Inner::Row { place, index: 0 }, None, js_children, None);
2616        self.components.instances.insert(cell, Box::new(instance));
2617        self.components.mark(cell);
2618    }
2619
2620    /// Runs a call JS made into Rust, in order with the ops before it: its
2621    /// result settles promise `call` (in the events, in order with them).
2622    pub(super) fn run_rust(&mut self, op: RustOp) {
2623        let posts = self.components.posts.clone();
2624        posts.in_op(|| self.run_rust_op(op));
2625    }
2626
2627    fn run_rust_op(&mut self, op: RustOp) {
2628        let RustOp { call, run } = op;
2629        match run {
2630            RustCall::Op(run) => {
2631                let mut cx = ModuleCx::default();
2632                // The app's code: a panic rejects the call (its actions are
2633                // dropped) instead of unwinding through the engine. It runs
2634                // in the graph, as a listener does: it may `spawn` and use
2635                // signals.
2636                let ran = {
2637                    let _entered = self.components.runtime.enter();
2638                    caught(|| run(&mut cx))
2639                };
2640                let result = match ran {
2641                    Ok(result) => {
2642                        for action in std::mem::take(&mut cx.actions) {
2643                            self.apply_action(action);
2644                        }
2645                        result
2646                    }
2647                    Err(message) => Err(message.into()),
2648                };
2649                self.apply_actions();
2650                self.settle(call, result);
2651            }
2652            RustCall::Task(start) => match caught(start) {
2653                Ok(future) => {
2654                    let executor = Rc::downgrade(&self.components.executor);
2655                    let pending =
2656                        crate::element::quit::Pending::new(&self.components.executor.calls);
2657                    // A task of the root: it never goes away.
2658                    crate::element::task::spawn_raw(
2659                        &self.components.executor,
2660                        ROOT_ID,
2661                        Box::pin(async move {
2662                            let result = crate::element::module::catching(future).await;
2663                            drop(pending);
2664                            match executor.upgrade() {
2665                                Some(executor) if call != 0 => {
2666                                    executor.act(Action::Return(call, result));
2667                                }
2668                                _ => {
2669                                    if let Err(e) = &result {
2670                                        log::warn!(target: "js", "an async call into Rust failed: {e}");
2671                                    }
2672                                }
2673                            }
2674                        }),
2675                    );
2676                }
2677                Err(message) => self.settle(call, Err(message.into())),
2678            },
2679            RustCall::Method(host, method) if self.view_pending(host) => {
2680                // Called from its ref, which the app gets as the component
2681                // is made, before its view is (`render_components`).
2682                self.components.parked_methods.push((host, call, method));
2683            }
2684            RustCall::Method(host, method) => {
2685                let mut failed = None;
2686                let result = match self
2687                    .components
2688                    .instances
2689                    .get_mut(&host)
2690                    .map(|i| &mut i.inner)
2691                {
2692                    Some(Inner::Component(inner)) => match caught(|| inner.call(method)) {
2693                        Ok(Some(result)) => result,
2694                        Ok(None) => {
2695                            Err(format!("{} has no ref of this method's type", inner.name()).into())
2696                        }
2697                        Err(message) => {
2698                            failed = Some(message.clone());
2699                            Err(message.into())
2700                        }
2701                    },
2702                    _ => {
2703                        drop_caught(method);
2704                        Err(format!("node {host} hosts no Rust component").into())
2705                    }
2706                };
2707                self.apply_actions();
2708                if let Some(message) = failed {
2709                    self.component_failed(host, message);
2710                }
2711                self.settle(call, result);
2712            }
2713            // Its place, released: the call runs there.
2714            RustCall::Post(place) => drop(place),
2715        }
2716    }
2717
2718    /// Settles promise `call` with `result` (in the events, in order with
2719    /// them); 0: JS does not wait, an error is logged.
2720    pub(super) fn settle(&mut self, call: u32, result: JsResult) {
2721        if call == 0 {
2722            if let Err(e) = &result {
2723                log::warn!(target: "js", "a call into Rust failed: {e}");
2724            }
2725            drop_caught(result);
2726            return;
2727        }
2728        self.events.push(JsEvent::Reply { call, result });
2729    }
2730
2731    /// The app's classes on `host` changed.
2732    pub(super) fn update_user_class(&mut self, host: NodeId) {
2733        let inst = &self.components.instances[&host];
2734        let mut combined = String::with_capacity(inst.class.len() + 16 * inst.class_list.len());
2735        combined.push_str(&inst.class);
2736        for name in &inst.class_list {
2737            combined.push(' ');
2738            combined.push_str(name);
2739        }
2740        let user = (!combined.trim().is_empty()).then(|| self.tailwind.get(&combined).0);
2741        self.set_user(host, user);
2742    }
2743
2744    /// What goes after `host`'s own styles.
2745    pub(super) fn set_user(&mut self, host: NodeId, user: Option<std::rc::Rc<ClassList>>) {
2746        let inst = self.components.instances.get_mut(&host).expect("host");
2747        if !same(&inst.user, &user) {
2748            inst.user = user;
2749            self.components.mark(host);
2750        }
2751    }
2752
2753    /// Slot node `id` leaves its host.
2754    fn unslot(&mut self, id: NodeId) {
2755        self.drop_slot_target(id);
2756        if let Some(host) = self.components.slot_hosts.remove(&id) {
2757            if let Some(inst) = self.components.instances.get_mut(&host) {
2758                inst.slots.retain(|(_, n)| *n != id);
2759            }
2760            self.components.mark(host);
2761        }
2762    }
2763
2764    /// `componentSlot` on a view: it holds a slot's JSX.
2765    pub(super) fn set_slot_name(&mut self, id: NodeId, name: Arc<str>) {
2766        self.components.slot_names.insert(id, name);
2767    }
2768
2769    /// `Prop::Component` on a view: it becomes the host of component `name`.
2770    pub(super) fn create_instance(&mut self, host: NodeId, name: Arc<str>) {
2771        if self.is_host(host) {
2772            return;
2773        }
2774        let (spec, inner) = match self.components.registry.make(&name) {
2775            Some((spec, inner)) => (Some(spec), Inner::Component(inner)),
2776            None => {
2777                self.deny(format!(
2778                    "no component is registered as `{name}`: it renders nothing"
2779                ));
2780                (None, Inner::Missing)
2781            }
2782        };
2783        self.insert_instance(host, spec, inner);
2784    }
2785
2786    /// View `host` becomes the host of the component `make` creates (a
2787    /// component a view or the app's root names by type).
2788    pub(super) fn create_instance_of(
2789        &mut self,
2790        host: NodeId,
2791        name: &'static str,
2792        make: fn() -> Box<dyn AnyInstance>,
2793        spec: fn() -> ComponentSpec,
2794    ) {
2795        if self.is_host(host) {
2796            return;
2797        }
2798        let spec = self
2799            .components
2800            .specs
2801            .entry(name)
2802            .or_insert_with(|| Arc::new(spec()))
2803            .clone();
2804        self.insert_instance(host, Some(spec), Inner::Component(make()));
2805    }
2806
2807    fn insert_instance(
2808        &mut self,
2809        host: NodeId,
2810        spec: Option<Arc<ComponentSpec>>,
2811        mut inner: Inner,
2812    ) {
2813        // A style JS set before the component prop.
2814        let app_style = self
2815            .key(host)
2816            .ok()
2817            .map(|k| self.nodes[k as usize].inline_style.clone())
2818            .filter(|p| !p.is_empty());
2819        // A component is made where it is: its lifetime is that run's, and
2820        // so is its context until a view places it (`adopt`).
2821        if let Inner::Component(c) = &mut inner {
2822            c.place(host, crate::element::Owner::current());
2823        }
2824        let instance = Instance::new(inner, spec, Vec::new(), app_style);
2825        self.components.instances.insert(host, Box::new(instance));
2826        self.components.mark(host);
2827        // No box of its own while its view styles none of its layout and
2828        // holds one node: that node is laid out in its place, so an app's
2829        // `flex-1` on a component's slot (a menu's trigger) fills the
2830        // component's parent (#2008).
2831        if let Ok(k) = self.key(host) {
2832            self.lay_out_through(k);
2833        }
2834    }
2835
2836    /// `$name` on a host: a prop of its component.
2837    pub(super) fn set_component_prop(
2838        &mut self,
2839        host: NodeId,
2840        name: &str,
2841        value: Option<AnyValue>,
2842    ) -> bool {
2843        let Some(inst) = self.components.instances.get_mut(&host) else {
2844            return false;
2845        };
2846        let Inner::Component(inner) = &mut inst.inner else {
2847            return true;
2848        };
2849        match inner.set_prop(name, value) {
2850            Ok(true) => self.components.mark(host),
2851            Ok(false) => {}
2852            Err(e) => {
2853                let component = inst.spec.as_ref().map_or("", |s| s.name);
2854                log::warn!(target: "js", "{component}: {e}");
2855            }
2856        }
2857        true
2858    }
2859
2860    /// Applies what the views' bindings queued and makes the views of the
2861    /// components marked, until neither is left.
2862    pub(super) fn render_components(&mut self) {
2863        let _entered = self.components.runtime.enter();
2864        // Views' patches, then the marked components, until none is left (a
2865        // patch may mark a component, a view made queues patches).
2866        loop {
2867            let changed = self.drain_views();
2868            let rendered = self.render_dirty();
2869            let failed = self.report_failures();
2870            let woke = self.wake_waiting();
2871            let called = self.run_parked_methods();
2872            if !changed && !rendered && !failed && !woke && !called && !self.run_after_render() {
2873                break;
2874            }
2875        }
2876        self.flush_renders();
2877        self.end_retags();
2878    }
2879
2880    /// Runs what waited for the commit's views ([`crate::element::after_render`]);
2881    /// whether there was any (what it asked for and changed renders in this
2882    /// round too).
2883    fn run_after_render(&mut self) -> bool {
2884        let rendered = self.components.executor.take_rendered();
2885        if rendered.is_empty() {
2886            return false;
2887        }
2888        for crate::element::AfterAnswer { f, .. } in rendered {
2889            if let Err(message) = caught(f) {
2890                log::error!(target: "js", "a closure after the views rendered failed: {message}");
2891            }
2892        }
2893        true
2894    }
2895
2896    /// Node `id` goes: what the views' renders and the app's classes knew
2897    /// of it goes too.
2898    fn forget_node_extras(&mut self, id: NodeId) {
2899        if !self.components.renders.is_empty() {
2900            self.forget_render_place(id);
2901        }
2902        if !self.components.app_classes.is_empty() {
2903            self.components.app_classes.remove(&id);
2904        }
2905    }
2906
2907    /// Sends the failures of views' code (bindings, effects, listeners) to
2908    /// the nearest error boundary, else to their component's; whether there
2909    /// were any.
2910    fn report_failures(&mut self) -> bool {
2911        let failures = self.components.runtime.take_failures();
2912        let any = !failures.is_empty();
2913        for (owner, message) in failures {
2914            let host = self.host_of_owner(owner);
2915            let component = host
2916                .and_then(|h| match &self.components.instances.get(&h)?.inner {
2917                    Inner::Component(inner) => Some(inner.name()),
2918                    _ => None,
2919                })
2920                .unwrap_or("a binding");
2921            if let Some(boundary) = crate::element::reactive::boundary_of(owner) {
2922                boundary.set(Some(ComponentError { component, message }));
2923                continue;
2924            }
2925            match host {
2926                Some(host) => self.component_failed(host, message),
2927                None => log::error!(target: "js", "a binding failed: {message}"),
2928            }
2929        }
2930        any
2931    }
2932
2933    /// Makes the views of the components marked dirty (one made already
2934    /// takes its slots, children and styles; a list cell builds its row
2935    /// again); whether there were any.
2936    fn render_dirty(&mut self) -> bool {
2937        // What handles asked for since (animated values released, ...).
2938        for action in self.components.executor.take_actions() {
2939            self.apply_action(action);
2940        }
2941        if self.components.dirty.is_empty() {
2942            return false;
2943        }
2944        while let Some(host) = self.components.dirty.pop() {
2945            // A view JS made waits to be in the tree (under what places it):
2946            // its context comes from above it.
2947            if self.waits_for_tree(host) {
2948                if let Some(inst) = self.components.instances.get_mut(&host) {
2949                    inst.dirty = false;
2950                }
2951                if !self.components.waiting.contains(&host) {
2952                    self.components.waiting.push(host);
2953                }
2954                continue;
2955            }
2956            let Some(mut inst) = self.components.instances.remove(&host) else {
2957                continue;
2958            };
2959            inst.dirty = false;
2960            let rooted = inst.rooted;
2961            let failed = self.render(host, &mut inst);
2962            let rerooted = inst.rooted != rooted;
2963            self.components.instances.insert(host, inst);
2964            if rerooted {
2965                self.follow_base(host, rooted);
2966            }
2967            if let Some(message) = failed {
2968                self.component_failed(host, message);
2969            }
2970        }
2971        true
2972    }
2973
2974    /// Applies the root styles of the view on `host` again over the app's
2975    /// (or its parent's) styles, which may have changed.
2976    fn restyle_view(&mut self, host: NodeId, inst: &mut Instance) {
2977        // The component its root is applies them to the node.
2978        if let Some(rooted) = inst.rooted {
2979            if std::mem::take(&mut inst.given_changed)
2980                && let Some(rooted) = self.components.instances.get_mut(&rooted)
2981            {
2982                rooted.given_changed = true;
2983            }
2984            self.components.mark(rooted);
2985            return;
2986        }
2987        let cx = self.root_context(inst);
2988        let given_changed = std::mem::take(&mut inst.given_changed);
2989        let attrs = if let Some(node) = inst.bound.get_mut(&host) {
2990            let (style, classes) = (node.style.clone(), node.classes.clone());
2991            let class = node.attrs.class.clone();
2992            let classes = self.apply_el_styles(
2993                host,
2994                &style,
2995                &style,
2996                classes,
2997                class.as_ref(),
2998                cx.user.clone(),
2999            );
3000            if let Some(node) = inst.bound.get_mut(&host) {
3001                node.classes = classes;
3002                given_changed.then(|| node.attrs.clone())
3003            } else {
3004                None
3005            }
3006        } else if let Some(root) = inst.root.as_mut() {
3007            let (style, classes) = (root.style.clone(), root.classes.clone());
3008            let class = root.attrs.class.clone();
3009            root.classes = self.apply_el_styles(
3010                host,
3011                &style,
3012                &style,
3013                classes,
3014                class.as_ref(),
3015                cx.user.clone(),
3016            );
3017            given_changed.then(|| root.attrs.clone())
3018        } else {
3019            None
3020        };
3021        // What the views above give it changed: applied again over its
3022        // root's own.
3023        if let Some(attrs) = attrs {
3024            let app = if cx.combined {
3025                cx.app.as_ref()
3026            } else {
3027                inst.app_style.as_ref()
3028            };
3029            let _ = self.apply_op(inline_style(
3030                host,
3031                attrs.inline.as_deref(),
3032                attrs.animated(),
3033                app,
3034            ));
3035            let applied = inst.root_insets_applied;
3036            let own_insets = attrs.insets();
3037            let insets = (
3038                cx.inset_padding.or(own_insets.0),
3039                cx.inset_margin.or(own_insets.1),
3040            );
3041            if insets.0 != applied.0 {
3042                let _ = self.apply_op(Op::SetProp {
3043                    id: host,
3044                    prop: Prop::InsetPadding(insets.0.unwrap_or_default()),
3045                });
3046            }
3047            if insets.1 != applied.1 {
3048                let _ = self.apply_op(Op::SetProp {
3049                    id: host,
3050                    prop: Prop::InsetMargin(insets.1.unwrap_or_default()),
3051                });
3052            }
3053            inst.root_insets_applied = insets;
3054            if cx.host != inst.root_host_applied {
3055                // As the root's own go: combined with a slot's where its
3056                // node takes one's props.
3057                let mut attrs = attrs;
3058                attrs.set_insets(insets);
3059                let old = with_host(attrs.clone(), &inst.root_host_applied);
3060                let new = with_host(attrs, &cx.host);
3061                if !self.apply_target_attrs(host, &new, &old, app) {
3062                    self.apply_attrs_over(host, &new, &old, app);
3063                }
3064                inst.root_host_applied = cx.host;
3065            }
3066        }
3067    }
3068
3069    /// Node `id` joined a host as its children or a slot's fill: the
3070    /// components in it, the node itself or inside its plain views however
3071    /// deep
3072    /// (`tabs().child(view().child(tab()))`), are `joined`, so their views
3073    /// wait to be placed and read the context of the host's view as a
3074    /// direct child does. A component's own content joins it in turn.
3075    fn join_content(&mut self, id: NodeId) {
3076        let mut stack = vec![id];
3077        while let Some(id) = stack.pop() {
3078            if let Some(inst) = self.components.instances.get_mut(&id) {
3079                inst.joined = true;
3080                continue;
3081            }
3082            if let Ok(k) = self.key(id) {
3083                stack.extend(
3084                    self.nodes[k as usize]
3085                        .children
3086                        .iter()
3087                        .map(|&c| self.nodes[c as usize].id),
3088                );
3089            }
3090        }
3091    }
3092
3093    /// Whether `host` is a component that runs once, made by JS (no owner
3094    /// placed it) or passed by a view as a nested component's content
3095    /// (`joined`), whose view is not made yet, out of the tree: the view
3096    /// that places it gives its context.
3097    fn waits_for_tree(&self, host: NodeId) -> bool {
3098        let Some(inst) = self.components.instances.get(&host) else {
3099            return false;
3100        };
3101        let Inner::Component(inner) = &inst.inner else {
3102            return false;
3103        };
3104        inst.root.is_none()
3105            && (inst.joined || !inner.failure_owner().is_live())
3106            && !self.id_in_tree(host)
3107    }
3108
3109    /// Whether node `id` is in the root's tree.
3110    fn id_in_tree(&self, id: NodeId) -> bool {
3111        self.key(id).is_ok_and(|k| self.in_tree(k))
3112    }
3113
3114    /// The views that waited for the tree and are in it now are made;
3115    /// whether there were any.
3116    fn wake_waiting(&mut self) -> bool {
3117        let waiting = std::mem::take(&mut self.components.waiting);
3118        let mut woke = false;
3119        for host in waiting {
3120            if !self.components.instances.contains_key(&host) {
3121                continue;
3122            }
3123            if self.id_in_tree(host) {
3124                self.components.mark(host);
3125                woke = true;
3126            } else {
3127                self.components.waiting.push(host);
3128            }
3129        }
3130        woke
3131    }
3132
3133    /// Runs the calls of methods parked for components whose view is now
3134    /// made; whether any ran.
3135    fn run_parked_methods(&mut self) -> bool {
3136        if self.components.parked_methods.is_empty() {
3137            return false;
3138        }
3139        let parked = std::mem::take(&mut self.components.parked_methods);
3140        let mut ran = false;
3141        for (host, call, method) in parked {
3142            if self.view_pending(host) {
3143                self.components.parked_methods.push((host, call, method));
3144            } else {
3145                ran = true;
3146                self.run_rust(RustOp {
3147                    call,
3148                    run: RustCall::Method(host, method),
3149                });
3150            }
3151        }
3152        ran
3153    }
3154
3155    /// Whether `host` hosts a component whose view is not made yet.
3156    fn view_pending(&self, host: NodeId) -> bool {
3157        self.components
3158            .instances
3159            .get(&host)
3160            .is_some_and(|i| matches!(&i.inner, Inner::Component(inner) if inner.owner().is_none()))
3161    }
3162
3163    /// The owner of the nearest component above `host` in the tree (its
3164    /// view's, or a list cell's row), else none.
3165    fn owner_above(&self, host: NodeId) -> crate::element::Owner {
3166        let mut key = self.key(host).ok();
3167        while let Some(k) = key {
3168            let parent = self.nodes[k as usize].parent;
3169            if parent == NO_KEY {
3170                break;
3171            }
3172            key = Some(parent);
3173            // A component may return another component as its root. The
3174            // innermost one owns the content's placement context.
3175            let id = self.base_of(self.nodes[parent as usize].id);
3176            // What JS made is under a component through its JS children:
3177            // under where it places them.
3178            let owner = self
3179                .components
3180                .instances
3181                .get(&id)
3182                .and_then(|inst| match &inst.inner {
3183                    Inner::Component(inner) => inst
3184                        .children_owner
3185                        .filter(|o| o.is_live())
3186                        .or_else(|| inner.owner().filter(|o| o.is_live())),
3187                    _ => inst.cell_owner,
3188                });
3189            if let Some(owner) = owner {
3190                return owner;
3191            }
3192        }
3193        crate::element::Owner::detached()
3194    }
3195
3196    /// The owner a component JS made in a window JS opened renders under
3197    /// when no component is above it: one per window, providing its ref,
3198    /// so [`crate::element::desktop::current_window`] is that window (its
3199    /// title bar area, its dialogs). `None` in the main window.
3200    fn js_window_owner(&mut self, host: NodeId) -> Option<crate::element::Owner> {
3201        let key = self.key(host).ok()?;
3202        let window = self.key_window(key);
3203        if window == ROOT_ID {
3204            return None;
3205        }
3206        if let Some((owner, _)) = self.components.js_windows.get(&window)
3207            && owner.is_live()
3208        {
3209            return Some(*owner);
3210        }
3211        let id = self
3212            .window_ids
3213            .iter()
3214            .find_map(|(id, (node, _))| (*node == window).then(|| id.clone()))?;
3215        let reported = self
3216            .components
3217            .window_reports
3218            .get(&window)
3219            .copied()
3220            .unwrap_or_default();
3221        let (owner, this) =
3222            crate::element::desktop::js_window(&id, window, &self.components.executor, reported);
3223        self.components.js_windows.insert(window, (owner, this));
3224        Some(owner)
3225    }
3226
3227    /// The host of the component that runs once whose owner is `owner`, or
3228    /// whose view made it (a binding's own owner is under the component's).
3229    fn host_of_owner(&self, owner: crate::element::Owner) -> Option<NodeId> {
3230        let mut at = Some(owner);
3231        while let Some(owner) = at {
3232            let host =
3233                self.components
3234                    .instances
3235                    .iter()
3236                    .find_map(|(&host, inst)| match &inst.inner {
3237                        Inner::Component(inner) if inner.owner() == Some(owner) => Some(host),
3238                        _ => None,
3239                    });
3240            if host.is_some() {
3241                return host;
3242            }
3243            at = owner.parent();
3244        }
3245        None
3246    }
3247
3248    /// The window the component that runs once under `owner` shows in (its
3249    /// root node), the main window's when there is none.
3250    fn window_of_owner(&self, owner: crate::element::Owner) -> NodeId {
3251        if self.window_ids.is_empty() {
3252            return crate::ROOT_ID;
3253        }
3254        self.host_of_owner(owner)
3255            .and_then(|host| self.key(host).ok())
3256            .map_or(crate::ROOT_ID, |key| self.key_window(key))
3257    }
3258
3259    /// Makes `inst`'s view on `host` (once: a view made already takes its
3260    /// slots, children and styles), or builds a list cell's row again; what
3261    /// its code panicked with, if it did.
3262    fn render(&mut self, host: NodeId, inst: &mut Instance) -> Option<String> {
3263        let mut failure = None;
3264        let el = match &mut inst.inner {
3265            Inner::Component(inner) => {
3266                // What the app passed, as props.
3267                if let Some(spec) = &inst.spec {
3268                    for name in spec.slots() {
3269                        let filled = inst.slots.iter().any(|(s, node)| {
3270                            *s == name
3271                                && self
3272                                    .key(*node)
3273                                    .is_ok_and(|k| !self.nodes[k as usize].children.is_empty())
3274                        }) || inst
3275                            .fills
3276                            .iter()
3277                            .any(|f| f.name == name && !self.fill_nodes(f).is_empty());
3278                        inner.set_slot(name, filled);
3279                    }
3280                }
3281                inner.set_children(!inst.js_children.is_empty());
3282                // Its view is made: its props now reach what read them, and
3283                // the app's (or its parent's) styles may have changed.
3284                if inst.root.is_some() && !std::mem::take(&mut inst.remake) {
3285                    self.restyle_view(host, inst);
3286                    return None;
3287                }
3288                let owner = self.owner_above(host);
3289                let owner = if owner.is_live() {
3290                    owner
3291                } else {
3292                    self.js_window_owner(host).unwrap_or(owner)
3293                };
3294                inner.adopt(owner);
3295                // A view that fails shows nothing.
3296                caught(|| inner.view()).unwrap_or_else(|message| {
3297                    failure = Some(message);
3298                    ElNode::empty_view()
3299                })
3300            }
3301            // The cell itself stays the list's: the wrapper goes inside.
3302            Inner::Row { place, index } => {
3303                let (place, index) = (place.clone(), *index);
3304                let count = self.rows_of_cell(host);
3305                let list = self.list_of(host);
3306                // The wrapper reads its position from signals.
3307                let count_signal = list.map(|list| self.list_count(list, count));
3308                let moves = list
3309                    .and_then(|list| self.components.virtual_lists.get(&list))
3310                    .and_then(|state| state.moves);
3311                let made = std::cell::Cell::new(None);
3312                let build = || {
3313                    let at = row_position(index, count, count_signal, moves, &made);
3314                    view().child(place(Child::row(), at)).into_element().0
3315                };
3316                // The wrapper is the placing component's.
3317                let parent = self.list_component_owner(list);
3318                let el = self.build_cell(parent, inst, build);
3319                inst.row_index = made.take();
3320                if let (Some(list), Some(index), Some(owner)) =
3321                    (list, inst.row_index, inst.cell_owner)
3322                    && let Some(state) = self.components.virtual_lists.get(&list)
3323                {
3324                    state.rows.borrow_mut().insert(host, (index, owner));
3325                }
3326                match el {
3327                    Ok(el) => el,
3328                    Err(message) => {
3329                        failure = Some(message);
3330                        ElNode::empty_view()
3331                    }
3332                }
3333            }
3334            Inner::VirtualRow { list, index } => {
3335                let (list, index) = (*list, *index);
3336                let inverted = self
3337                    .key(list)
3338                    .ok()
3339                    .and_then(|k| self.nodes[k as usize].list.as_ref())
3340                    .is_some_and(|l| l.inverted);
3341                let state = self.components.virtual_lists.get(&list).map(|state| {
3342                    // The run that made the list went (its view goes in
3343                    // this commit): no row is made under it.
3344                    let scope = state.scope.get();
3345                    let gone = scope.is_some_and(|s| !s.is_live());
3346                    (
3347                        if gone { 0 } else { state.count as usize },
3348                        state.row.clone(),
3349                        state.separator.clone(),
3350                        state.rows.clone(),
3351                        scope,
3352                        state.moves,
3353                    )
3354                });
3355                match state {
3356                    // The row is gone (the list shrank): the cell shows
3357                    // nothing until the list unbinds it or binds it to a
3358                    // row again; the row function is never asked for a
3359                    // row past the end.
3360                    Some((count, ..)) if index >= count => {
3361                        if let Some(owner) = inst.cell_owner.take() {
3362                            owner.dispose();
3363                        }
3364                        inst.row_index = None;
3365                        ElNode::empty_view()
3366                    }
3367                    Some((count, row, separator, rows, scope, moves)) => {
3368                        let count_signal = Some(self.list_count(list, count));
3369                        let made = std::cell::Cell::new(None);
3370                        let build = || {
3371                            let at = row_position(index, count, count_signal, moves, &made);
3372                            let row = row(at);
3373                            // Between rows: after each but the last (before
3374                            // it, inverted), while it is not.
3375                            let separator = separator.map(|s| {
3376                                crate::element::when(move || !at.is_last(), move || s())
3377                                    .into_element()
3378                            });
3379                            match separator {
3380                                Some(s) if inverted => view().child(s).child(row),
3381                                Some(s) => view().child(row).child(s),
3382                                None => view().child(row),
3383                            }
3384                            .into_element()
3385                            .0
3386                        };
3387                        // Under the run that made the list, also when the
3388                        // row is inside another component's wrapper (an
3389                        // `Items` prop): the list is known here, not from
3390                        // the cell's parent.
3391                        let parent = scope.unwrap_or_else(|| self.list_component_owner(Some(list)));
3392                        let el = self.build_cell(parent, inst, build);
3393                        inst.row_index = made.take();
3394                        if let (Some(index), Some(owner)) = (inst.row_index, inst.cell_owner) {
3395                            rows.borrow_mut().insert(host, (index, owner));
3396                        }
3397                        match el {
3398                            Ok(el) => el,
3399                            Err(message) => {
3400                                failure = Some(message);
3401                                ElNode::empty_view()
3402                            }
3403                        }
3404                    }
3405                    None => ElNode::empty_view(),
3406                }
3407            }
3408            Inner::Missing => ElNode::empty_view(),
3409        };
3410        // The view binds under its owner.
3411        let owner = match &inst.inner {
3412            Inner::Component(inner) => inner.owner(),
3413            _ => inst.cell_owner,
3414        };
3415        match owner {
3416            Some(owner) => owner.run(|| self.expand_root(host, inst, el)),
3417            None => self.expand_root(host, inst, el),
3418        }
3419        failure
3420    }
3421
3422    /// Builds a list cell's row with `build` under an owner of the cell's
3423    /// own (the previous row's goes), made under `parent` so the row sees
3424    /// its context.
3425    fn build_cell(
3426        &mut self,
3427        parent: crate::element::Owner,
3428        inst: &mut Instance,
3429        build: impl FnOnce() -> ElNode,
3430    ) -> Result<ElNode, String> {
3431        if let Some(owner) = inst.cell_owner.take() {
3432            owner.dispose();
3433        }
3434        let (owner, el) = parent.run(|| crate::element::create_root(|| caught(build)));
3435        inst.cell_owner = Some(owner);
3436        el
3437    }
3438
3439    /// The owner of the component whose list `list` is (its own list, or
3440    /// the list it places another component's `Items` in).
3441    fn list_component_owner(&self, list: Option<NodeId>) -> crate::element::Owner {
3442        let component = list
3443            .and_then(|list| {
3444                self.components
3445                    .virtual_lists
3446                    .get(&list)
3447                    .map(|s| s.owner)
3448                    .or_else(|| self.components.slot_hosts.get(&list).copied())
3449            })
3450            .and_then(|host| self.components.instances.get(&host))
3451            .and_then(|inst| match &inst.inner {
3452                Inner::Component(inner) => inner.owner(),
3453                _ => None,
3454            });
3455        component.unwrap_or_else(crate::element::Owner::detached)
3456    }
3457
3458    /// The text content `new` of node `id` (of `host`'s view), its raw
3459    /// text node made, changed or released from `old`.
3460    fn reconcile_text(
3461        &mut self,
3462        id: NodeId,
3463        host: NodeId,
3464        new: Option<SharedString>,
3465        old: Option<(SharedString, NodeId)>,
3466    ) -> Option<(SharedString, NodeId)> {
3467        match (new, old) {
3468            (Some(content), Some((old, raw))) => {
3469                if content != old {
3470                    let _ = self.apply_op(Op::SetText {
3471                        id: raw,
3472                        text: content.as_str().to_owned(),
3473                    });
3474                }
3475                Some((content, raw))
3476            }
3477            (Some(content), None) => {
3478                let raw = self.components.alloc();
3479                let _ = self.apply_op(Op::CreateText {
3480                    id: raw,
3481                    text: content.as_str().to_owned(),
3482                });
3483                self.components.owners.insert(raw, host);
3484                let _ = self.apply_op(Op::Insert {
3485                    parent: id,
3486                    child: raw,
3487                    before: None,
3488                });
3489                Some((content, raw))
3490            }
3491            (None, Some((_, raw))) => {
3492                self.release_id(raw);
3493                None
3494            }
3495            (None, None) => None,
3496        }
3497    }
3498
3499    /// Applies a view's root `el` to `host` itself (over a list cell's
3500    /// previous row) and expands its children. A view's root can be any
3501    /// element: the host becomes its node (a screen, a modal, a text, a
3502    /// list), holds it (a region), or is the host of a component as the
3503    /// root ([`Self::expand_rooted`]).
3504    fn expand_root(&mut self, host: NodeId, inst: &mut Instance, mut el: ElNode) {
3505        if matches!(el.kind, ElKind::Component(_))
3506            && matches!(inst.inner, Inner::Component(_))
3507            && inst
3508                .root
3509                .as_ref()
3510                .is_none_or(|r| matches!(r.part, Part::Component(_)))
3511        {
3512            return self.expand_rooted(host, inst, el);
3513        }
3514        let node = matches!(el.kind, ElKind::Plain | ElKind::VirtualList(_));
3515        if !node || (el.tag != Tag::View && !self.retag(host, el.tag)) {
3516            if node {
3517                log::error!(target: "js", "a component's root takes its kind only when it is first mounted; it is placed in a view");
3518            }
3519            let inner = std::mem::replace(&mut el, ElNode::new(Tag::View));
3520            el.children.push(inner);
3521        }
3522        if !el.children.is_empty()
3523            && let Some(content) = el.bound_text.take()
3524        {
3525            let mut first = ElNode::new(Tag::Text);
3526            first.text = Some(SharedString::default());
3527            first.bound_text = Some(content);
3528            el.text = None;
3529            el.children.insert(0, first);
3530        }
3531        // Bound parts are bound first: what they read now is applied with
3532        // the static parts.
3533        let applied_layout = if matches!(el.kind, ElKind::VirtualList(_)) {
3534            self.components.list_layouts.remove(&host)
3535        } else {
3536            None
3537        };
3538        let bound = super::views::Bound::take(&mut el).map(|bound| {
3539            self.bind_parts(host, host, bound, &mut el);
3540        });
3541        inst.handlers.clear();
3542        inst.event_handlers.clear();
3543        inst.responders.clear();
3544        let old = inst.root.take();
3545        let first = old.is_none();
3546        let old_place = std::mem::replace(&mut inst.children_at, Placement::None);
3547        // The root is the host itself.
3548        let (old_attrs, old_style, old_classes, old_events, old_children, old_text, old_list) =
3549            match old {
3550                Some(e) => (
3551                    e.attrs,
3552                    e.style,
3553                    e.classes,
3554                    e.events,
3555                    e.children,
3556                    e.text,
3557                    e.list.map(|l| *l).unwrap_or_default(),
3558                ),
3559                None => (
3560                    Attrs::default(),
3561                    StyleRefinement::default(),
3562                    (None, None),
3563                    EventMask::default(),
3564                    Vec::new(),
3565                    None,
3566                    ListConfig::default(),
3567                ),
3568            };
3569        // What the views above give it and the components on its host, the
3570        // outer last.
3571        let cx = self.root_context(inst);
3572        let app = if cx.combined {
3573            cx.app.as_ref()
3574        } else {
3575            inst.app_style.as_ref()
3576        };
3577        let attrs = cx.over(el.attrs.clone());
3578        // As it was applied: with the insets its node got.
3579        let mut old_over = old_attrs.clone();
3580        old_over.set_insets(inst.root_insets_applied);
3581        let old_over = with_host(old_over, &inst.root_host_applied);
3582        if !self.apply_target_attrs(host, &attrs, &old_over, app) {
3583            self.apply_attrs_over(host, &attrs, &old_over, app);
3584        }
3585        inst.root_insets_applied = attrs.insets();
3586        inst.root_host_applied = cx.host.clone();
3587        // Given an inline style or animated values while its own did not
3588        // change: they go now.
3589        let given_changed = std::mem::take(&mut inst.given_changed) || first;
3590        if cx.given
3591            && given_changed
3592            && attrs.inline == old_over.inline
3593            && attrs.animated() == old_over.animated()
3594        {
3595            let _ = self.apply_op(inline_style(
3596                host,
3597                attrs.inline.as_deref(),
3598                attrs.animated(),
3599                app,
3600            ));
3601        }
3602        let user = cx.user.clone();
3603        let top_js = cx.js;
3604        let given_events = cx.given_events;
3605        let classes = self.apply_el_styles(
3606            host,
3607            &el.style,
3608            &old_style,
3609            old_classes,
3610            el.attrs.class.as_ref(),
3611            user,
3612        );
3613        let text = self.reconcile_text(host, host, el.text.take(), old_text);
3614        if bound.is_some() {
3615            Self::keep_bound(
3616                inst,
3617                host,
3618                &el.attrs,
3619                &el.style,
3620                classes.clone(),
3621                text.clone(),
3622            );
3623        }
3624        // The host listens to its component's events, JS's and those the
3625        // views above give it.
3626        let js = top_js.unwrap_or(inst.js_events) | given_events;
3627        self.apply_handlers(host, host, &el, old_events | js, js, inst);
3628        let mut events = EventMask::default();
3629        for (kind, _) in &el.handlers {
3630            events.set(*kind, true);
3631        }
3632        events.set(
3633            EventKind::Touch,
3634            events.contains(EventKind::Touch) || el.responder.is_some(),
3635        );
3636        let new_children = std::mem::take(&mut el.children);
3637        let children = self.reconcile_children(host, old_children, new_children, host, inst);
3638        let (list, part) = match std::mem::replace(&mut el.kind, ElKind::Plain) {
3639            ElKind::VirtualList(list) => {
3640                let config = list.config;
3641                let old_list = applied_layout.unwrap_or(old_list);
3642                self.update_virtual_list(self.native_id(host), host, *list, &old_list);
3643                (Some(Box::new(config)), Part::VirtualList)
3644            }
3645            _ => (None, Part::Node),
3646        };
3647        inst.root = Some(Expanded {
3648            id: host,
3649            tag: el.tag,
3650            key: None,
3651            text,
3652            attrs: el.attrs,
3653            style: el.style,
3654            classes,
3655            events,
3656            list,
3657            part,
3658            children,
3659        });
3660        self.children_placed(host, inst, old_place);
3661    }
3662
3663    /// [`Self::expand_root`] of a view whose root is component element
3664    /// `el`: that component is made on `host` itself, under an alias of its
3665    /// node ([`Core::alias`]), and its view makes the node, with what this
3666    /// view gives it (props, styles, listeners, ref, content) and what the
3667    /// app gives this one (styles, events): no node of its own.
3668    fn expand_rooted(&mut self, host: NodeId, inst: &mut Instance, el: ElNode) {
3669        let ElKind::Component(c) = &el.kind else {
3670            return;
3671        };
3672        let part = Part::Component(c.name);
3673        inst.handlers.clear();
3674        inst.event_handlers.clear();
3675        inst.responders.clear();
3676        let old_place = std::mem::replace(&mut inst.children_at, Placement::None);
3677        let prev = match inst.root.take() {
3678            Some(old) if old.part == part => old,
3679            old => {
3680                if let Some(old) = old {
3681                    self.release_expanded(old);
3682                }
3683                let id = self.components.alloc();
3684                if let Err(e) = self.alias(id, host) {
3685                    log::error!(target: "js", "a view's root component is not made: {e:?}");
3686                    return;
3687                }
3688                self.components.owners.insert(id, host);
3689                self.create_instance_for(id, c);
3690                if let Some(rooted) = self.components.instances.get_mut(&id) {
3691                    // The app's style is the top host's.
3692                    rooted.app_style = None;
3693                    rooted.above = Some(host);
3694                }
3695                Expanded::js(id, part)
3696            }
3697        };
3698        inst.rooted = Some(prev.id);
3699        let root = self.reconcile_node(Some(prev), el, part, host, inst);
3700        inst.root = Some(root);
3701        self.children_placed(host, inst, old_place);
3702    }
3703
3704    /// The component whose view makes host `id`'s node: its own, or the
3705    /// one its view's root is (as deep as roots are components).
3706    pub(super) fn base_of(&self, id: NodeId) -> NodeId {
3707        let mut at = id;
3708        while let Some(next) = self.components.instances.get(&at).and_then(|i| i.rooted) {
3709            at = next;
3710        }
3711        at
3712    }
3713
3714    /// What `inst`'s root takes besides its own: the styles, inline styles,
3715    /// animated values and insets the views above give it and the
3716    /// components whose views' roots it is (the outer last), the app's
3717    /// style and JS's events on the top host.
3718    pub(super) fn root_context(&mut self, inst: &Instance) -> RootContext {
3719        let mut cx = RootContext {
3720            user: inst.user.clone(),
3721            combined: false,
3722            app: None,
3723            js: None,
3724            given_events: inst.given_events,
3725            inset_padding: None,
3726            inset_margin: None,
3727            host: Vec::new(),
3728            given: false,
3729        };
3730        if inst.above.is_none() && inst.given.is_none() {
3731            cx.host.clone_from(&inst.js_host);
3732            return cx;
3733        }
3734        cx.combined = true;
3735        let mut decls: Vec<crate::StyleDecl> = Vec::new();
3736        let mut take = |cx: &mut RootContext, given: &Attrs| {
3737            cx.given = true;
3738            if let Some(inline) = &given.inline {
3739                decls.extend(inline.decls().iter().cloned());
3740            }
3741            if let Some(r) = &given.rare {
3742                decls.extend(r.animated.iter().map(|(d, _)| d.clone()));
3743                cx.inset_padding = r.inset_padding.or(cx.inset_padding);
3744                cx.inset_margin = r.inset_margin.or(cx.inset_margin);
3745            }
3746            given_host(given, &mut cx.host);
3747        };
3748        if let Some(given) = &inst.given {
3749            take(&mut cx, given);
3750        }
3751        // The classes the element was given in Rust (`app_class`), as the
3752        // app's `class` on its host.
3753        if let Some(class) = inst.given.as_ref().and_then(|g| g.class.clone()) {
3754            let given = self.app_class_list(&class);
3755            cx.user = self.merge_user(cx.user.take(), Some(given));
3756        }
3757        let mut app = inst.app_style.clone();
3758        // JS's on the top host.
3759        let mut js_host = None;
3760        let mut at = inst.above;
3761        while let Some(id) = at {
3762            let Some(above) = self.components.instances.get(&id) else {
3763                break;
3764            };
3765            let (outer, given) = (above.user.clone(), above.given.clone());
3766            app = above.app_style.clone();
3767            js_host = Some(above.js_host.clone());
3768            cx.js = Some(above.js_events);
3769            cx.given_events = cx.given_events | above.given_events;
3770            at = above.above;
3771            if let Some(given) = &given {
3772                take(&mut cx, given);
3773            }
3774            cx.user = self.merge_user(cx.user.take(), outer);
3775            if let Some(class) = given.and_then(|g| g.class.clone()) {
3776                let given = self.app_class_list(&class);
3777                cx.user = self.merge_user(cx.user.take(), Some(given));
3778            }
3779        }
3780        for prop in js_host.as_ref().unwrap_or(&inst.js_host) {
3781            give_host(&mut cx.host, prop.clone());
3782        }
3783        if let Some(app) = &app {
3784            decls.extend(app.decls().iter().cloned());
3785        }
3786        if !decls.is_empty() {
3787            let mut style = crate::Style::default();
3788            let mut patch = crate::StylePatch::default();
3789            for decl in decls {
3790                let _ = patch.push(&mut style, decl);
3791            }
3792            cx.app = Some(patch);
3793        }
3794        cx
3795    }
3796
3797    /// [`Self::root_context`] of the component hosted by `host`.
3798    pub(super) fn root_context_of(&mut self, host: NodeId) -> Option<RootContext> {
3799        let inst = self.components.instances.remove(&host)?;
3800        let cx = self.root_context(&inst);
3801        self.components.instances.insert(host, inst);
3802        Some(cx)
3803    }
3804
3805    /// What the view `host` is in gives its element besides styles is `attrs`:
3806    /// its root takes them.
3807    pub(super) fn set_given(&mut self, host: NodeId, mut attrs: Attrs) {
3808        attrs.set_element_ref(None);
3809        let given = (attrs != Attrs::default()).then(|| Box::new(attrs));
3810        let Some(inst) = self.components.instances.get_mut(&host) else {
3811            return;
3812        };
3813        if inst.given != given {
3814            inst.given = given;
3815            inst.given_changed = true;
3816            self.components.mark(host);
3817        }
3818    }
3819
3820    /// `inner`'s rules, then `outer`'s (one list per pair, kept).
3821    pub(super) fn merge_user(
3822        &mut self,
3823        inner: Option<std::rc::Rc<ClassList>>,
3824        outer: Option<std::rc::Rc<ClassList>>,
3825    ) -> Option<std::rc::Rc<ClassList>> {
3826        match (inner, outer) {
3827            (Some(a), Some(b)) => {
3828                let key = (
3829                    std::rc::Rc::as_ptr(&a) as usize,
3830                    std::rc::Rc::as_ptr(&b) as usize,
3831                );
3832                if let Some([_, _, merged]) = self.components.merges.get(&key) {
3833                    return Some(merged.clone());
3834                }
3835                if self.components.merges.len() >= STYLE_CACHE {
3836                    self.components.merges.clear();
3837                }
3838                let merged = std::rc::Rc::new(a.merged(&b));
3839                self.components.merges.insert(key, [a, b, merged.clone()]);
3840                Some(merged)
3841            }
3842            (a, None) => a,
3843            (None, b) => b,
3844        }
3845    }
3846
3847    /// Where the JS children of `host` go changed from `old_place`: they
3848    /// leave the tree when nothing places them, and lazy ones are asked for
3849    /// or dropped.
3850    pub(super) fn children_placed(
3851        &mut self,
3852        host: NodeId,
3853        inst: &mut Instance,
3854        old_place: Placement,
3855    ) {
3856        // No `Children` any more: the JS children leave the tree.
3857        if inst.children_at == Placement::None && old_place != Placement::None {
3858            for &child in &inst.js_children {
3859                self.unplace(old_place, child);
3860            }
3861        }
3862        // Lazy children are made while the view places them: by JS, or by
3863        // the view this one is in (what passes them reads a signal).
3864        let wanted = inst.children_at != Placement::None;
3865        if inst.children_wanted != wanted && inst.spec.as_ref().is_some_and(|s| s.lazy_children) {
3866            inst.children_wanted = wanted;
3867            match self.components.owners.get(&host).copied() {
3868                // A view's: what passes them follows (a view that passes
3869                // none made no signal). The run of the view that passed
3870                // them may be gone already, in this commit, before what it
3871                // made is released: a region of this component and the one
3872                // passing its children changed together (a menu and its
3873                // submenu ending their exits at once). Nothing reads its
3874                // signal then.
3875                Some(_) => {
3876                    if let Some(signal) = inst.lazy_wanted {
3877                        signal.try_set(wanted);
3878                    }
3879                }
3880                None => self.events.push(JsEvent::Children { host, wanted }),
3881            }
3882        }
3883    }
3884
3885    /// The signal of whether the component hosted by `nested` places its
3886    /// lazy children, made under the current owner (the view passing them)
3887    /// the first time.
3888    fn children_wanted_signal(&mut self, nested: NodeId) -> crate::element::Signal<bool> {
3889        let Some(inst) = self.components.instances.get_mut(&nested) else {
3890            return crate::element::signal(false);
3891        };
3892        // Made again under this owner when the one that made it is gone
3893        // (the run that passed them before was disposed while the
3894        // component stayed).
3895        match inst.lazy_wanted {
3896            Some(signal) if signal.is_live() => signal,
3897            _ => {
3898                let signal = crate::element::signal(inst.children_wanted);
3899                inst.lazy_wanted = Some(signal);
3900                signal
3901            }
3902        }
3903    }
3904
3905    /// JS child `child`, placed at `place`, leaves the tree (and the
3906    /// nested component it was passed on to).
3907    fn unplace(&mut self, place: Placement, child: NodeId) {
3908        match place {
3909            Placement::Nested(nested, _) if self.is_host(nested) => {
3910                let _ = self.intercept(Op::Remove {
3911                    parent: nested,
3912                    child,
3913                });
3914            }
3915            _ => self.detach_id(child),
3916        }
3917    }
3918
3919    pub(super) fn detach_id(&mut self, id: NodeId) {
3920        self.unfold_run(id);
3921        if let Ok(key) = self.key(id)
3922            && self.nodes[key as usize].parent != NO_KEY
3923        {
3924            self.detach(key);
3925        }
3926    }
3927
3928    pub(super) fn apply_attrs(&mut self, id: NodeId, new: &Attrs, old: &Attrs) {
3929        self.apply_attrs_over(id, new, old, None);
3930    }
3931
3932    /// [`Self::apply_attrs`] for a host: the app's style goes after the
3933    /// root's (and is sent again with it).
3934    pub(super) fn apply_attrs_over(
3935        &mut self,
3936        id: NodeId,
3937        new: &Attrs,
3938        old: &Attrs,
3939        app: Option<&crate::StylePatch>,
3940    ) {
3941        // An element's ref names its node by its own id.
3942        let node = self.native_id(id);
3943        let has_rare = new.rare.is_some() || old.rare.is_some();
3944        if has_rare {
3945            let empty = crate::element::builder::RareAttrs::default();
3946            let nr = new.rare.as_deref().unwrap_or(&empty);
3947            let or = old.rare.as_deref().unwrap_or(&empty);
3948            if or.element_ref != nr.element_ref
3949                && let Some(r) = &or.element_ref
3950            {
3951                r.detach(node);
3952            }
3953            if let Some(r) = &nr.element_ref {
3954                r.attach(node);
3955            }
3956            if nr.render != or.render {
3957                self.update_render(node, or.render.as_ref(), nr.render.as_ref());
3958            }
3959        }
3960        let mut props = std::mem::take(&mut self.components.props);
3961        new.changes(old, &mut props);
3962        for prop in props.drain(..) {
3963            let _ = self.apply_op(Op::SetProp { id, prop });
3964        }
3965        self.components.props = props;
3966        let animated_changed = has_rare && new.animated() != old.animated();
3967        if new.inline != old.inline || animated_changed {
3968            let _ = self.apply_op(inline_style(id, new.inline.as_deref(), new.animated(), app));
3969        }
3970        if has_rare {
3971            let empty = crate::element::builder::RareAttrs::default();
3972            let nr = new.rare.as_deref().unwrap_or(&empty);
3973            let or = old.rare.as_deref().unwrap_or(&empty);
3974            if nr.drawing != or.drawing
3975                && let Some(drawing) = &nr.drawing
3976            {
3977                let _ = self.apply_op(Op::Draw {
3978                    id,
3979                    drawing: Box::new((**drawing).clone()),
3980                });
3981            }
3982            if nr.window != or.window
3983                && let Some(window) = &nr.window
3984            {
3985                // Opened once; then only its attributes follow (the record sends
3986                // what changed).
3987                let command = if or.window.is_none() {
3988                    crate::desktop::DesktopCommand::OpenWindow(Box::new(
3989                        crate::desktop::OpenWindow {
3990                            options: (**window).clone(),
3991                            ..Default::default()
3992                        },
3993                    ))
3994                } else {
3995                    crate::desktop::DesktopCommand::SetAttributes(Box::new(
3996                        window.attributes.clone(),
3997                    ))
3998                };
3999                let opens = or.window.is_none();
4000                let _ = self.apply_op(Op::Command {
4001                    id,
4002                    command: crate::Command::Desktop(Box::new(command)),
4003                });
4004                // What its ref was asked for before it existed follows its
4005                // opening, in order (`open_window(..)` then `focus()`).
4006                if opens {
4007                    for command in &nr.window_commands {
4008                        let _ = self.apply_op(Op::Command {
4009                            id,
4010                            command: crate::Command::Desktop(Box::new(command.clone())),
4011                        });
4012                    }
4013                }
4014            }
4015        }
4016    }
4017
4018    /// Sets node `id`'s classes: `style` lowered, then `user` (a host's).
4019    pub(super) fn apply_styles(
4020        &mut self,
4021        id: NodeId,
4022        style: &StyleRefinement,
4023        old_style: &StyleRefinement,
4024        old: Classes,
4025        user: Option<std::rc::Rc<ClassList>>,
4026    ) -> Classes {
4027        let own = if style == old_style {
4028            old.0.clone()
4029        } else if style.is_empty() {
4030            None
4031        } else {
4032            Some(self.components.lowered(style))
4033        };
4034        if !same(&own, &old.0) || !same(&user, &old.1) {
4035            let list = self.merge_user(own.clone(), user.clone());
4036            if let Ok(key) = self.key(id) {
4037                self.set_class_list(key, list);
4038            }
4039        }
4040        (own, user)
4041    }
4042
4043    /// [`Self::apply_styles`] for an element of a view: the app's classes
4044    /// it carries (`class`, [`crate::element::Element::app_class`]) go after its
4045    /// own styles, then `outer` (a root's: what the views and the app give
4046    /// its host).
4047    pub(super) fn apply_el_styles(
4048        &mut self,
4049        id: NodeId,
4050        style: &StyleRefinement,
4051        old_style: &StyleRefinement,
4052        old: Classes,
4053        class: Option<&SharedString>,
4054        outer: Option<std::rc::Rc<ClassList>>,
4055    ) -> Classes {
4056        let Some(class) = class.filter(|c| !c.trim().is_empty()) else {
4057            if !self.components.app_classes.is_empty() {
4058                self.components.app_classes.remove(&id);
4059            }
4060            return self.apply_styles(id, style, old_style, old, outer);
4061        };
4062        let app = self.app_class_list(class);
4063        let user = self.merge_user(Some(app), outer.clone());
4064        let classes = self.apply_styles(id, style, old_style, old, user);
4065        self.components
4066            .app_classes
4067            .insert(id, (classes.0.clone(), class.clone(), outer));
4068        classes
4069    }
4070
4071    /// The rules of the app's classes `class` (the unknown ones warned of
4072    /// once, as a host's).
4073    pub(super) fn app_class_list(&mut self, class: &str) -> std::rc::Rc<ClassList> {
4074        let (list, fresh) = self.tailwind.get(class);
4075        if fresh && !list.unknown().is_empty() {
4076            log::warn!(
4077                "unknown classes: {}",
4078                list.unknown()
4079                    .iter()
4080                    .map(|s| &**s)
4081                    .collect::<Vec<_>>()
4082                    .join(" ")
4083            );
4084        }
4085        list
4086    }
4087
4088    /// Registers `el`'s handlers for node `id` and listens to their events
4089    /// (plus `extra`, what JS listens to on a host); returns the mask.
4090    #[allow(
4091        clippy::too_many_arguments,
4092        reason = "the installed node and its owning view"
4093    )]
4094    fn apply_handlers(
4095        &mut self,
4096        host: NodeId,
4097        id: NodeId,
4098        el: &ElNode,
4099        old: EventMask,
4100        extra: EventMask,
4101        inst: &mut Instance,
4102    ) -> EventMask {
4103        let mut mask = extra;
4104        self.initialize_layout_listeners(host, id, el, old, inst);
4105        // A node made again (its region ran again) hears what this run
4106        // gives it, not also what the runs before gave it.
4107        if old.bits() != 0 {
4108            inst.handlers.remove(id);
4109            inst.responders.retain(|(n, _)| *n != id);
4110        }
4111        for (kind, handler) in &el.handlers {
4112            mask.set(*kind, true);
4113            inst.handlers.push(id, *kind, handler.clone());
4114        }
4115        // The responder hears the touches the platform reports.
4116        if let Some(responder) = &el.responder {
4117            mask.set(EventKind::Touch, true);
4118            inst.responders.push((id, responder.clone()));
4119        }
4120        // Only the events that changed (with a slot's own when the node
4121        // takes a slot's props: they stay).
4122        let own = self.target_events(id, mask);
4123        let mut changed = (mask.bits() ^ old.bits()) & !own.bits();
4124        while changed != 0 {
4125            let kind = EventKind::ALL[changed.trailing_zeros() as usize];
4126            changed &= changed - 1;
4127            let _ = self.apply_op(Op::Listen {
4128                id,
4129                event: kind,
4130                enabled: mask.contains(kind),
4131            });
4132        }
4133        mask
4134    }
4135
4136    /// Queues the current frame for listeners belonging to a new region run.
4137    pub(super) fn initialize_layout_listeners(
4138        &mut self,
4139        host: NodeId,
4140        id: NodeId,
4141        el: &ElNode,
4142        old: EventMask,
4143        inst: &Instance,
4144    ) {
4145        // Only listeners of a new owner need the kept node's initial
4146        // frame. A listener passed in from outside the region stays live.
4147        if old.contains(EventKind::Layout)
4148            && let Ok(key) = self.key(id)
4149        {
4150            let frame = self.nodes[key as usize].frame;
4151            if !frame.origin.x.0.is_nan() {
4152                for (kind, listener) in &el.handlers {
4153                    if *kind == EventKind::Layout
4154                        && !inst
4155                            .handlers
4156                            .of(id)
4157                            .iter()
4158                            .any(|(k, old)| *k == *kind && old.same_owner(listener))
4159                    {
4160                        self.events.push(JsEvent::LayoutListener {
4161                            host,
4162                            id,
4163                            listener: listener.clone(),
4164                            frame,
4165                        });
4166                    }
4167                }
4168            }
4169        }
4170    }
4171
4172    fn reconcile_children(
4173        &mut self,
4174        parent: NodeId,
4175        old: Vec<Expanded>,
4176        new: Vec<ElNode>,
4177        host: NodeId,
4178        inst: &mut Instance,
4179    ) -> Vec<Expanded> {
4180        if new.is_empty() && old.is_empty() {
4181            return Vec::new();
4182        }
4183        let new = new.into_iter().map(|el| NewChild::Made(None, el)).collect();
4184        let (out, placeholder) = self.match_children(parent, old, new, host, inst);
4185        // A region's nodes go before what follows it.
4186        self.set_region_anchors(&out, inst, Anchor::End);
4187        let nested = parent != host && self.is_host(parent);
4188        if nested {
4189            if let Some(at) = placeholder {
4190                let anchor = self.anchor_after(&out[at + 1..], inst, Anchor::End);
4191                inst.children_at = Placement::Nested(parent, anchor);
4192            }
4193            self.place_filled(&out, inst, Anchor::End, |anchor| {
4194                Placement::Nested(parent, anchor)
4195            });
4196            self.fill_nested(parent, &out, host, inst);
4197            self.join_nested(parent, &out, inst);
4198            return out;
4199        }
4200        if let Some(at) = placeholder {
4201            let anchor = self.anchor_after(&out[at + 1..], inst, Anchor::End);
4202            inst.children_at = Placement::At(parent, anchor);
4203        }
4204        self.place_filled(&out, inst, Anchor::End, |anchor| {
4205            Placement::At(parent, anchor)
4206        });
4207        // The native children in the view's order: the JS children in the
4208        // placeholder's place, a region's nodes in its (moves only when the
4209        // order changed).
4210        let wanted_ids: Vec<NodeId> = out
4211            .iter()
4212            .flat_map(|e| match e.part {
4213                Part::Children => inst.js_children.clone(),
4214                Part::Filled(name) => self
4215                    .fill_of(inst, name)
4216                    .map(|f| self.fill_nodes(f))
4217                    .unwrap_or_default(),
4218                Part::Region(region) => self.region_nodes(region),
4219                _ => vec![e.id],
4220            })
4221            .collect();
4222        let wanted = || wanted_ids.iter();
4223        // A list positions its cells itself: their order does not matter
4224        // (and the cells it binds are not the view's), new ones join it.
4225        if self.is_list(parent) {
4226            // (A region's nodes join it as they come.)
4227            for e in out.iter().filter(|e| e.id != 0) {
4228                let joined = self
4229                    .key(e.id)
4230                    .is_ok_and(|k| self.nodes[k as usize].parent != NO_KEY);
4231                if !joined {
4232                    let _ = self.apply_op(Op::Insert {
4233                        parent,
4234                        child: e.id,
4235                        before: None,
4236                    });
4237                }
4238            }
4239            return out;
4240        }
4241        let in_order = self.key(parent).is_ok_and(|k| {
4242            let have = &self.nodes[k as usize].children;
4243            have.len() == wanted().count()
4244                && have
4245                    .iter()
4246                    .zip(wanted())
4247                    .all(|(&c, &id)| self.nodes[c as usize].id == id)
4248        });
4249        if !in_order {
4250            // From the end, each child before the one after it: only the
4251            // children out of place move. Moving a native view takes it
4252            // out of the window for a moment, which ends its touches and
4253            // its focus (Android: an input that gains a sibling would lose
4254            // the keyboard on each keystroke).
4255            let ids: Vec<NodeId> = wanted().copied().collect();
4256            // A first fill appends them in order: no child to find its place
4257            // among (from the end, each would scan the ones placed already).
4258            let empty = self
4259                .key(parent)
4260                .is_ok_and(|k| self.nodes[k as usize].children.is_empty());
4261            if empty {
4262                for &child in &ids {
4263                    let _ = self.apply_op(Op::Insert {
4264                        parent,
4265                        child,
4266                        before: None,
4267                    });
4268                }
4269                return out;
4270            }
4271            let mut before = None;
4272            for &child in ids.iter().rev() {
4273                if !self.precedes(parent, child, before) {
4274                    let _ = self.apply_op(Op::Insert {
4275                        parent,
4276                        child,
4277                        before,
4278                    });
4279                }
4280                before = Some(child);
4281            }
4282        }
4283        out
4284    }
4285
4286    /// Matches `new` with the `old` elements of `parent` and applies them;
4287    /// releases the old ones left. The elements as applied, and where the
4288    /// JS children go among them.
4289    pub(super) fn match_children(
4290        &mut self,
4291        parent: NodeId,
4292        old: Vec<Expanded>,
4293        new: Vec<NewChild>,
4294        host: NodeId,
4295        inst: &mut Instance,
4296    ) -> (Vec<Expanded>, Option<usize>) {
4297        // `children_each`: one wrapper per JS child, keyed by it; in a view,
4298        // a region following them.
4299        let new = if new.iter().any(
4300            |child| matches!(child, NewChild::Made(_, e) if matches!(e.kind, ElKind::EachChild(_))),
4301        ) {
4302            let mut each = Vec::with_capacity(new.len() + inst.js_children.len());
4303            for child in new {
4304                let NewChild::Made(owner, el) = child else {
4305                    each.push(child);
4306                    continue;
4307                };
4308                let ElKind::EachChild(place) = &el.kind else {
4309                    each.push(NewChild::Made(owner, el));
4310                    continue;
4311                };
4312                if inst.children_at != Placement::None {
4313                    log::error!(target: "js", "a view places its children once");
4314                    continue;
4315                }
4316                inst.children_at = Placement::Each;
4317                {
4318                    let children = match inst.js_kids {
4319                        Some(children) => children,
4320                        None => *inst.js_kids.insert(crate::element::signal_with(
4321                            inst.js_kids(),
4322                            crate::element::SignalEquals::Never,
4323                        )),
4324                    };
4325                    // A wrapper per child, kept while the child stays; its
4326                    // position follows it.
4327                    let place = place.clone();
4328                    let count = crate::element::computed(move || children.with(Vec::len));
4329                    let region = crate::element::each(
4330                        children,
4331                        |&(child, _): &(NodeId, bool)| child,
4332                        move |child, index| {
4333                            let at = Position::of(index.node(), count.node());
4334                            let (child, text) = child.get_untracked();
4335                            place(Child::js(child, text), at)
4336                        },
4337                    );
4338                    each.push(NewChild::Made(owner, region.0));
4339                }
4340            }
4341            each
4342        } else {
4343            new
4344        };
4345        let mut old: Vec<Option<Expanded>> = old.into_iter().map(Some).collect();
4346        let mut out = Vec::with_capacity(new.len());
4347        let mut placeholder = None;
4348        // Unkeyed elements take the next unused old element of their kind,
4349        // in order: an element that comes or goes (`.children(option)`)
4350        // does not shift its siblings onto new nodes.
4351        let mut cursor = 0;
4352        // Where the element after the last one kept was: kept rows mostly
4353        // follow each other as they did, and are then found without a
4354        // search of all the old ones for each.
4355        let mut after_kept = 0;
4356        // The keyed old elements by key, for the rows and elements not
4357        // where they were (a reversed list: each would search them all).
4358        let mut keys = OldKeys::default();
4359        for child in new {
4360            let (owner, el) = match child {
4361                NewChild::Made(owner, el) => (owner, el),
4362                // An `Each` row that stays: as it was. (One old element
4363                // at most has its key, which is its row's own.)
4364                NewChild::Kept(key) => {
4365                    let is = |o: &Option<Expanded>| {
4366                        o.as_ref().is_some_and(|o| o.key.as_ref() == Some(&key))
4367                    };
4368                    let at = if old.get(after_kept).is_some_and(is) {
4369                        Some(after_kept)
4370                    } else {
4371                        keys.find(&old, &key, |_| true)
4372                    };
4373                    match at.and_then(|at| {
4374                        after_kept = at + 1;
4375                        old[at].take()
4376                    }) {
4377                        Some(e) => out.push(e),
4378                        None => log::error!("a kept row is gone"),
4379                    }
4380                    continue;
4381                }
4382            };
4383            let child = |core: &mut Self| {
4384                core.match_child(
4385                    parent,
4386                    el,
4387                    host,
4388                    inst,
4389                    &mut old,
4390                    &mut out,
4391                    &mut placeholder,
4392                    &mut cursor,
4393                    &mut keys,
4394                );
4395            };
4396            match owner {
4397                Some(owner) => owner.run(|| child(self)),
4398                None => child(self),
4399            }
4400        }
4401        // Content of a nested component (`.child`, `.fill`): it leaves and
4402        // joins the nested host as JS children and slots do, so the nested
4403        // component's view places it.
4404        let nested = parent != host && self.is_host(parent);
4405        for o in old.into_iter().flatten() {
4406            // What fills a slot this view placed there stays (another
4407            // view's): it leaves first.
4408            self.unplace_filled(&o, inst);
4409            if nested && o.part == Part::Children {
4410                // The JS children passed on stay (JS's): they leave.
4411                for &child in &inst.js_children {
4412                    let _ = self.intercept(Op::Remove { parent, child });
4413                }
4414            } else if nested {
4415                for node in self.placed(&o) {
4416                    self.forget_nested(parent, node);
4417                }
4418            }
4419            self.release_expanded(o);
4420        }
4421        (out, placeholder)
4422    }
4423
4424    /// Matches element `el` with one of the `old` elements of `parent` and
4425    /// applies it (see [`Self::match_children`]).
4426    #[allow(clippy::too_many_arguments, reason = "the matching's state")]
4427    fn match_child(
4428        &mut self,
4429        parent: NodeId,
4430        mut el: ElNode,
4431        host: NodeId,
4432        inst: &mut Instance,
4433        old: &mut [Option<Expanded>],
4434        out: &mut Vec<Expanded>,
4435        placeholder: &mut Option<usize>,
4436        cursor: &mut usize,
4437        keys: &mut OldKeys,
4438    ) {
4439        // A slot a view fills: placed as it is (`Filled`), or in a node of
4440        // this view's own when the view gives it anything, which lays its
4441        // one node out through while it styles none of its layout (as JS's
4442        // holders: `lay_out_through`).
4443        let mut wrapper = false;
4444        if let ElKind::Slot(name) = el.kind
4445            && inst.fills.iter().any(|f| f.name == name)
4446        {
4447            if is_plain(&el) {
4448                el.kind = ElKind::Filled(name);
4449            } else {
4450                el.kind = ElKind::Plain;
4451                let mut filled = ElNode::new(Tag::View);
4452                filled.kind = ElKind::Filled(name);
4453                el.children = vec![filled];
4454                el.key.get_or_insert_with(|| format!("slot:{name}").into());
4455                wrapper = true;
4456            }
4457        }
4458        match std::mem::replace(&mut el.kind, ElKind::Plain) {
4459            ElKind::Filled(name) => {
4460                if let Some(j) = old
4461                    .iter()
4462                    .position(|o| o.as_ref().is_some_and(|o| o.part == Part::Filled(name)))
4463                {
4464                    old[j] = None;
4465                }
4466                out.push(Expanded::js(0, Part::Filled(name)));
4467            }
4468            ElKind::Fill(name) => {
4469                // Content of the nested component `parent`, as its children
4470                // are: nodes of this view, its regions bound here.
4471                let prev = old
4472                    .iter()
4473                    .position(|o| o.as_ref().is_some_and(|o| o.part == Part::Fill(name)))
4474                    .and_then(|j| old[j].take());
4475                let old_children = prev.map(|p| p.children).unwrap_or_default();
4476                let new = std::mem::take(&mut el.children)
4477                    .into_iter()
4478                    .map(|c| NewChild::Made(None, c))
4479                    .collect();
4480                let filling = self.components.filling.replace((parent, name));
4481                let (children, _) = self.match_children(parent, old_children, new, host, inst);
4482                self.components.filling = filling;
4483                let mut e = Expanded::js(0, Part::Fill(name));
4484                e.children = children;
4485                out.push(e);
4486            }
4487            ElKind::Slot(name) => {
4488                // The slot's own node, while the app passes one.
4489                let Some(&(_, node)) = inst.slots.iter().find(|(s, _)| *s == name) else {
4490                    return;
4491                };
4492                let at = old.iter().position(|o| {
4493                    o.as_ref()
4494                        .is_some_and(|o| o.part == Part::Slot && o.id == node)
4495                });
4496                let prev = at.and_then(|j| old[j].take());
4497                out.push(self.reconcile_slot(prev, node, el, host, inst));
4498            }
4499            ElKind::Children => {
4500                if placeholder.is_some() || inst.children_at != Placement::None {
4501                    log::error!(target: "js", "a view places its children once");
4502                    return;
4503                }
4504                if let Some(j) = old
4505                    .iter()
4506                    .position(|o| o.as_ref().is_some_and(|o| o.part == Part::Children))
4507                {
4508                    old[j] = None;
4509                }
4510                *placeholder = Some(out.len());
4511                inst.children_owner = Some(crate::element::Owner::current());
4512                out.push(Expanded::js(0, Part::Children));
4513            }
4514            ElKind::JsChild(id) => {
4515                // Taken over, not released (that would detach it).
4516                if let Some(j) = old.iter().position(|o| {
4517                    o.as_ref()
4518                        .is_some_and(|o| o.part == Part::JsChild && o.id == id)
4519                }) {
4520                    old[j] = None;
4521                }
4522                if inst.js_children.contains(&id) {
4523                    out.push(Expanded::js(id, Part::JsChild));
4524                }
4525            }
4526            // Expanded above.
4527            ElKind::EachChild(_) => {}
4528            // A view's region: bound, its nodes come with its patches.
4529            ElKind::Region(region) => {
4530                let id = self.bind_region(host, parent, region);
4531                let mut e = super::views::region_placeholder(id);
4532                // An `Each` row's region keeps its row's key: a run that
4533                // keeps the row finds it by that key (`NewChild::Kept`).
4534                e.key = el.key;
4535                out.push(e);
4536            }
4537            ElKind::List(list) => {
4538                // The glue's list: placed and laid out like a slot,
4539                // its rows wrapped by this view's row function.
4540                let Some(&(_, node)) = inst.slots.iter().find(|(s, _)| *s == list.name) else {
4541                    return;
4542                };
4543                let at = old.iter().position(|o| {
4544                    o.as_ref()
4545                        .is_some_and(|o| o.part == Part::Slot && o.id == node)
4546                });
4547                let prev = at.and_then(|j| old[j].take());
4548                let old_config = self
4549                    .components
4550                    .list_layouts
4551                    .remove(&node)
4552                    .or_else(|| prev.as_ref().and_then(|p| p.list.as_deref().copied()))
4553                    .unwrap_or_default();
4554                // Its bound layout is a binding.
4555                let parts = std::mem::take(&mut el.bound_list);
4556                let config = if parts.is_empty() {
4557                    list.config
4558                } else {
4559                    self.bind_list_layout(node, list.config, parts)
4560                };
4561                let mut props = std::mem::take(&mut self.components.props);
4562                config.changes(&old_config, &mut props);
4563                for prop in props.drain(..) {
4564                    let _ = self.apply_op(Op::SetProp { id: node, prop });
4565                }
4566                self.components.props = props;
4567                let mut e = self.reconcile_slot(prev, node, el, host, inst);
4568                e.list = Some(Box::new(config));
4569                let rows = self.rows_of_list(node);
4570                self.components.lists.insert(node, (list.row.clone(), rows));
4571                // Rows of the component whose view has this one: its
4572                // cells to come are wrapped too.
4573                if let Some(state) = self.components.virtual_lists.get_mut(&node) {
4574                    state.place = Some(list.row.clone());
4575                }
4576                let cells: Vec<NodeId> = match self.key(node) {
4577                    Ok(k) => self.nodes[k as usize]
4578                        .children
4579                        .iter()
4580                        .map(|&c| self.nodes[c as usize].id)
4581                        .collect(),
4582                    Err(_) => Vec::new(),
4583                };
4584                for cell in cells {
4585                    self.wrap_row(cell, list.row.clone());
4586                }
4587                out.push(e);
4588            }
4589            kind => {
4590                el.kind = kind;
4591                let part = match &el.kind {
4592                    ElKind::Component(c) => Part::Component(c.name),
4593                    ElKind::VirtualList(_) => Part::VirtualList,
4594                    ElKind::Raw => Part::Raw,
4595                    _ => Part::Node,
4596                };
4597                // A component made again is a new one, as in TSX: it runs
4598                // once, so an old instance cannot take a new element (its
4599                // view would keep what it made from the old props).
4600                let component = matches!(part, Part::Component(_));
4601                let matches = |o: &Expanded| !component && o.tag == el.tag && o.part == part;
4602                let at = match &el.key {
4603                    Some(k) => keys.find(old, k, matches),
4604                    None => {
4605                        let at = old[(*cursor).min(old.len())..]
4606                            .iter()
4607                            .position(|o| o.as_ref().is_some_and(|o| o.key.is_none() && matches(o)))
4608                            .map(|j| j + *cursor);
4609                        if let Some(j) = at {
4610                            *cursor = j + 1;
4611                        }
4612                        at
4613                    }
4614                };
4615                let prev = at.and_then(|j| old[j].take());
4616                let e = if wrapper {
4617                    self.reconcile_wrapper(prev, el, host, inst)
4618                } else {
4619                    self.reconcile_node(prev, el, part, host, inst)
4620                };
4621                out.push(e);
4622            }
4623        }
4624    }
4625
4626    /// Whether `child` is content of the nested component hosted by
4627    /// `nested` right before `next` (the last when `next` is `None`).
4628    pub(super) fn nested_precedes(
4629        &self,
4630        nested: NodeId,
4631        child: NodeId,
4632        next: Option<NodeId>,
4633    ) -> bool {
4634        let Some(inst) = self.components.instances.get(&nested) else {
4635            return false;
4636        };
4637        let kids = &inst.js_children;
4638        kids.iter()
4639            .position(|&c| c == child)
4640            .is_some_and(|i| kids.get(i + 1).copied() == next)
4641    }
4642
4643    /// Inserts `child` into the content of the nested component hosted by
4644    /// `nested`, before `before`, as JS inserts its children.
4645    pub(super) fn join_nested_at(&mut self, nested: NodeId, child: NodeId, before: Option<NodeId>) {
4646        if let Ok(Some(op)) = self.intercept(Op::Insert {
4647            parent: nested,
4648            child,
4649            before,
4650        }) {
4651            let _ = self.apply_op(op);
4652        }
4653    }
4654
4655    /// Node `child` of this view, about to be released, is no longer
4656    /// content of the nested component hosted by `nested`: it leaves the
4657    /// component's children with no native removal (deleting a view
4658    /// detaches it, as a plain element's does).
4659    fn forget_nested(&mut self, nested: NodeId, child: NodeId) {
4660        if self.components.slot_names.remove(&child).is_some() {
4661            self.unslot(child);
4662            return;
4663        }
4664        let Some(inst) = self.components.instances.get_mut(&nested) else {
4665            return;
4666        };
4667        let count = inst.js_children.len();
4668        inst.forget_js_child(child);
4669        if inst.js_children.len() == count {
4670            return;
4671        }
4672        inst.js_children_changed();
4673        let place = inst.children_at;
4674        if inst.js_children.is_empty() || place == Placement::Each {
4675            self.components.mark(nested);
4676        }
4677        // Passed on deeper, it leaves those components' children too.
4678        if let Placement::Nested(deeper, _) = place
4679            && self.is_host(deeper)
4680        {
4681            self.forget_nested(deeper, child);
4682        }
4683    }
4684
4685    /// The content `out` of the nested component hosted by `nested`, in
4686    /// order: its children as the host's JS children (`js_children`, the
4687    /// view's own JS children, where it passes them on), its slots' holders
4688    /// in their slots (inserted only when that changed).
4689    fn join_nested(&mut self, nested: NodeId, out: &[Expanded], inst: &Instance) {
4690        let insert = |core: &mut Self, child: NodeId, before: Option<NodeId>| {
4691            if let Ok(Some(op)) = core.intercept(Op::Insert {
4692                parent: nested,
4693                child,
4694                before,
4695            }) {
4696                let _ = core.apply_op(op);
4697            }
4698        };
4699        let (slots, children): (Vec<NodeId>, Vec<NodeId>) = out
4700            .iter()
4701            .flat_map(|e| match e.part {
4702                Part::Children => inst.js_children.clone(),
4703                Part::Filled(name) => self
4704                    .fill_of(inst, name)
4705                    .map(|f| self.fill_nodes(f))
4706                    .unwrap_or_default(),
4707                // A slot's: placed by the nested view where it places it.
4708                Part::Fill(_) | Part::Tooltip => Vec::new(),
4709                _ => self.placed(e),
4710            })
4711            .partition(|id| self.components.slot_names.contains_key(id));
4712        for slot in slots {
4713            if self.components.slot_hosts.get(&slot) != Some(&nested) {
4714                insert(self, slot, None);
4715            }
4716        }
4717        let same = self
4718            .components
4719            .instances
4720            .get(&nested)
4721            .is_some_and(|i| i.js_children == children);
4722        if !same {
4723            let mut before = None;
4724            for &child in children.iter().rev() {
4725                insert(self, child, before);
4726                before = Some(child);
4727            }
4728        }
4729    }
4730
4731    /// The fill of slot `name` among `inst`'s.
4732    pub(super) fn fill_of<'a>(&self, inst: &'a Instance, name: &'static str) -> Option<&'a Fill> {
4733        inst.fills.iter().find(|f| f.name == name)
4734    }
4735
4736    /// The nodes of `fill` now, in order.
4737    pub(super) fn fill_nodes(&self, fill: &Fill) -> Vec<NodeId> {
4738        self.fill_nodes_with(fill, None)
4739    }
4740
4741    /// [`Self::fill_nodes`], with `out`'s instance for its host (one taken
4742    /// out of the instances while its view is reconciled).
4743    fn fill_nodes_with(&self, fill: &Fill, out: Option<(NodeId, &Instance)>) -> Vec<NodeId> {
4744        let mut nodes = Vec::with_capacity(fill.parts.len());
4745        for part in &fill.parts {
4746            match *part {
4747                FillPart::Node(id) => nodes.push(id),
4748                FillPart::Region(region) => self.fill_region_nodes(region, out, &mut nodes),
4749                FillPart::Filled(name) => self.passed_nodes(fill.from, name, out, &mut nodes),
4750            }
4751        }
4752        nodes
4753    }
4754
4755    /// Adds the nodes of region `region` of a fill to `nodes`, what fills
4756    /// a slot of the region's view passed on among them.
4757    fn fill_region_nodes(
4758        &self,
4759        region: u32,
4760        out: Option<(NodeId, &Instance)>,
4761        nodes: &mut Vec<NodeId>,
4762    ) {
4763        let Some(state) = self.components.regions.get(&region) else {
4764            return;
4765        };
4766        for e in &state.children {
4767            match e.part {
4768                Part::Filled(name) => self.passed_nodes(state.host, name, out, nodes),
4769                Part::Region(inner) => self.fill_region_nodes(inner, out, nodes),
4770                _ => nodes.extend(self.placed(e)),
4771            }
4772        }
4773    }
4774
4775    /// Adds the nodes of what fills slot `name` of the component on `host`
4776    /// to `nodes` (`out`: an instance taken out of the instances).
4777    fn passed_nodes(
4778        &self,
4779        host: NodeId,
4780        name: &'static str,
4781        out: Option<(NodeId, &Instance)>,
4782        nodes: &mut Vec<NodeId>,
4783    ) {
4784        let inst = match out {
4785            Some((h, inst)) if h == host => Some(inst),
4786            _ => self.components.instances.get(&host).map(|i| &**i),
4787        };
4788        if let Some(fill) = inst.and_then(|i| self.fill_of(i, name)) {
4789            nodes.extend(self.fill_nodes_with(fill, out));
4790        }
4791    }
4792
4793    /// The slots of the view on `host` whose fills `parts` pass on (as they
4794    /// are, or in a region of them).
4795    fn passed_slots(&self, parts: &[FillPart], host: NodeId, names: &mut Vec<&'static str>) {
4796        fn of_region<M: TextEngine>(
4797            core: &Core<M>,
4798            region: u32,
4799            host: NodeId,
4800            names: &mut Vec<&'static str>,
4801        ) {
4802            let Some(state) = core.components.regions.get(&region) else {
4803                return;
4804            };
4805            for e in &state.children {
4806                match e.part {
4807                    Part::Filled(name) if state.host == host => names.push(name),
4808                    Part::Region(inner) => of_region(core, inner, host, names),
4809                    _ => {}
4810                }
4811            }
4812        }
4813        for part in parts {
4814            match *part {
4815                FillPart::Filled(name) => names.push(name),
4816                FillPart::Region(region) => of_region(self, region, host, names),
4817                FillPart::Node(_) => {}
4818            }
4819        }
4820    }
4821
4822    /// Notes on the view on `host` (`inst`) which of its slots' fills go
4823    /// on into the fill of slot `name` of the nested component `nested`.
4824    pub(super) fn note_passed(
4825        &self,
4826        nested: NodeId,
4827        name: &'static str,
4828        host: NodeId,
4829        inst: &mut Instance,
4830    ) {
4831        let mut passed = Vec::new();
4832        if let Some(fill) = self
4833            .components
4834            .instances
4835            .get(&nested)
4836            .and_then(|t| self.fill_of(t, name))
4837        {
4838            self.passed_slots(&fill.parts, host, &mut passed);
4839        }
4840        for fill in &mut inst.fills {
4841            if passed.contains(&fill.name) {
4842                fill.forwarded = Some((nested, name));
4843            } else if fill.forwarded == Some((nested, name)) {
4844                fill.forwarded = None;
4845            }
4846        }
4847    }
4848
4849    /// Where `out` (a view's children, or a region's, `end` after them)
4850    /// places what fills its slots: `place` of what follows each.
4851    pub(super) fn place_filled(
4852        &self,
4853        out: &[Expanded],
4854        inst: &mut Instance,
4855        end: Anchor,
4856        place: impl Fn(Anchor) -> Placement,
4857    ) {
4858        if inst.fills.is_empty() {
4859            return;
4860        }
4861        for (i, e) in out.iter().enumerate() {
4862            let Part::Filled(name) = e.part else {
4863                continue;
4864            };
4865            let at = place(self.anchor_after(&out[i + 1..], inst, end));
4866            if let Some(fill) = inst.fills.iter_mut().find(|f| f.name == name) {
4867                fill.at = at;
4868            }
4869        }
4870    }
4871
4872    /// `e` and what it holds leave this view: what fills a slot it placed
4873    /// leaves its place (it stays: another view's).
4874    pub(super) fn unplace_filled(&mut self, e: &Expanded, inst: &mut Instance) {
4875        if inst.fills.is_empty() {
4876            return;
4877        }
4878        match e.part {
4879            Part::Filled(name) => {
4880                let Some(fill) = inst.fills.iter_mut().find(|f| f.name == name) else {
4881                    return;
4882                };
4883                let at = std::mem::replace(&mut fill.at, Placement::None);
4884                if at == Placement::None {
4885                    return;
4886                }
4887                let nodes = self.fill_nodes(self.fill_of(inst, name).expect("a fill"));
4888                for node in nodes {
4889                    self.unplace(at, node);
4890                }
4891            }
4892            Part::Region(region) => {
4893                let children = self
4894                    .components
4895                    .regions
4896                    .get_mut(&region)
4897                    .map(|s| std::mem::take(&mut s.children))
4898                    .unwrap_or_default();
4899                for c in &children {
4900                    self.unplace_filled(c, inst);
4901                }
4902                if let Some(state) = self.components.regions.get_mut(&region) {
4903                    state.children = children;
4904                }
4905            }
4906            _ => {
4907                for c in &e.children {
4908                    self.unplace_filled(c, inst);
4909                }
4910            }
4911        }
4912    }
4913
4914    /// The slots the view on `host` (its instance `inst`) fills of the
4915    /// nested component hosted by `nested`, from its content `out`: they
4916    /// replace the ones before (a fill gone was released with its nodes,
4917    /// what was passed on and no longer is leaves its place), and go where
4918    /// the nested view places them.
4919    fn fill_nested(&mut self, nested: NodeId, out: &[Expanded], host: NodeId, inst: &mut Instance) {
4920        let fills: Vec<(&'static str, Vec<FillPart>)> = out
4921            .iter()
4922            .filter_map(|e| match e.part {
4923                Part::Fill(name) => Some((
4924                    name,
4925                    e.children
4926                        .iter()
4927                        .filter_map(|c| match c.part {
4928                            Part::Region(region) => Some(FillPart::Region(region)),
4929                            Part::Filled(name) => Some(FillPart::Filled(name)),
4930                            _ if c.id != 0 => Some(FillPart::Node(c.id)),
4931                            _ => None,
4932                        })
4933                        .collect(),
4934                )),
4935                _ => None,
4936            })
4937            .collect();
4938        // What fills this view's own slots goes where they are passed on.
4939        for fill in &mut inst.fills {
4940            if fill.forwarded.is_some_and(|(n, _)| n == nested) {
4941                fill.forwarded = None;
4942            }
4943        }
4944        for (name, parts) in &fills {
4945            let mut passed = Vec::new();
4946            self.passed_slots(parts, host, &mut passed);
4947            for fill in inst.fills.iter_mut().filter(|f| passed.contains(&f.name)) {
4948                fill.forwarded = Some((nested, name));
4949            }
4950        }
4951        let Some(target) = self.components.instances.get_mut(&nested) else {
4952            return;
4953        };
4954        if fills.is_empty() && target.fills.is_empty() {
4955            return;
4956        }
4957        let mut changed = target.fills.len() != fills.len();
4958        let old = std::mem::take(&mut target.fills);
4959        let mut joining = Vec::new();
4960        for (name, parts) in fills {
4961            let (at, forwarded, same) = match old.iter().find(|f| f.name == name) {
4962                Some(f) => (f.at, f.forwarded, f.parts == parts),
4963                None => (Placement::None, None, false),
4964            };
4965            changed |= !same;
4966            if !same {
4967                joining.push(name);
4968            }
4969            target.fills.push(Fill {
4970                name,
4971                parts,
4972                from: host,
4973                at,
4974                forwarded,
4975            });
4976        }
4977        if !changed {
4978            return;
4979        }
4980        // What was passed on and is no longer leaves its place (it stays:
4981        // the view above's); what was released went with its Delete.
4982        let out = Some((host, &*inst));
4983        let mut leaving = Vec::new();
4984        for fill in &old {
4985            let at = self.fill_place(nested, fill.name);
4986            let now = self
4987                .components
4988                .instances
4989                .get(&nested)
4990                .and_then(|t| self.fill_of(t, fill.name))
4991                .map(|f| self.fill_nodes_with(f, out))
4992                .unwrap_or_default();
4993            for node in self.fill_nodes_with(fill, out) {
4994                if !now.contains(&node) && self.key(node).is_ok() {
4995                    leaving.push((at, node));
4996                }
4997            }
4998        }
4999        for (at, node) in leaving {
5000            self.unplace(at, node);
5001        }
5002        for name in joining {
5003            self.join_fill(nested, name, out);
5004        }
5005        // Its slot props follow (`Some` while a fill has nodes).
5006        self.components.mark(nested);
5007        let names: Vec<&'static str> = self.components.instances[&nested]
5008            .fills
5009            .iter()
5010            .map(|f| f.name)
5011            .collect();
5012        for name in names {
5013            self.place_fill_with(nested, name, Some((host, &*inst)));
5014        }
5015    }
5016
5017    /// The fill of slot `name` of the nested component hosted by `nested`
5018    /// is content its view places, as its children are
5019    /// ([`Self::join_content`]): the components in it wait to be placed
5020    /// and read the context of the view that places them (`out`: an
5021    /// instance taken out of the instances).
5022    pub(super) fn join_fill(
5023        &mut self,
5024        nested: NodeId,
5025        name: &'static str,
5026        out: Option<(NodeId, &Instance)>,
5027    ) {
5028        let nodes = self
5029            .components
5030            .instances
5031            .get(&nested)
5032            .and_then(|inst| self.fill_of(inst, name))
5033            .map(|fill| self.fill_nodes_with(fill, out))
5034            .unwrap_or_default();
5035        for node in nodes {
5036            self.join_content(node);
5037        }
5038    }
5039
5040    /// Where the nodes of the fill of slot `name` of the nested component
5041    /// hosted by `nested` are placed: where its view places them, or where
5042    /// the slot it is passed on to is.
5043    fn fill_place(&self, nested: NodeId, name: &'static str) -> Placement {
5044        let Some(fill) = self
5045            .components
5046            .instances
5047            .get(&nested)
5048            .and_then(|inst| self.fill_of(inst, name))
5049        else {
5050            return Placement::None;
5051        };
5052        match (fill.at, fill.forwarded) {
5053            (Placement::None, Some((deeper, slot))) => self.fill_place(deeper, slot),
5054            (at, _) => at,
5055        }
5056    }
5057
5058    /// Puts the nodes of the fill of slot `name` of the nested component
5059    /// hosted by `nested` where its view places them (a region of the fill
5060    /// changed, or the fill), and where it passes them on to.
5061    pub(super) fn place_fill(&mut self, nested: NodeId, name: &'static str) {
5062        self.place_fill_with(nested, name, None);
5063    }
5064
5065    /// [`Self::place_fill`], with `out`'s instance for its host (one taken
5066    /// out of the instances while its view is reconciled).
5067    fn place_fill_with(
5068        &mut self,
5069        nested: NodeId,
5070        name: &'static str,
5071        out: Option<(NodeId, &Instance)>,
5072    ) {
5073        let Some(fill) = self
5074            .components
5075            .instances
5076            .get(&nested)
5077            .and_then(|inst| self.fill_of(inst, name))
5078        else {
5079            return;
5080        };
5081        let (nodes, at, forwarded) = (self.fill_nodes_with(fill, out), fill.at, fill.forwarded);
5082        if let Some((deeper, slot)) = forwarded {
5083            // Passed on: the deeper slot's fill holds them, and its prop
5084            // follows.
5085            self.components.mark(deeper);
5086            self.place_fill_with(deeper, slot, out);
5087        }
5088        match at {
5089            Placement::At(parent, anchor) => {
5090                let parent_key = self.key(parent).ok();
5091                // An anchor that left the parent: at the end.
5092                let mut before = self.anchor_node(anchor).filter(|&a| {
5093                    self.key(a)
5094                        .is_ok_and(|k| Some(self.nodes[k as usize].parent) == parent_key)
5095                });
5096                for &child in nodes.iter().rev() {
5097                    if !self.precedes(parent, child, before) {
5098                        let _ = self.apply_op(Op::Insert {
5099                            parent,
5100                            child,
5101                            before,
5102                        });
5103                    }
5104                    before = Some(child);
5105                }
5106                // In a holder: the slot's props follow its one element.
5107                if self.components.fill_holders.contains(&parent) {
5108                    self.retarget_slot(parent, None);
5109                }
5110            }
5111            Placement::Nested(other, anchor) => {
5112                let mut before = self.anchor_node(anchor);
5113                for &child in nodes.iter().rev() {
5114                    if !self.nested_precedes(other, child, before) {
5115                        self.join_nested_at(other, child, before);
5116                    }
5117                    before = Some(child);
5118                }
5119            }
5120            _ => {}
5121        }
5122    }
5123
5124    /// Whether `child` is a child of `parent` right before `next` (the last
5125    /// one when `next` is `None`).
5126    pub(super) fn precedes(&self, parent: NodeId, child: NodeId, next: Option<NodeId>) -> bool {
5127        self.preceding(parent, child, next, None).is_some()
5128    }
5129
5130    /// Where `child` is among `parent`'s children when it is right before
5131    /// `next` ([`Self::precedes`]). `hint` is where it is expected, looked
5132    /// at first: nodes checked from the last to the first, each before the
5133    /// one after it, are found without a search of the children for each.
5134    /// A node not among them, as each node of a region mounted for the
5135    /// first time, is known from its own parent without a search either.
5136    pub(super) fn preceding(
5137        &self,
5138        parent: NodeId,
5139        child: NodeId,
5140        next: Option<NodeId>,
5141        hint: Option<usize>,
5142    ) -> Option<usize> {
5143        let k = self.key(parent).ok()?;
5144        if self.nodes[self.key(child).ok()? as usize].parent != k {
5145            return None;
5146        }
5147        let children = &self.nodes[k as usize].children;
5148        let id = |at: usize| children.get(at).map(|&c| self.nodes[c as usize].id);
5149        let at = match hint {
5150            Some(at) if id(at) == Some(child) => at,
5151            _ => {
5152                let at = children
5153                    .iter()
5154                    .position(|&c| self.nodes[c as usize].id == child);
5155                self.placing(at.map_or(children.len(), |at| at + 1));
5156                at?
5157            }
5158        };
5159        (id(at + 1) == next).then_some(at)
5160    }
5161
5162    /// `n` more siblings or overlays looked at to place a view
5163    /// ([`Components::placing_work`]).
5164    #[cfg(test)]
5165    pub(super) fn placing(&self, n: usize) {
5166        let work = &self.components.placing_work;
5167        work.set(work.get() + n);
5168    }
5169
5170    #[cfg(not(test))]
5171    #[inline(always)]
5172    pub(super) fn placing(&self, _n: usize) {}
5173
5174    /// `n` more mount items looked at for views taking the kind of their
5175    /// component's root ([`Components::retag_work`]).
5176    #[cfg(test)]
5177    pub(super) fn retagging(&self, n: usize) {
5178        let work = &self.components.retag_work;
5179        work.set(work.get() + n);
5180    }
5181
5182    #[cfg(not(test))]
5183    #[inline(always)]
5184    pub(super) fn retagging(&self, _n: usize) {}
5185
5186    /// Slot node `node` as element `el` of `host`'s view: its styles, props
5187    /// and handlers (its children are the app's JSX). Its bound parts are
5188    /// bound as a node's of the view are; what is not a style goes to the
5189    /// slot's target, the app's element when the node holds one
5190    /// ([`super::slots`]).
5191    fn reconcile_slot(
5192        &mut self,
5193        prev: Option<Expanded>,
5194        node: NodeId,
5195        mut el: ElNode,
5196        host: NodeId,
5197        inst: &mut Instance,
5198    ) -> Expanded {
5199        let bound = super::views::Bound::take(&mut el);
5200        // What its bindings applied since it was placed is what the node
5201        // has (an `Expanded` keeps what was applied with it).
5202        let applied = inst.bound.remove(&node);
5203        let (old_attrs, old_style, old_classes) = match (prev, applied) {
5204            (Some(_), Some(a)) => (a.attrs, a.style, a.classes),
5205            (Some(p), None) => (p.attrs, p.style, p.classes),
5206            (None, _) => (Attrs::default(), StyleRefinement::default(), (None, None)),
5207        };
5208        let bound = bound.map(|bound| self.bind_parts(host, node, bound, &mut el));
5209        self.apply_slot_attrs(node, host, &el.attrs, &old_attrs, Some(&mut *inst));
5210        let classes = self.apply_el_styles(
5211            node,
5212            &el.style,
5213            &old_style,
5214            old_classes,
5215            el.attrs.class.as_ref(),
5216            None,
5217        );
5218        if bound.is_some() {
5219            Self::keep_bound(inst, node, &el.attrs, &el.style, classes.clone(), None);
5220        }
5221        // Its events are the component's first (`component_event` finds it
5222        // by its host); the node stays JS's or the placing view's.
5223        let events = self.apply_slot_handlers(node, host, &el, inst);
5224        Expanded {
5225            id: node,
5226            tag: Tag::View,
5227            key: None,
5228            text: None,
5229            attrs: el.attrs,
5230            style: el.style,
5231            classes,
5232            events,
5233            list: None,
5234            part: Part::Slot,
5235            children: Vec::new(),
5236        }
5237    }
5238
5239    /// The node of `host`'s view element `el` wraps a slot's fill in (its
5240    /// one child places the fill): a slot node as JS's holders are. Its
5241    /// styles are its own, and it lays the fill's one node out through
5242    /// while they style none of its layout; the rest of what the place
5243    /// gives goes to that node when the fill is one element
5244    /// ([`super::slots`]), so its focus, keys and presses reach the
5245    /// component's listeners as a JS app's element's do.
5246    fn reconcile_wrapper(
5247        &mut self,
5248        mut prev: Option<Expanded>,
5249        mut el: ElNode,
5250        host: NodeId,
5251        inst: &mut Instance,
5252    ) -> Expanded {
5253        let (id, old_children) = match &mut prev {
5254            Some(p) => (p.id, std::mem::take(&mut p.children)),
5255            None => {
5256                let id = self.components.alloc();
5257                let _ = self.apply_op(Op::Create { id, tag: el.tag });
5258                self.components.owners.insert(id, host);
5259                (id, Vec::new())
5260            }
5261        };
5262        self.components.fill_holders.insert(id);
5263        // The fill first: its one element is where the rest goes.
5264        let children = std::mem::take(&mut el.children);
5265        let children = self.reconcile_children(id, old_children, children, host, inst);
5266        let (tag, key) = (el.tag, el.key.clone());
5267        let mut e = self.reconcile_slot(prev, id, el, host, inst);
5268        if let Ok(k) = self.key(id) {
5269            self.lay_out_through(k);
5270        }
5271        e.tag = tag;
5272        e.key = key;
5273        e.part = Part::Node;
5274        e.children = children;
5275        e
5276    }
5277
5278    pub(super) fn reconcile_node(
5279        &mut self,
5280        prev: Option<Expanded>,
5281        mut el: ElNode,
5282        part: Part,
5283        host: NodeId,
5284        inst: &mut Instance,
5285    ) -> Expanded {
5286        // A text whose content is bound, with spans: the content is its
5287        // first span.
5288        if !el.children.is_empty()
5289            && let Some(content) = el.bound_text.take()
5290        {
5291            let mut first = ElNode::new(Tag::Text);
5292            first.text = Some(SharedString::default());
5293            first.bound_text = Some(content);
5294            el.text = None;
5295            el.children.insert(0, first);
5296        }
5297        // Bound parts are bound once the node exists, and what they read
5298        // now is applied with its static parts. The styles given a nested
5299        // component are a binding of their own (its host's styles are its
5300        // own and the app's).
5301        let nested_style = (matches!(el.kind, ElKind::Component(_)) && el.style.is_bound())
5302            .then(|| el.style.clone());
5303        // So are its bound attributes (insets).
5304        let nested_attrs = (matches!(el.kind, ElKind::Component(_)) && !el.bound_attrs.is_empty())
5305            .then(|| (el.attrs.clone(), el.bound_attrs.clone()));
5306        let bound = if matches!(el.kind, ElKind::Component(_)) {
5307            el.resolve_once();
5308            None
5309        } else {
5310            super::views::Bound::take(&mut el)
5311        };
5312        if matches!(el.kind, ElKind::Raw) {
5313            return self.reconcile_raw(prev, el, host);
5314        }
5315        // A text with spans: its own content is the first piece, as JS
5316        // has it.
5317        if !el.children.is_empty()
5318            && let Some(content) = el.text.take()
5319            && !content.is_empty()
5320        {
5321            let mut raw = ElNode::new(Tag::Text);
5322            raw.text = Some(content);
5323            raw.kind = ElKind::Raw;
5324            el.children.insert(0, raw);
5325        }
5326        let old_list = prev
5327            .as_ref()
5328            .and_then(|p| p.list.as_deref().copied())
5329            .unwrap_or_default();
5330        let kept = prev.is_some();
5331        let (id, old_attrs, old_style, old_classes, old_events, old_children, old_text) = match prev
5332        {
5333            Some(mut p) => {
5334                // Bindings may have changed the node since this element
5335                // was applied. Diff against those latest values, even
5336                // when the new element has no bindings.
5337                if let Some(applied) = inst.bound.remove(&p.id) {
5338                    p.attrs = applied.attrs;
5339                    p.style = applied.style;
5340                    p.classes = applied.classes;
5341                    p.text = applied.text;
5342                }
5343                (
5344                    p.id, p.attrs, p.style, p.classes, p.events, p.children, p.text,
5345                )
5346            }
5347            None => {
5348                let id = self.components.alloc();
5349                let _ = self.apply_op(Op::Create { id, tag: el.tag });
5350                self.components.owners.insert(id, host);
5351                if let ElKind::Component(c) = &el.kind {
5352                    self.create_instance_for(id, c);
5353                }
5354                (
5355                    id,
5356                    Attrs::default(),
5357                    StyleRefinement::default(),
5358                    (None, None),
5359                    EventMask::default(),
5360                    Vec::new(),
5361                    None,
5362                )
5363            }
5364        };
5365        // The element snapshot predates any applied layout binding patches.
5366        let old_list = if matches!(el.kind, ElKind::VirtualList(_)) {
5367            self.components.list_layouts.remove(&id).unwrap_or(old_list)
5368        } else {
5369            old_list
5370        };
5371        let bound = bound.map(|bound| self.bind_parts(host, id, bound, &mut el));
5372        let (component, virtual_list) = match std::mem::replace(&mut el.kind, ElKind::Plain) {
5373            ElKind::Component(c) => (Some(c), None),
5374            ElKind::VirtualList(list) => (None, Some(list)),
5375            _ => (None, None),
5376        };
5377        if let Some(c) = component {
5378            // A nested component: its props, and the styles as the app's
5379            // classes of its host.
5380            self.set_element_props(id, c.props.as_ref());
5381            if self.is_host(id) {
5382                if let Some(style) = nested_style {
5383                    el.style = self.bind_nested_style(id, style);
5384                }
5385                let user = (!el.style.is_empty()).then(|| self.components.lowered(&el.style));
5386                self.set_user(id, user);
5387            }
5388            // Made again, it hears this run's listeners only.
5389            if kept {
5390                inst.event_handlers.retain(|(n, _)| *n != id);
5391            }
5392            // The view's listeners of its node's events, after its root's.
5393            if self.is_host(id) {
5394                self.set_given_handlers(id, std::mem::take(&mut el.handlers));
5395            }
5396            inst.event_handlers
5397                .extend(c.on_event.into_iter().map(|listener| (id, listener)));
5398            // Its `ComponentRef`.
5399            let element_ref = el.attrs.take_element_ref();
5400            if old_attrs.element_ref() != element_ref.as_ref()
5401                && let Some(r) = old_attrs.element_ref()
5402            {
5403                r.detach(id);
5404            }
5405            if let Some(r) = &element_ref {
5406                r.attach(id);
5407            }
5408            // The tooltip it gives the root: an element of this view, which
5409            // the root's node shows as it shows JS's.
5410            let mut old_children = old_children;
5411            let tooltip =
5412                self.reconcile_given_tooltip(id, &mut old_children, &mut el.children, host, inst);
5413            let tooltip_prop = tooltip
5414                .as_ref()
5415                .and_then(|t| t.children.first())
5416                .filter(|e| e.id != 0)
5417                .map(|e| Prop::Tooltip(crate::overlay::TooltipContent::Node(e.id)));
5418            // The rest goes on its root, after the root's own.
5419            if self.is_host(id) {
5420                let given = match nested_attrs {
5421                    Some((mut base, parts)) => {
5422                        if let Some(prop) = &tooltip_prop {
5423                            crate::element::host::set_in(&mut base.props, prop.clone());
5424                        }
5425                        self.bind_nested_attrs(id, base, parts)
5426                    }
5427                    None => {
5428                        let mut given = std::mem::take(&mut el.attrs);
5429                        if let Some(prop) = tooltip_prop {
5430                            crate::element::host::set_in(&mut given.props, prop);
5431                        }
5432                        given
5433                    }
5434                };
5435                self.set_given(id, given);
5436            }
5437            // The content this view passes it (`.child`, `.fill`): nodes of
5438            // this view, inserted into its host as JS inserts its children,
5439            // so the nested component places them where its view says.
5440            // Lazy children are passed only while it places them, as JS
5441            // makes the app's (`$children`); slots and rows always are.
5442            let mut content = std::mem::take(&mut el.children);
5443            let is_slot = |c: &ElNode| {
5444                matches!(c.kind, ElKind::Fill(_))
5445                    || c.attrs
5446                        .props
5447                        .iter()
5448                        .any(|p| matches!(p, Prop::ComponentSlot(_)))
5449            };
5450            let lazy = self
5451                .components
5452                .instances
5453                .get(&id)
5454                .is_some_and(|i| i.spec.as_ref().is_some_and(|s| s.lazy_children));
5455            if lazy {
5456                // A view passes them while a signal of the nested
5457                // component's says it places them: a region of its own.
5458                let (slots, kids): (Vec<ElNode>, Vec<ElNode>) =
5459                    content.into_iter().partition(|c| is_slot(c));
5460                content = slots;
5461                if !kids.is_empty() {
5462                    let wanted = self.children_wanted_signal(id);
5463                    let shown = crate::element::when(wanted, move || {
5464                        kids.iter()
5465                            .cloned()
5466                            .map(crate::element::AnyElement)
5467                            .collect::<Vec<_>>()
5468                    });
5469                    content.push(shown.into_element().0);
5470                }
5471            }
5472            let mut children = self.reconcile_children(id, old_children, content, host, inst);
5473            children.extend(tooltip);
5474            let mut kept_attrs = Attrs::default();
5475            kept_attrs.set_element_ref(element_ref);
5476            return Expanded {
5477                id,
5478                tag: el.tag,
5479                key: el.key,
5480                text: None,
5481                attrs: kept_attrs,
5482                style: el.style,
5483                classes: (None, None),
5484                events: EventMask::default(),
5485                list: None,
5486                part,
5487                children,
5488            };
5489        }
5490        if !self.apply_target_attrs(id, &el.attrs, &old_attrs, None) {
5491            self.apply_attrs(id, &el.attrs, &old_attrs);
5492        }
5493        let classes = self.apply_el_styles(
5494            id,
5495            &el.style,
5496            &old_style,
5497            old_classes,
5498            el.attrs.class.as_ref(),
5499            None,
5500        );
5501        let text = self.reconcile_text(id, host, el.text.take(), old_text);
5502        if bound.is_some() {
5503            Self::keep_bound(
5504                inst,
5505                id,
5506                &el.attrs,
5507                &el.style,
5508                classes.clone(),
5509                text.clone(),
5510            );
5511        }
5512        let events = self.apply_handlers(host, id, &el, old_events, EventMask::default(), inst);
5513        let new_children = std::mem::take(&mut el.children);
5514        let children = self.reconcile_children(id, old_children, new_children, host, inst);
5515        let list = match virtual_list {
5516            Some(list) => {
5517                let config = list.config;
5518                self.update_virtual_list(id, host, *list, &old_list);
5519                Some(Box::new(config))
5520            }
5521            None => None,
5522        };
5523        Expanded {
5524            id,
5525            tag: el.tag,
5526            key: el.key,
5527            text,
5528            attrs: el.attrs,
5529            style: el.style,
5530            classes,
5531            events,
5532            list,
5533            part,
5534            children,
5535        }
5536    }
5537
5538    /// The tooltip view `host` gives the root of the nested component on
5539    /// `nested` ([`ElKind::Tooltip`], taken out of its element's `content`),
5540    /// matched with the one it gave before (taken out of `old`, the
5541    /// element's children as applied): its element is a node of this view,
5542    /// out of the tree until the root's node shows it.
5543    fn reconcile_given_tooltip(
5544        &mut self,
5545        nested: NodeId,
5546        old: &mut Vec<Expanded>,
5547        content: &mut Vec<ElNode>,
5548        host: NodeId,
5549        inst: &mut Instance,
5550    ) -> Option<Expanded> {
5551        let prev = old
5552            .iter()
5553            .position(|e| e.part == Part::Tooltip)
5554            .map(|at| old.remove(at));
5555        let Some(at) = content
5556            .iter()
5557            .position(|c| matches!(c.kind, ElKind::Tooltip))
5558        else {
5559            if let Some(prev) = prev {
5560                self.release_expanded(prev);
5561            }
5562            return None;
5563        };
5564        let given = content.remove(at);
5565        let new = given
5566            .children
5567            .into_iter()
5568            .map(|c| NewChild::Made(None, c))
5569            .collect();
5570        let old = prev.map(|p| p.children).unwrap_or_default();
5571        let (children, _) = self.match_children(nested, old, new, host, inst);
5572        let mut tooltip = Expanded::js(0, Part::Tooltip);
5573        tooltip.children = children;
5574        Some(tooltip)
5575    }
5576
5577    /// A piece `el` of a text's content: its raw text node, created or
5578    /// changed (the view's order puts it in place).
5579    fn reconcile_raw(&mut self, prev: Option<Expanded>, el: ElNode, host: NodeId) -> Expanded {
5580        let content = el.text.unwrap_or_else(|| "".into());
5581        let id = match prev {
5582            Some(p) => {
5583                if p.text.as_ref().is_none_or(|(old, _)| *old != content) {
5584                    let _ = self.apply_op(Op::SetText {
5585                        id: p.id,
5586                        text: content.as_str().to_owned(),
5587                    });
5588                }
5589                p.id
5590            }
5591            None => {
5592                let id = self.components.alloc();
5593                let _ = self.apply_op(Op::CreateText {
5594                    id,
5595                    text: content.as_str().to_owned(),
5596                });
5597                self.components.owners.insert(id, host);
5598                id
5599            }
5600        };
5601        Expanded {
5602            id,
5603            tag: Tag::Text,
5604            key: None,
5605            text: Some((content, id)),
5606            attrs: Attrs::default(),
5607            style: StyleRefinement::default(),
5608            classes: (None, None),
5609            events: EventMask::default(),
5610            list: None,
5611            part: Part::Raw,
5612            children: Vec::new(),
5613        }
5614    }
5615
5616    /// A view's list of its own rows: its layout, its rows (a splice when
5617    /// the keys say rows came or went, then the count), and its live cells
5618    /// built again with the new row function (when the list is made
5619    /// again). A bound count or keys are a binding: a memo that moves the
5620    /// live cells' indices as the rows moved (dropping the content of cells
5621    /// whose row went) and queues the change for the list
5622    /// ([`Self::set_list_rows`]). The cells' positions run it before they
5623    /// are read, so the rows' own bindings never read the new rows at the
5624    /// old indices, whichever runs first.
5625    fn update_virtual_list(
5626        &mut self,
5627        id: NodeId,
5628        owner: NodeId,
5629        list: VirtualListEl,
5630        old: &ListConfig,
5631    ) {
5632        // The static layout (its bound parts come as patches).
5633        let mut props = std::mem::take(&mut self.components.props);
5634        list.config.changes(old, &mut props);
5635        for prop in props.drain(..) {
5636            let _ = self.apply_op(Op::SetProp { id, prop });
5637        }
5638        self.components.props = props;
5639        let before = self
5640            .components
5641            .virtual_lists
5642            .get(&id)
5643            .map(|state| (state.count, state.keys.clone()));
5644        // The rows of another component's `Items` prop (its slot's node).
5645        let items = self.components.slot_names.contains_key(&id);
5646        let state = self
5647            .components
5648            .virtual_lists
5649            .entry(id)
5650            .or_insert_with(|| VirtualListState {
5651                owner,
5652                scope: Rc::default(),
5653                row: list.row.clone(),
5654                count: 0,
5655                keys: None,
5656                separator: None,
5657                cells: Vec::new(),
5658                rows: CellRows::default(),
5659                moves: None,
5660                items,
5661                place: None,
5662                contents: Vec::new(),
5663                min_view: None,
5664                reported: None,
5665                latest: None,
5666                report: None,
5667            });
5668        // The rows go with the run that made the list. A list a later run
5669        // keeps takes that run's owner: its cells are made again below.
5670        if state.scope.get() != list.scope {
5671            state.scope.set(list.scope);
5672            if let Some(scope) = list.scope {
5673                let rows = Rc::downgrade(&state.rows);
5674                let current = Rc::downgrade(&state.scope);
5675                scope.run(|| {
5676                    crate::element::cleanup(move || {
5677                        // A run the list has since left keeps the rows of
5678                        // the run it is in now.
5679                        if current.upgrade().is_some_and(|c| c.get() == Some(scope)) {
5680                            dispose_rows(&rows);
5681                        }
5682                    })
5683                });
5684            }
5685        }
5686        let cells = state.rows.clone();
5687        let bound = matches!(list.count, Reactive::Bound(_)) || list.keys.is_some();
5688        let (count, keys) = (list.count, list.keys);
5689        let rows = move || (count.get(), keys.as_ref().map(|k| k()));
5690        let mut moves = None;
5691        let (count, keys) = if bound {
5692            let count_signal = self.list_count(id, 0);
5693            let patches = self.components.patches.clone();
5694            let first: Rc<RefCell<Option<Rows>>> = Rc::default();
5695            let slot = first.clone();
5696            let last: RefCell<Option<Rc<[u64]>>> = RefCell::new(None);
5697            let made = std::cell::Cell::new(false);
5698            let memo = crate::element::computed(move || {
5699                let (count, keys) = rows();
5700                let diff = match (&*last.borrow(), &keys) {
5701                    (Some(old), Some(new)) => ListDiff::new(old, new),
5702                    _ => None,
5703                };
5704                last.replace(keys.clone());
5705                if made.replace(true) {
5706                    move_rows(&cells, diff.as_ref(), count);
5707                    count_signal.set(count as usize);
5708                    patches.borrow_mut().push(super::views::Patch::Rows {
5709                        list: id,
5710                        binding: crate::element::Owner::current(),
5711                        count,
5712                        keys,
5713                    });
5714                } else {
5715                    count_signal.set(count as usize);
5716                    *slot.borrow_mut() = Some((count, keys));
5717                }
5718            });
5719            moves = Some(memo.node());
5720            first.take().expect("a memo runs when it is made")
5721        } else {
5722            let (count, keys) = crate::element::untracked(rows);
5723            // What the cells of a view (or a view's wrappers) read.
5724            {
5725                self.list_count(id, count as usize).set(count as usize);
5726            }
5727            (count, keys)
5728        };
5729        self.send_list_rows(id, before.as_ref(), count, keys.as_ref());
5730        if before.is_none()
5731            && let Some(command) = list.initial_scroll
5732        {
5733            let _ = self.apply_op(Op::Command { id, command });
5734        }
5735        let state = self.components.virtual_lists.get_mut(&id).expect("list");
5736        state.row = list.row;
5737        state.count = count;
5738        state.keys = keys;
5739        state.moves = moves;
5740        state.separator = list.separator;
5741        state.min_view = list.min_view_time;
5742        self.sync_virtual_cells(id, true);
5743    }
5744
5745    /// Sends list `id` its rows' changes from `before` (none: a new list):
5746    /// how the keys say rows came, went or moved, then the count.
5747    fn send_list_rows(
5748        &mut self,
5749        id: NodeId,
5750        before: Option<&Rows>,
5751        count: u32,
5752        keys: Option<&Rc<[u64]>>,
5753    ) {
5754        if let (Some((_, Some(old))), Some(new)) = (before, keys)
5755            && let Some(diff) = ListDiff::new(old, new)
5756        {
5757            let _ = self.apply_op(Op::SetProp {
5758                id,
5759                prop: Prop::ListDiff(Rc::new(diff)),
5760            });
5761        }
5762        if before.map(|(count, _)| *count) != Some(count) {
5763            let _ = self.apply_op(Op::SetProp {
5764                id,
5765                prop: Prop::Count(count),
5766            });
5767        }
5768    }
5769
5770    /// A view's list `id` has new rows (its bound count or keys changed):
5771    /// sent to the list. Its cells' bindings already follow their rows
5772    /// ([`move_rows`]); the core takes their indices, and the cells whose row
5773    /// went show nothing until the list shows another row in them.
5774    pub(super) fn set_list_rows(&mut self, id: NodeId, count: u32, keys: Option<Rc<[u64]>>) {
5775        let Some(state) = self.components.virtual_lists.get(&id) else {
5776            return;
5777        };
5778        let before = (state.count, state.keys.clone());
5779        self.send_list_rows(id, Some(&before), count, keys.as_ref());
5780        let state = self.components.virtual_lists.get_mut(&id).expect("list");
5781        state.count = count;
5782        state.keys = keys;
5783        self.sync_virtual_cells(id, false);
5784    }
5785
5786    fn sync_virtual_cells(&mut self, id: NodeId, rebuild: bool) {
5787        let key = self.key(id).expect("virtual list node");
5788        let slots = &self.nodes[key as usize].list.as_ref().expect("list").slots;
5789        let state = &self.components.virtual_lists[&id];
5790        for (slot, (&cell, &content)) in state.cells.iter().zip(&state.contents).enumerate() {
5791            for part in [cell, content].into_iter().filter(|&part| part != 0) {
5792                let Some(inst) = self.components.instances.get_mut(&part) else {
5793                    continue;
5794                };
5795                let remake = rebuild || !inst.cell_owner.is_some_and(|o| o.is_live());
5796                if let Inner::VirtualRow { index, .. } | Inner::Row { index, .. } = &mut inst.inner
5797                {
5798                    if remake {
5799                        // The content owner can die while the slot still has a row.
5800                        *index = slots[slot].requested.map_or(usize::MAX, |i| i as usize);
5801                    } else if let Some(position) = inst.row_index {
5802                        *index = position.get_untracked();
5803                    }
5804                }
5805                if remake && !inst.dirty {
5806                    inst.dirty = true;
5807                    self.components.dirty.push(part);
5808                }
5809            }
5810        }
5811    }
5812
5813    /// The row count the cells of list `list` read, made with `count` the
5814    /// first time.
5815    fn list_count(&mut self, list: NodeId, count: usize) -> crate::element::Signal<usize> {
5816        if let Some(&(_, signal)) = self.components.list_counts.get(&list) {
5817            return signal;
5818        }
5819        let made = crate::element::Owner::detached()
5820            .run(|| crate::element::create_root(|| crate::element::signal(count)));
5821        self.components.list_counts.insert(list, made);
5822        made.1
5823    }
5824
5825    /// List `list` goes: so do the count its cells read and its layout.
5826    fn forget_list_count(&mut self, list: NodeId) {
5827        if let Some((owner, _)) = self.components.list_counts.remove(&list) {
5828            owner.dispose();
5829        }
5830        self.components.list_layouts.remove(&list);
5831    }
5832
5833    /// Binds the cells of the components' own lists the last layout asked
5834    /// for (creating them as needed); false when there were none.
5835    pub(super) fn bind_virtual_lists(&mut self) -> bool {
5836        if self.components.virtual_lists.is_empty() {
5837            return false;
5838        }
5839        let _entered = self.components.runtime.enter();
5840        let mut binds = std::mem::take(&mut self.list_binds);
5841        let mut bound = false;
5842        binds.retain(|bind| {
5843            if !self.components.virtual_lists.contains_key(&bind.list) {
5844                return true;
5845            }
5846            for &(slot, index) in &bind.binds {
5847                self.bind_virtual_cell(bind.list, slot as usize, index as usize);
5848            }
5849            bound = true;
5850            false
5851        });
5852        self.list_binds = binds;
5853        bound
5854    }
5855
5856    fn bind_virtual_cell(&mut self, list: NodeId, slot: usize, index: usize) {
5857        let state = &self.components.virtual_lists[&list];
5858        let owner = state.owner;
5859        let cell = match state.cells.get(slot).copied().filter(|&c| c != 0) {
5860            Some(cell) => {
5861                let content = state.contents.get(slot).copied().filter(|&c| c != 0);
5862                for part in [Some(cell), content].into_iter().flatten() {
5863                    if let Some(inst) = self.components.instances.get_mut(&part) {
5864                        match &mut inst.inner {
5865                            Inner::VirtualRow { index: current, .. }
5866                            | Inner::Row { index: current, .. } => *current = index,
5867                            _ => {}
5868                        }
5869                        // A view's cell keeps its content: what reads its
5870                        // position follows.
5871                        if let Some(row) = inst.row_index
5872                            && inst.cell_owner.is_some_and(|o| o.is_live())
5873                        {
5874                            row.set(index);
5875                            continue;
5876                        }
5877                    }
5878                    self.components.mark(part);
5879                }
5880                cell
5881            }
5882            None => {
5883                let (items, place) = (state.items, state.place.clone());
5884                let cell = self.components.alloc();
5885                let _ = self.apply_op(Op::Create {
5886                    id: cell,
5887                    tag: Tag::Cell,
5888                });
5889                self.components.owners.insert(cell, owner);
5890                let _ = self.apply_op(Op::SetProp {
5891                    id: cell,
5892                    prop: Prop::Slot(crate::CellSlot::Item(slot as u32)),
5893                });
5894                let _ = self.apply_op(Op::Insert {
5895                    parent: list,
5896                    child: cell,
5897                    before: None,
5898                });
5899                let row = Inner::VirtualRow { list, index };
5900                let content = if items {
5901                    // The placing component's wrapper in the cell, around
5902                    // the row's own node (placed as a row's content is).
5903                    let content = self.components.alloc();
5904                    let _ = self.apply_op(Op::Create {
5905                        id: content,
5906                        tag: Tag::View,
5907                    });
5908                    self.components.owners.insert(content, owner);
5909                    let _ = self.apply_op(Op::Insert {
5910                        parent: cell,
5911                        child: content,
5912                        before: None,
5913                    });
5914                    let instance = Instance::new(row, None, Vec::new(), None);
5915                    self.components
5916                        .instances
5917                        .insert(content, Box::new(instance));
5918                    self.components.mark(content);
5919                    let place = place.unwrap_or_else(|| Rc::new(|row, _| row.into_element()));
5920                    // The wrapper is the placing component's.
5921                    let wrapper =
5922                        Instance::new(Inner::Row { place, index }, None, vec![content], None);
5923                    self.components.instances.insert(cell, Box::new(wrapper));
5924                    content
5925                } else {
5926                    let instance = Instance::new(row, None, Vec::new(), None);
5927                    self.components.instances.insert(cell, Box::new(instance));
5928                    0
5929                };
5930                let state = self.components.virtual_lists.get_mut(&list).expect("list");
5931                if state.cells.len() <= slot {
5932                    state.cells.resize(slot + 1, 0);
5933                    state.contents.resize(slot + 1, 0);
5934                }
5935                state.cells[slot] = cell;
5936                state.contents[slot] = content;
5937                self.components.mark(cell);
5938                cell
5939            }
5940        };
5941        let _ = self.apply_op(Op::SetProp {
5942            id: cell,
5943            prop: Prop::CellIndex(index as u32),
5944        });
5945    }
5946
5947    /// A component's own list reported its viewable rows: they are the
5948    /// owner's to handle now, or once they stayed so for the minimum view
5949    /// time (a change meanwhile starts the wait again).
5950    fn viewable_changed(&mut self, list: NodeId, payload: &EventPayload) {
5951        let executor = self.components.executor.clone();
5952        let Some(state) = self.components.virtual_lists.get_mut(&list) else {
5953            return;
5954        };
5955        state.latest = virtual_list::viewable_range(payload, "first", "last");
5956        match state.min_view {
5957            Some(delay) => {
5958                state.report = Some(crate::element::task::act_after(
5959                    &executor,
5960                    state.owner,
5961                    delay,
5962                    Action::ReportViewable(list),
5963                ));
5964            }
5965            None => self.report_viewable(list),
5966        }
5967    }
5968
5969    /// Hands list `list`'s owner the rows viewable now, unless they are the
5970    /// ones reported last.
5971    fn report_viewable(&mut self, list: NodeId) {
5972        let Some(state) = self.components.virtual_lists.get_mut(&list) else {
5973            return;
5974        };
5975        state.report = None;
5976        if state.latest == state.reported {
5977            return;
5978        }
5979        let payload = virtual_list::viewable_payload(state.latest, state.reported);
5980        state.reported = state.latest;
5981        let owner = state.owner;
5982        self.handle(owner, list, EventKind::ViewableItemsChange, &payload);
5983    }
5984
5985    fn release_id(&mut self, id: NodeId) {
5986        self.components.release_generation = self.components.release_generation.wrapping_add(1);
5987        if let Some(host) = self.components.owners.remove(&id) {
5988            // Cells can replace/empty their static root outside a region's
5989            // matching pass. Their released bindings need the same sweep
5990            // even if the next region only populates new nodes.
5991            self.components.released_hosts.insert(host);
5992        }
5993        self.forget_node_extras(id);
5994        // A root component's host is its view's: only the name goes.
5995        if self.is_alias(id) {
5996            self.unalias(id);
5997            return;
5998        }
5999        // A fill's node in a holder: the slot's props follow what is left.
6000        let holder = if self.components.fill_holders.is_empty() {
6001            None
6002        } else {
6003            self.key(id)
6004                .ok()
6005                .map(|k| self.nodes[k as usize].parent)
6006                .filter(|&p| p != NO_KEY)
6007                .map(|p| self.nodes[p as usize].id)
6008                .filter(|p| self.components.fill_holders.contains(p))
6009        };
6010        let _ = self.apply_op(Op::Release { id });
6011        if let Some(holder) = holder {
6012            self.retarget_slot(holder, None);
6013        }
6014    }
6015
6016    /// Frees an expanded element and what it rendered (a slot's node is
6017    /// JS's: it only leaves the tree).
6018    pub(super) fn release_expanded(&mut self, e: Expanded) {
6019        // Slot/JS nodes can lose this view's part without being deleted or
6020        // leaving `owners`, so count expanded releases as well as raw IDs.
6021        self.components.release_generation = self.components.release_generation.wrapping_add(1);
6022        match e.part {
6023            Part::Slot => {
6024                self.drop_slot_target(e.id);
6025                self.detach_id(e.id);
6026                return;
6027            }
6028            // The JS children are placed (or detached) by the view, and
6029            // what fills a slot by the view that fills it.
6030            Part::Children | Part::Filled(_) => return,
6031            // Its nodes are its children's.
6032            Part::Fill(_) | Part::Tooltip => {
6033                for c in e.children {
6034                    self.release_expanded(c);
6035                }
6036                return;
6037            }
6038            // A JS child leaves the wrapper being released.
6039            Part::JsChild => {
6040                self.detach_id(e.id);
6041                return;
6042            }
6043            Part::Raw => {
6044                self.release_id(e.id);
6045                return;
6046            }
6047            // Its content is this view's, released below: deleting it
6048            // detaches it.
6049            Part::Component(_) => {
6050                let content: Vec<NodeId> = e.children.iter().flat_map(|c| self.placed(c)).collect();
6051                self.release_component(e.id, &content);
6052            }
6053            // Its nodes are the region's.
6054            Part::Region(region) => {
6055                self.release_region(region);
6056                return;
6057            }
6058            Part::VirtualList => self.release_virtual_list(e.id),
6059            // A fill's holder: its element gets its own props back.
6060            Part::Node => {
6061                if !self.components.fill_holders.is_empty()
6062                    && self.components.fill_holders.remove(&e.id)
6063                {
6064                    self.drop_slot_target(e.id);
6065                }
6066            }
6067        }
6068        if let Some(r) = e.attrs.rare.as_ref().and_then(|r| r.element_ref.as_ref()) {
6069            r.detach(e.id);
6070        }
6071        for c in e.children {
6072            self.release_expanded(c);
6073        }
6074        if let Some((_, raw)) = e.text {
6075            self.release_id(raw);
6076        }
6077        self.release_id(e.id);
6078    }
6079
6080    /// Frees what a component made (not its host nor its JS children,
6081    /// which leave its view).
6082    pub(super) fn release_instance(&mut self, host: NodeId) {
6083        self.release_component(host, &[]);
6084    }
6085
6086    /// [`Self::release_instance`], but of its JS children and slots, those
6087    /// in `content` are released right after (a view's content of a nested
6088    /// component: deleting them detaches them); the others leave its view
6089    /// natively (they stay: JS's, or passed on by the view).
6090    fn release_component(&mut self, host: NodeId, content: &[NodeId]) {
6091        let Some(mut inst) = self.components.instances.remove(&host) else {
6092            return;
6093        };
6094        // The app's element in a slot: the holder takes the slot's props.
6095        self.target_released(host);
6096        if self
6097            .components
6098            .parked_methods
6099            .iter()
6100            .any(|(h, ..)| *h == host)
6101        {
6102            let (gone, kept) = std::mem::take(&mut self.components.parked_methods)
6103                .into_iter()
6104                .partition(|(h, ..)| *h == host);
6105            self.components.parked_methods = kept;
6106            for (_, call, method) in gone {
6107                drop_caught(method);
6108                self.settle(
6109                    call,
6110                    Err(format!("node {host} hosts no Rust component").into()),
6111                );
6112            }
6113        }
6114        // Its root's (a render or classes of the app's) on the host.
6115        self.forget_node_extras(host);
6116        if let Inner::Component(inner) = &mut inst.inner {
6117            if let Err(message) = caught(|| inner.cleanup()) {
6118                log::error!(target: "js", "{} failed in its cleanup: {message}", inner.name());
6119            }
6120            self.apply_actions();
6121        }
6122        self.release_regions(host);
6123        self.components.runtime.forget_host(host);
6124        if let Some(owner) = inst.cell_owner.take() {
6125            owner.dispose();
6126        }
6127        for &child in &inst.js_children {
6128            if !content.contains(&child) {
6129                self.detach_id(child);
6130            }
6131        }
6132        for (_, node) in inst.slots {
6133            self.drop_slot_target(node);
6134            self.components.slot_hosts.remove(&node);
6135            if !content.contains(&node) {
6136                self.detach_id(node);
6137            }
6138        }
6139        if let Some(root) = inst.root {
6140            // The component its root is, with its alias.
6141            if matches!(root.part, Part::Component(_)) {
6142                self.release_expanded(root);
6143                return;
6144            }
6145            let node = self.native_id(host);
6146            if let Some(r) = root
6147                .attrs
6148                .rare
6149                .as_ref()
6150                .and_then(|r| r.element_ref.as_ref())
6151            {
6152                r.detach(node);
6153            }
6154            if root.part == Part::VirtualList {
6155                self.release_virtual_list(node);
6156            }
6157            if let Some((_, raw)) = root.text {
6158                self.release_id(raw);
6159            }
6160            for c in root.children {
6161                self.release_expanded(c);
6162            }
6163        }
6164    }
6165
6166    /// Releases the component's own list `id`: its cells, and what knew of
6167    /// it.
6168    fn release_virtual_list(&mut self, id: NodeId) {
6169        if let Some(state) = self.components.virtual_lists.remove(&id) {
6170            let parts = state.contents.into_iter().chain(state.cells);
6171            for part in parts.filter(|&c| c != 0) {
6172                self.release_instance(part);
6173                self.release_id(part);
6174            }
6175        }
6176        // The rows of another component's `Items` prop: no longer its slot.
6177        if self.components.slot_names.remove(&id).is_some() {
6178            self.unslot(id);
6179        }
6180        self.components.lists.remove(&id);
6181        self.forget_list_count(id);
6182    }
6183
6184    /// A native event on node `id`: true when a component handled it (its
6185    /// own parts' events never reach JS, which does not know them).
6186    pub fn component_event(&mut self, id: NodeId, kind: EventKind, payload: &EventPayload) -> bool {
6187        let _entered = self.components.runtime.enter();
6188        // A Rust text block's final layout, for its `on_text_layout`.
6189        let _geometry = (kind == EventKind::TextLayout)
6190            .then(|| self.geometries.remove(&id))
6191            .flatten()
6192            .map(crate::text::GeometryScope::enter);
6193        let handled = self.dispatch_event(id, kind, payload);
6194        self.flush_component_emits();
6195        handled
6196    }
6197
6198    /// Whether node `id` has a listener for `event` (a JS handler or a Rust
6199    /// component's), as the platform sees it mounted. The engine skips
6200    /// nodes without one when it fans a key notification out.
6201    #[doc(hidden)]
6202    pub fn listens(&self, id: NodeId, event: EventKind) -> bool {
6203        self.key(id)
6204            .is_ok_and(|key| self.nodes[key as usize].mounted_events().contains(event))
6205    }
6206
6207    /// Whether `id` or an enabled logical ancestor up to its window root
6208    /// hears a key transition (`KeyDown` or `KeyUp`) or has a capture rule
6209    /// that is not `None`. Follows the logical tree (`node.parent`), so an
6210    /// overlay's content finds the views it is logically in even where a
6211    /// backend mounts it elsewhere. No allocation: a walk per transition.
6212    #[doc(hidden)]
6213    pub fn key_interest(&self, id: NodeId) -> bool {
6214        let Ok(mut key) = self.key(id).map(|key| self.key_start(key)) else {
6215            return false;
6216        };
6217        let window = self.key_window(key);
6218        loop {
6219            let node = &self.nodes[key as usize];
6220            let disabled = node
6221                .props
6222                .as_ref()
6223                .is_some_and(|p| p.accessibility.state.disabled);
6224            if !disabled {
6225                let events = node.mounted_events();
6226                if events.contains(EventKind::KeyDown) || events.contains(EventKind::KeyUp) {
6227                    return true;
6228                }
6229                if node
6230                    .props
6231                    .as_ref()
6232                    .is_some_and(|p| !p.key_capture.is_none())
6233                {
6234                    return true;
6235                }
6236            }
6237            if node.id == window || node.parent == NO_KEY {
6238                return false;
6239            }
6240            key = node.parent;
6241        }
6242    }
6243
6244    /// The views a key notification on `id` reaches, in order: `id`, then
6245    /// each enabled ancestor, up to and including the root of `id`'s window.
6246    /// The engine notifies every one of them (Rust and JS listeners alike)
6247    /// from one platform event; a native window is a keyboard boundary even
6248    /// when its declarative root remains in another window's logical tree.
6249    /// A disabled view hears nothing, and its enabled ancestors still do.
6250    #[doc(hidden)]
6251    pub fn key_path(&self, id: NodeId, out: &mut Vec<NodeId>) {
6252        out.clear();
6253        let Ok(mut key) = self.key(id).map(|key| self.key_start(key)) else {
6254            return;
6255        };
6256        let window = self.key_window(key);
6257        loop {
6258            let node = &self.nodes[key as usize];
6259            let disabled = node
6260                .props
6261                .as_ref()
6262                .is_some_and(|p| p.accessibility.state.disabled);
6263            if !disabled {
6264                out.push(node.id);
6265            }
6266            if node.id == window || node.parent == NO_KEY {
6267                return;
6268            }
6269            key = node.parent;
6270        }
6271    }
6272
6273    /// Whether `id` or an enabled ancestor within its window captures the
6274    /// transition whose canonical shortcut stroke is `keystroke` under its
6275    /// mounted [`crate::KeyCapture`] rule (`captureKeys`). The platform
6276    /// decides before native defaults from the stroke its own shortcut
6277    /// vocabulary names, never from [`crate::KeyEvent`]'s `key` or `code`;
6278    /// `None` (a key no shortcut names) is captured only by
6279    /// [`crate::KeyCapture::All`]. A focused native text input keeps the
6280    /// keys that edit it: nothing captures them.
6281    #[doc(hidden)]
6282    pub fn key_captured(&self, id: NodeId, keystroke: Option<&crate::keymap::Keystroke>) -> bool {
6283        let Ok(mut key) = self.key(id).map(|key| self.key_start(key)) else {
6284            return false;
6285        };
6286        // A native text input owns the keys that edit it: an ancestor's
6287        // capture never intercepts its typing, caret or editing commands.
6288        if self.nodes[key as usize].kind == Kind::Input {
6289            return false;
6290        }
6291        let window = self.key_window(key);
6292        loop {
6293            let node = &self.nodes[key as usize];
6294            let disabled = node
6295                .props
6296                .as_ref()
6297                .is_some_and(|p| p.accessibility.state.disabled);
6298            if !disabled
6299                && node
6300                    .props
6301                    .as_ref()
6302                    .is_some_and(|p| p.key_capture.captures_key(keystroke))
6303            {
6304                return true;
6305            }
6306            if node.id == window || node.parent == NO_KEY {
6307                return false;
6308            }
6309            key = node.parent;
6310        }
6311    }
6312
6313    /// Where a key transition reported at `key` starts. A backend with
6314    /// nothing focused in a window reports at the window's root (`ROOT_ID`,
6315    /// or a dialog window's root): the app's views are not its ancestors,
6316    /// so the transition starts at the view mounted there (the app's mount
6317    /// root, or the dialog's content) and bubbles from it, as a browser
6318    /// reports it at `document.body` (#2362). Any other node starts at
6319    /// itself.
6320    pub(super) fn key_start(&self, key: Key) -> Key {
6321        let node = &self.nodes[key as usize];
6322        if node.id != crate::ROOT_ID
6323            && (node.kind != Kind::Modal || self.key_window(key) != node.id)
6324        {
6325            return key;
6326        }
6327        node.children
6328            .iter()
6329            .copied()
6330            .find(|&child| !matches!(self.nodes[child as usize].kind, Kind::Overlay | Kind::Modal))
6331            .unwrap_or(key)
6332    }
6333
6334    /// A window's staged keyboard target follows its logical children.
6335    pub(super) fn key_content_changed(&mut self, parent: Key) {
6336        let node = &self.nodes[parent as usize];
6337        if node.id == crate::ROOT_ID
6338            || (node.kind == Kind::Modal && self.key_window(parent) == node.id)
6339        {
6340            self.key_ancestry_dirty = true;
6341        }
6342    }
6343
6344    /// The root of the window `key` is in, `key` itself when it is one.
6345    pub(super) fn key_window(&self, key: Key) -> NodeId {
6346        let node = &self.nodes[key as usize];
6347        if node.kind == Kind::Modal && self.window_ids.values().any(|(root, _)| *root == node.id) {
6348            node.id
6349        } else {
6350            self.window_of(key)
6351        }
6352    }
6353
6354    fn flush_component_emits(&mut self) {
6355        // What views' listeners emitted reaches its listeners (JS hears it
6356        // in this turn).
6357        loop {
6358            let emits = self.components.runtime.take_emits();
6359            if emits.is_empty() {
6360                break;
6361            }
6362            for (host, event) in emits {
6363                self.route_emit(host, event);
6364            }
6365        }
6366    }
6367
6368    /// Initializes one newly installed layout listener of a kept node.
6369    /// The engine delivers this in event order, without notifying the
6370    /// node's retained listeners or its JS handlers.
6371    #[doc(hidden)]
6372    pub fn component_layout(
6373        &mut self,
6374        host: NodeId,
6375        id: NodeId,
6376        listener: &Listener<EventPayload>,
6377        frame: crate::Bounds<Points>,
6378    ) {
6379        let _entered = self.components.runtime.enter();
6380        let installed = self.components.instances.get(&host).is_some_and(|inst| {
6381            inst.handlers
6382                .of(id)
6383                .iter()
6384                .any(|(kind, current)| *kind == EventKind::Layout && current.ptr_eq(listener))
6385        });
6386        if installed {
6387            self.run_listener(host, listener, &EventPayload::Layout(frame));
6388            self.flush_component_emits();
6389        }
6390    }
6391
6392    fn dispatch_event(&mut self, id: NodeId, kind: EventKind, payload: &EventPayload) -> bool {
6393        // Before a cancelled press's release is dropped: it still ends the
6394        // span's press.
6395        self.span_state(id, kind);
6396        // A cancelled press's release reaches no one, JS included.
6397        if self.drop_cancelled_press(id, kind, payload) {
6398            return true;
6399        }
6400        // Touches come on the root with the listening nodes around each
6401        // finger: the components hear theirs, JS its own.
6402        if kind == EventKind::Touch && id == ROOT_ID {
6403            if let EventPayload::Touch(touch) = payload {
6404                self.overlay_touches(touch);
6405                self.touches(payload, touch);
6406            }
6407            return false;
6408        }
6409        // Hints follow the pointer on their anchors, whoever else listens.
6410        if matches!(kind, EventKind::MouseEnter | EventKind::MouseLeave) {
6411            let at = match payload {
6412                EventPayload::Mouse(mouse) => Some(mouse.page_position),
6413                _ => None,
6414            };
6415            self.overlay_hover(id, kind, at);
6416        }
6417        // A download event's listener gets a handle bound to the native
6418        // web view node the platform reported, not the component host its
6419        // handlers were registered on: only this dispatch can make one.
6420        let _target = matches!(kind, EventKind::DownloadPending | EventKind::Download)
6421            .then(|| crate::element::download_target(id, Rc::downgrade(&self.components.executor)));
6422        if self.platform_event(id, kind, payload) {
6423            return true;
6424        }
6425        if self.is_host(id) {
6426            // The component whose view makes the host's node handles them,
6427            // after the one whose slot's props it takes.
6428            let base = self.base_of(id);
6429            if let Some(slot) = self.adopted_host(base) {
6430                self.handle(slot, base, kind, payload);
6431            }
6432            let own = self.handle(base, base, kind, payload);
6433            // A context menu has one listener: a component showing its own
6434            // keeps it.
6435            if own && kind == EventKind::ContextMenu {
6436                return true;
6437            }
6438            let given = self.handle_given(base, kind, payload);
6439            // JS listening on the host hears it too.
6440            return (own || given) && !self.js_listens(base, kind);
6441        }
6442        // A component's own list reports its viewable rows as they settle.
6443        if kind == EventKind::ViewableItemsChange && self.components.virtual_lists.contains_key(&id)
6444        {
6445            self.viewable_changed(id, payload);
6446            return true;
6447        }
6448        // A slot's node: the component it is a slot of handles its events,
6449        // then whoever made it: the component whose view has it, or JS (the
6450        // app's list of an `Items` prop has the app's handlers). So does the
6451        // app's element that takes the slot's props, then JS.
6452        let slot_of = self
6453            .components
6454            .slot_hosts
6455            .get(&id)
6456            .copied()
6457            .or_else(|| self.adopted_host(id));
6458        let owner = self.components.owners.get(&id).copied();
6459        if let Some(host) = slot_of {
6460            self.handle(host, id, kind, payload);
6461        }
6462        if let Some(host) = owner
6463            && Some(host) != slot_of
6464        {
6465            self.handle(host, id, kind, payload);
6466        }
6467        // The core's nodes (odd ids) are the components': JS does not know
6468        // them.
6469        (slot_of.is_some() || owner.is_some()) && id % 2 == 1
6470    }
6471
6472    /// The host of the component whose view has node `id` (for a host, the
6473    /// component whose view makes its node: itself, or its root
6474    /// component's).
6475    pub(super) fn host_of(&self, id: NodeId) -> Option<NodeId> {
6476        if self.is_host(id) {
6477            Some(self.base_of(id))
6478        } else {
6479            self.components.owners.get(&id).copied()
6480        }
6481    }
6482
6483    /// Runs `host`'s component's handlers of `kind` on its node `id`, in
6484    /// the order the element was given them; false when it has none.
6485    fn handle(
6486        &mut self,
6487        host: NodeId,
6488        id: NodeId,
6489        kind: EventKind,
6490        payload: &EventPayload,
6491    ) -> bool {
6492        let id = self.base_of(id);
6493        let mut handled = false;
6494        let mut from = 0;
6495        while let Some((at, listener)) = self.next_handler(host, id, kind, from) {
6496            from = at + 1;
6497            // A listener may release the component: the rest go with it.
6498            if !self.run_listener(host, &listener, payload) {
6499                break;
6500            }
6501            handled = true;
6502        }
6503        handled
6504    }
6505
6506    /// The first of `host`'s component's handlers of `kind` on its node `id`
6507    /// at or after index `from`, with its index: a dispatch walks them in
6508    /// order (an element given several listeners of one event calls them
6509    /// all) with no list of its own. The handlers stay as they are while it
6510    /// does: a view's regions change them when they are reconciled, in the
6511    /// commit, not as listeners run.
6512    pub(super) fn next_handler(
6513        &self,
6514        host: NodeId,
6515        id: NodeId,
6516        kind: EventKind,
6517        from: usize,
6518    ) -> Option<(usize, Listener<EventPayload>)> {
6519        let id = self.base_of(id);
6520        let inst = self.components.instances.get(&host)?;
6521        let handlers = inst.handlers.of(id);
6522        #[cfg(test)]
6523        self.components
6524            .handler_visits
6525            .set(self.components.handler_visits.get() + handlers.len().saturating_sub(from));
6526        handlers
6527            .iter()
6528            .enumerate()
6529            .skip(from)
6530            .find(|(_, (k, _))| *k == kind)
6531            .map(|(at, (_, l))| (at, l.clone()))
6532    }
6533
6534    /// The part of `host`'s node `id` in the touch responder.
6535    pub(super) fn responder_el(&self, host: NodeId, id: NodeId) -> Option<Rc<ResponderEl>> {
6536        let id = self.base_of(id);
6537        self.components
6538            .instances
6539            .get(&host)?
6540            .responders
6541            .iter()
6542            .find(|(n, _)| *n == id)
6543            .map(|(_, r)| r.clone())
6544    }
6545
6546    /// Runs `listener` of a node of `host`'s view (or of a list row of it);
6547    /// false when that component is gone.
6548    pub(super) fn run_listener<E: ?Sized + 'static>(
6549        &mut self,
6550        host: NodeId,
6551        listener: &Listener<E>,
6552        event: &E,
6553    ) -> bool {
6554        let Some(owner) = self.state_owner(host) else {
6555            return false;
6556        };
6557        if let Err(message) = caught(|| listener.call(event)) {
6558            self.component_failed(owner, message);
6559        }
6560        self.apply_actions();
6561        true
6562    }
6563
6564    /// The component whose state `host`'s handlers change: its own, or for
6565    /// a list row the component's whose list it is.
6566    pub(super) fn state_owner(&self, host: NodeId) -> Option<NodeId> {
6567        match &self.components.instances.get(&host)?.inner {
6568            Inner::Component(_) => Some(host),
6569            Inner::VirtualRow { list, .. } => {
6570                self.components.virtual_lists.get(list).map(|s| s.owner)
6571            }
6572            Inner::Row { .. } => self
6573                .list_of(host)
6574                .and_then(|l| self.components.slot_hosts.get(&l))
6575                .copied(),
6576            Inner::Missing => None,
6577        }
6578    }
6579
6580    /// The code of `host`'s component panicked: the nearest error boundary
6581    /// above it shows it ([`crate::element::catch_error`]); else it is reported.
6582    pub(super) fn component_failed(&mut self, host: NodeId, message: String) {
6583        let component = match self.components.instances.get(&host).map(|i| &i.inner) {
6584            Some(Inner::Component(inner)) => inner.name(),
6585            _ => "a list row",
6586        };
6587        let error = ComponentError { component, message };
6588        // The nearest error boundary of a view above it.
6589        let owner = self
6590            .components
6591            .instances
6592            .get(&host)
6593            .and_then(|inst| match &inst.inner {
6594                Inner::Component(inner) => Some(inner.failure_owner()),
6595                _ => inst.cell_owner,
6596            });
6597        let _entered = self.components.runtime.enter();
6598        match owner.and_then(crate::element::reactive::boundary_of) {
6599            Some(boundary) => boundary.set(Some(error)),
6600            None => log::error!(target: "js", "{error}"),
6601        }
6602    }
6603
6604    /// The list cell `cell` is in.
6605    fn list_of(&self, cell: NodeId) -> Option<NodeId> {
6606        let key = self.key(cell).ok()?;
6607        let parent = self.nodes[key as usize].parent;
6608        (parent != NO_KEY).then(|| self.nodes[parent as usize].id)
6609    }
6610
6611    /// Reads (`enabled` `None`) or changes whether the app launches at
6612    /// login: on the backend's thread when the runner gave the core one,
6613    /// the answer (on or not) delivered in a task here; without one the app
6614    /// does not launch at login, and a change fails.
6615    fn login_item_action(
6616        &mut self,
6617        enabled: Option<bool>,
6618        answer: crate::element::AnswerSlot<Result<bool, crate::desktop::LaunchAtLoginError>>,
6619    ) {
6620        use crate::desktop::{LaunchAtLoginError, LoginItemStatus};
6621        // Launching at login acts on the application as a whole: an app
6622        // declaring capabilities needs `application` to change it, and is
6623        // told it does not launch at login otherwise.
6624        if !self.access.allows_application() {
6625            answer.borrow_mut().deliver(match enabled {
6626                None => Ok(false),
6627                Some(_) => Err(LaunchAtLoginError::Denied),
6628            });
6629            return;
6630        }
6631        let Some(items) = self.login_item.as_mut() else {
6632            answer.borrow_mut().deliver(match enabled {
6633                None => Ok(false),
6634                Some(_) => Err(LaunchAtLoginError::Unavailable),
6635            });
6636            return;
6637        };
6638        let result = items.call(enabled);
6639        crate::element::task::spawn_raw(
6640            &self.components.executor,
6641            crate::ROOT_ID,
6642            Box::pin(async move {
6643                let result = match result.await {
6644                    // Nothing to change where the platform has no login
6645                    // item for the app (a sandboxed Linux app).
6646                    Ok(LoginItemStatus::Unavailable) if enabled.is_some() => {
6647                        Err(LaunchAtLoginError::Unavailable)
6648                    }
6649                    Ok(status) => Ok(status == LoginItemStatus::Enabled),
6650                    Err(error) => Err(LaunchAtLoginError::System(error)),
6651                };
6652                answer.borrow_mut().deliver(result);
6653            }),
6654        );
6655    }
6656
6657    /// Applies what the app asks about notifications: granted and where
6658    /// the platform shows them, the platform answers with
6659    /// [`EventKind::Notification`]; otherwise the answer is given here.
6660    fn notification_action(&mut self, action: crate::element::NotificationAction) {
6661        use crate::{
6662            element::NotificationAction,
6663            notifications::{NotificationCommand, NotificationPermission},
6664        };
6665        let allowed = self.access.allows_notifications();
6666        let available = allowed && self.components.environment.notifications;
6667        let command = match action {
6668            NotificationAction::Permission { ask, answer } => {
6669                if !available {
6670                    answer
6671                        .borrow_mut()
6672                        .deliver(NotificationPermission::Unavailable);
6673                    return;
6674                }
6675                let state = &mut self.components.notifications;
6676                let id = state.next;
6677                state.next = id.wrapping_add(1);
6678                state.permissions.insert(id, answer);
6679                NotificationCommand::Permission { id, ask }
6680            }
6681            NotificationAction::Show {
6682                notification,
6683                answer,
6684            } => {
6685                if !available {
6686                    answer.borrow_mut().deliver(false);
6687                    return;
6688                }
6689                let state = &mut self.components.notifications;
6690                let id = state.next;
6691                state.next = id.wrapping_add(1);
6692                state.shows.insert(id, answer);
6693                NotificationCommand::Show { id, notification }
6694            }
6695            NotificationAction::Close(id) => {
6696                if !available {
6697                    return;
6698                }
6699                NotificationCommand::Close(id)
6700            }
6701            NotificationAction::CloseAll => {
6702                if !available {
6703                    return;
6704                }
6705                NotificationCommand::CloseAll
6706            }
6707            NotificationAction::SetBadge(count) => {
6708                if !allowed {
6709                    return;
6710                }
6711                NotificationCommand::SetBadge(count)
6712            }
6713            NotificationAction::NextPress(answer) => {
6714                let state = &mut self.components.notifications;
6715                if let Some(pressed) = state.presses.pop_front() {
6716                    answer.borrow_mut().deliver(pressed);
6717                    return;
6718                }
6719                state.next_press = Some(answer);
6720                if !available || state.listening {
6721                    return;
6722                }
6723                state.listening = true;
6724                NotificationCommand::Listen
6725            }
6726        };
6727        let _ = self.apply_op(Op::Command {
6728            id: crate::ROOT_ID,
6729            command: Command::Notification(command),
6730        });
6731    }
6732
6733    /// The app's address, which the engine shares with every VM's
6734    /// `System` (`UrlScheme.url()` reads it there).
6735    #[doc(hidden)]
6736    pub fn app_url_cell(&self) -> crate::url_scheme::AppUrlCell {
6737        self.components.url_schemes.address.clone()
6738    }
6739
6740    /// Hands `url`, a link the system gave the app, to the listener, or
6741    /// keeps it for the next; drops it when the app does not claim it.
6742    /// `page`: the address of the page the app is (the web), which needs
6743    /// no scheme of the app's; `quiet` only takes it as the address;
6744    /// `change`, an address the app moved to without making the move,
6745    /// goes to the change listener instead of `open`.
6746    fn url_scheme(
6747        &mut self,
6748        url: String,
6749        page: bool,
6750        quiet: bool,
6751        change: Option<crate::url_scheme::AppUrlChangeReason>,
6752    ) {
6753        let links = &mut self.components.url_schemes;
6754        // A file the system opened the app with (nsh.json `fileTypes`): the
6755        // platforms report it as a `file://` URL, the core hands it to the
6756        // app as a file ([`crate::file_type`]), never as a link.
6757        if !page && change.is_none() && crate::file_type::is_file_url(&url) {
6758            if !links
6759                .links
6760                .schemes()
6761                .iter()
6762                .any(|s| s == crate::file_type::FILE_SCHEME)
6763            {
6764                log::warn!("file dropped: the app declares no file types (nsh.json `fileTypes`)");
6765                return;
6766            }
6767            let Some(path) = crate::file_type::file_path(&url) else {
6768                log::warn!("file dropped: {url} is not a local file");
6769                return;
6770            };
6771            let files = &mut self.components.open_files;
6772            if let Some(answer) = files.next.take() {
6773                answer.borrow_mut().deliver(vec![path]);
6774                return;
6775            }
6776            if files.pending.len() == crate::file_type::MAX_PENDING {
6777                log::warn!(
6778                    "file dropped: {} came while nothing listened",
6779                    crate::file_type::MAX_PENDING
6780                );
6781                files.pending.pop_front();
6782            }
6783            files.pending.push_back(path);
6784            return;
6785        }
6786        let checked = if page {
6787            crate::url_scheme::check_page_url(&url)
6788        } else {
6789            links.links.check(&url)
6790        };
6791        if let Err(dropped) = checked {
6792            log::warn!("link dropped: {dropped}");
6793            return;
6794        }
6795        let links = &mut self.components.url_schemes;
6796        // A link a wait for its scheme takes is that wait's alone (a sign-in
6797        // session's callback): no listener of the app's hears it, and it
6798        // does not become the app's address.
6799        if !quiet && change.is_none() {
6800            let scheme = url.split_once(':').map_or("", |(scheme, _)| scheme);
6801            links
6802                .next_of_scheme
6803                .retain(|(_, answer)| crate::element::task::awaited(answer));
6804            if let Some(at) = links
6805                .next_of_scheme
6806                .iter()
6807                .position(|(waited, _)| waited.eq_ignore_ascii_case(scheme))
6808            {
6809                let (_, answer) = links.next_of_scheme.remove(at);
6810                answer.borrow_mut().deliver(url);
6811                return;
6812            }
6813        }
6814        links.address.set(url.clone());
6815        if quiet {
6816            return;
6817        }
6818        if let Some(reason) = change {
6819            if !links.hears_changes {
6820                return;
6821            }
6822            let change = crate::url_scheme::AppUrlChange { url, reason };
6823            if let Some(answer) = links.next_change.take() {
6824                answer.borrow_mut().deliver(change);
6825                return;
6826            }
6827            if links.changes.len() == crate::url_scheme::MAX_PENDING {
6828                links.changes.pop_front();
6829            }
6830            links.changes.push_back(change);
6831            return;
6832        }
6833        let executor = &self.components.executor;
6834        links.open(url, |task| executor.has_task(task));
6835    }
6836
6837    /// The schemes the app claims (`nsh.json` `schemes`,
6838    /// [`crate::url_scheme`]), from the app's own resources: the links the
6839    /// platform reports of other schemes are dropped. None by default.
6840    /// [`Core::set_app_links`] sets them with the app's web links.
6841    pub fn set_url_schemes(&mut self, schemes: impl IntoIterator<Item = impl Into<String>>) {
6842        self.components.url_schemes.links.set_schemes(schemes);
6843    }
6844
6845    /// The links the app claims (`nsh.json` `schemes` and `links`,
6846    /// [`crate::url_scheme::AppLinks`]), from the app's own resources: the
6847    /// links the platform reports that are none of them (another scheme, an
6848    /// `https` link of another host or path) are dropped. None by default.
6849    pub fn set_app_links(&mut self, links: crate::url_scheme::AppLinks) {
6850        self.components.url_schemes.links = links;
6851    }
6852
6853    /// Answers what waits for the platform's [`EventKind::Notification`].
6854    fn notification_event(&mut self, payload: &EventPayload) {
6855        use crate::notifications::{NotificationEvent as Field, NotificationPermission};
6856        let EventPayload::Map(entries) = payload else {
6857            return;
6858        };
6859        let state = &mut self.components.notifications;
6860        let id = entries.iter().find_map(|(k, v)| match v {
6861            crate::PayloadValue::Number(n) if *k == Field::ID => Some(*n as u32),
6862            _ => None,
6863        });
6864        for (key, value) in entries {
6865            match (*key, value) {
6866                (Field::PERMISSION, crate::PayloadValue::Str(name)) => {
6867                    if let Some(answer) = id.and_then(|id| state.permissions.remove(&id)) {
6868                        let permission = NotificationPermission::from_name(name)
6869                            .unwrap_or(NotificationPermission::Unavailable);
6870                        answer.borrow_mut().deliver(permission);
6871                    }
6872                }
6873                (Field::SHOWN, crate::PayloadValue::Bool(shown)) => {
6874                    if let Some(answer) = id.and_then(|id| state.shows.remove(&id)) {
6875                        answer.borrow_mut().deliver(*shown);
6876                    }
6877                }
6878                (Field::PRESSED, crate::PayloadValue::Str(pressed)) => {
6879                    match state.next_press.take() {
6880                        Some(answer) => answer.borrow_mut().deliver(pressed.clone()),
6881                        None => state.presses.push_back(pressed.clone()),
6882                    }
6883                }
6884                _ => {}
6885            }
6886        }
6887    }
6888
6889    /// Applies a sound's or a player's request: through the embedding
6890    /// app's audio stack when it gave one, else as commands on the root the
6891    /// platform answers with [`EventKind::Audio`].
6892    fn audio_action(&mut self, action: crate::element::AudioAction) {
6893        use crate::{
6894            audio::{AudioCommand, AudioError, AudioEvent},
6895            element::AudioAction,
6896        };
6897        let (command, sink) = match action {
6898            AudioAction::Available(answer) => {
6899                let available = match &self.audio {
6900                    Some(backend) => backend.available(),
6901                    None => self.components.environment.audio,
6902                };
6903                answer.borrow_mut().deliver(available);
6904                return;
6905            }
6906            AudioAction::Open { mut command, sink } => {
6907                debug_assert!(matches!(
6908                    command,
6909                    AudioCommand::Load { .. }
6910                        | AudioCommand::LoadUrl { .. }
6911                        | AudioCommand::Open { .. }
6912                ));
6913                let failed = |error, message: &str| AudioEvent::Failed {
6914                    error,
6915                    message: message.into(),
6916                };
6917                if !self.access.allows_audio() {
6918                    sink.send(failed(AudioError::NotAllowed, "sound is not granted"));
6919                    sink.close();
6920                    self.deny(
6921                        "sound is not granted: add `\"audio\": true` to capabilities in nsh.json"
6922                            .into(),
6923                    );
6924                    return;
6925                }
6926                // A sound loads what the check granted (`Access::media_url`).
6927                if let AudioCommand::Open { src, .. } | AudioCommand::LoadUrl { url: src, .. } =
6928                    &mut command
6929                {
6930                    match self.media_source(src) {
6931                        Some(granted) => {
6932                            if let Some(url) = granted {
6933                                *src = url.to_string();
6934                            }
6935                        }
6936                        None => {
6937                            let base = self.base_url.as_deref();
6938                            let capability = crate::access::media_capability(src, base);
6939                            let advice = crate::access::media_grant_advice(src, base);
6940                            // Worded without the app's text: the player's
6941                            // error names the capability from it.
6942                            sink.send(failed(
6943                                AudioError::NotAllowed,
6944                                &format!("{}{capability}", super::SOURCE_NOT_GRANTED),
6945                            ));
6946                            sink.close();
6947                            self.deny(format!(
6948                                "`{src}` is not granted by capabilities.{capability}: {advice}"
6949                            ));
6950                            return;
6951                        }
6952                    }
6953                }
6954                if self.audio.is_none() && !self.components.environment.audio {
6955                    sink.send(failed(AudioError::Unavailable, "nothing plays sound here"));
6956                    sink.close();
6957                    return;
6958                }
6959                self.components.audio.insert(command.id(), sink.clone());
6960                (command, sink)
6961            }
6962            AudioAction::Command(command) => {
6963                let id = command.id();
6964                let sink = if command.ends() {
6965                    self.components.audio.remove(&id)
6966                } else {
6967                    self.components.audio.get(&id).cloned()
6968                };
6969                // A command of an object that failed to open, or closed.
6970                let Some(sink) = sink else {
6971                    return;
6972                };
6973                if command.ends() {
6974                    sink.close();
6975                }
6976                (command, sink)
6977            }
6978        };
6979        match self.audio.clone() {
6980            Some(backend) => backend.command(command, &sink),
6981            None => {
6982                let _ = self.apply_op(Op::Command {
6983                    id: crate::ROOT_ID,
6984                    command: Command::Audio(command),
6985                });
6986            }
6987        }
6988    }
6989
6990    fn apply_action(&mut self, action: Action) {
6991        match action {
6992            Action::Command(id, command) => {
6993                let _ = self.apply_op(Op::Command { id, command });
6994            }
6995            // Answered as the command leaves for the platform
6996            // (`Core::take_commands`) or when the platform reports it.
6997            Action::WriteClipboard(command, answer) => {
6998                self.components.clipboard_writes.push_back(answer);
6999                let _ = self.apply_op(Op::Command {
7000                    id: crate::ROOT_ID,
7001                    command,
7002                });
7003            }
7004            Action::FocusBack { to, from } => self.focus_back = Some((to, from)),
7005            Action::FocusOrigin { to } => self.note_focus_origin(to),
7006            Action::Dialog(mut dialog, answer) => {
7007                dialog.id = self.components.next_dialog;
7008                self.components.next_dialog += 1;
7009                self.components.dialogs.insert(dialog.id, answer);
7010                let _ = self.apply_op(Op::Command {
7011                    id: crate::ROOT_ID,
7012                    command: Command::Dialog(Box::new(dialog)),
7013                });
7014            }
7015            Action::CloseDialog(answer) => {
7016                // Answered already (or never shown): nothing to close.
7017                let Some(id) = self
7018                    .components
7019                    .dialogs
7020                    .iter()
7021                    .find_map(|(id, slot)| Rc::ptr_eq(slot, &answer).then_some(*id))
7022                else {
7023                    return;
7024                };
7025                self.components.dialogs.remove(&id);
7026                answer
7027                    .borrow_mut()
7028                    .deliver(crate::element::DialogReply::dismissed());
7029                let _ = self.apply_op(Op::Command {
7030                    id: crate::ROOT_ID,
7031                    command: Command::CloseDialog(id),
7032                });
7033            }
7034            Action::Return(call, result) => self.settle(call, result),
7035            Action::Animation(op) => {
7036                let _ = self.apply_op(Op::Animation(op));
7037            }
7038            Action::Animate { op, animation, end } => {
7039                self.components
7040                    .animations
7041                    .insert(animation, Awaited::End(end));
7042                let _ = self.apply_op(Op::Animation(op));
7043            }
7044            Action::ReadValue { node, value } => {
7045                let request = self.components.executor.next_animation_id();
7046                self.components
7047                    .animations
7048                    .insert(request, Awaited::Value(value));
7049                let _ = self.apply_op(Op::Animation(crate::animation::AnimationOp::Read {
7050                    node,
7051                    request,
7052                }));
7053            }
7054            Action::ReportViewable(list) => self.report_viewable(list),
7055            Action::Hint(overlay) => self.hint_due(overlay),
7056            Action::Frame(answer) => self.wait_frame(answer),
7057            Action::Appearance(appearance) => self.set_appearance(appearance),
7058            Action::Tokens(tokens) => self.set_tokens(tokens),
7059            Action::Translations(translations) => self.set_translations(translations),
7060            Action::AddTranslations(map) => self.add_translations(map),
7061            Action::TranslationsChanged(before) => self.translations_changed(&before),
7062            Action::Locale(locale) => self.components.locale_request = Some(locale),
7063            Action::MainThread(task) => self.components.main_thread.push(task),
7064            Action::BuiltInScrollbars(source, theme) => {
7065                self.set_builtin_scrollbars(theme.map(|theme| (source, theme)))
7066            }
7067            Action::Measure(id, answer) => self.components.measures.push((id, answer)),
7068            Action::MeasureScrollPosition(id, answer) => {
7069                self.components.scroll_positions.push((id, answer))
7070            }
7071            Action::Evaluate(node, script, timeout, answer) => {
7072                self.start_web_evaluation(node, script, timeout, answer)
7073            }
7074            Action::WebEvaluationTimeout(request) => self.timeout_web_evaluation(request),
7075            Action::CanvasRenderTimeout(id) => self.timeout_canvas_render(id),
7076            Action::TransitionTime(id, answer) => {
7077                self.components.transition_times.push((id, answer))
7078            }
7079            Action::TextContent(id, answer) => self.components.text_contents.push((id, answer)),
7080            Action::PressAt(id, press, answer) => self.components.presses.push((id, press, answer)),
7081            Action::HoverAt(id, mouse) => self.components.hovers.push((id, mouse)),
7082            Action::ImageInfo(uri, answer) => {
7083                let id = self.components.next_image_info;
7084                self.components.next_image_info += 1;
7085                self.components.image_infos.insert(id, answer);
7086                let _ = self.apply_op(Op::Command {
7087                    id: crate::ROOT_ID,
7088                    command: Command::ImageInfo { id, uri },
7089                });
7090            }
7091            Action::Fetch(request, answer) => {
7092                let id = self.components.next_fetch;
7093                self.components.next_fetch += 1;
7094                self.components.fetches.insert(
7095                    id,
7096                    PendingFetch {
7097                        response: crate::element::HttpResponse::default(),
7098                        answer,
7099                    },
7100                );
7101                self.components.fetch_requests.push((id, *request));
7102            }
7103            Action::RegisterFont(data, answer) => {
7104                // The family is the answer: a font without one is refused.
7105                let family = crate::text::font_family(&data)
7106                    .and_then(|family| self.register_font(&data).map(|()| family));
7107                answer.borrow_mut().deliver(family);
7108            }
7109            Action::PickImages(request, answer) => {
7110                if !self.access.allows_picker() {
7111                    answer.borrow_mut().deliver(Vec::new());
7112                    self.deny(
7113                        "the picker is not granted: add `\"picker\": true` to capabilities in nsh.json"
7114                            .into(),
7115                    );
7116                    return;
7117                }
7118                if let Some(picker) = self.picker.clone() {
7119                    let picked = picker.pick_images(request);
7120                    crate::element::task::spawn_raw(
7121                        &self.components.executor,
7122                        crate::ROOT_ID,
7123                        Box::pin(async move {
7124                            let files = crate::picker::finish(&request, picked.await);
7125                            answer.borrow_mut().deliver(files);
7126                        }),
7127                    );
7128                    return;
7129                }
7130                let id = self.components.next_pick;
7131                self.components.next_pick += 1;
7132                self.components
7133                    .picks
7134                    .insert(id, (crate::picker::Pick::Images(request), answer));
7135                let _ = self.apply_op(Op::Command {
7136                    id: crate::ROOT_ID,
7137                    command: Command::PickImages { id, request },
7138                });
7139            }
7140            Action::PickFiles(request, answer) => {
7141                if !self.access.allows_picker() {
7142                    answer.borrow_mut().deliver(Vec::new());
7143                    self.deny(
7144                        "the picker is not granted: add `\"picker\": true` to capabilities in nsh.json"
7145                            .into(),
7146                    );
7147                    return;
7148                }
7149                if let Some(picker) = self.picker.clone() {
7150                    let picked = picker.pick_files(request.clone());
7151                    crate::element::task::spawn_raw(
7152                        &self.components.executor,
7153                        crate::ROOT_ID,
7154                        Box::pin(async move {
7155                            let files = crate::picker::finish_files(&request, picked.await);
7156                            answer.borrow_mut().deliver(files);
7157                        }),
7158                    );
7159                    return;
7160                }
7161                let id = self.components.next_pick;
7162                self.components.next_pick += 1;
7163                self.components
7164                    .picks
7165                    .insert(id, (crate::picker::Pick::Files(request.clone()), answer));
7166                let _ = self.apply_op(Op::Command {
7167                    id: crate::ROOT_ID,
7168                    command: Command::PickFiles { id, request },
7169                });
7170            }
7171            Action::ReadClipboard(read) => {
7172                let id = self.components.next_clipboard_read;
7173                self.components.next_clipboard_read += 1;
7174                let command = match &read {
7175                    ClipboardRead::Text(_) | ClipboardRead::CheckedText(_) => {
7176                        Command::ReadClipboard {
7177                            id,
7178                            has_only: false,
7179                        }
7180                    }
7181                    ClipboardRead::Has(_) => Command::ReadClipboard { id, has_only: true },
7182                    ClipboardRead::Image(_) | ClipboardRead::CheckedImage(_) => {
7183                        Command::ReadClipboardImage {
7184                            id,
7185                            has_only: false,
7186                        }
7187                    }
7188                    ClipboardRead::HasImage(_) => {
7189                        Command::ReadClipboardImage { id, has_only: true }
7190                    }
7191                    ClipboardRead::Files(_) => Command::ReadClipboardFiles { id },
7192                };
7193                self.components.clipboard_reads.insert(id, read);
7194                let _ = self.apply_op(Op::Command {
7195                    id: crate::ROOT_ID,
7196                    command,
7197                });
7198            }
7199            // Checked here, before the engine routes them: the embedding
7200            // app's channel and the platform get only granted names.
7201            Action::HostCall { name, args, answer } => {
7202                use crate::host_channel::{HostError, MAX_PENDING_CALLS};
7203                let refused = crate::host_channel::refusal(&self.access, &name).or_else(|| {
7204                    (self.components.host_calls.len() >= MAX_PENDING_CALLS)
7205                        .then(|| HostError::TooManyCalls { name: name.clone() })
7206                });
7207                if let Some(error) = refused {
7208                    if !matches!(error, HostError::TooManyCalls { .. }) {
7209                        self.deny(error.to_string());
7210                    }
7211                    answer.borrow_mut().deliver(Err(error));
7212                    return;
7213                }
7214                let id = self.components.next_host_call;
7215                self.components.next_host_call += 1;
7216                self.components.host_calls.insert(id, answer);
7217                self.components
7218                    .host_requests
7219                    .push(crate::host_channel::HostRequest::Call { id, name, args });
7220            }
7221            Action::HostPost { name, args } => {
7222                if let Some(error) = crate::host_channel::refusal(&self.access, &name) {
7223                    self.deny(error.to_string());
7224                    return;
7225                }
7226                self.components
7227                    .host_requests
7228                    .push(crate::host_channel::HostRequest::Post { name, args });
7229            }
7230            // A call timed out (`runtime/host.rs`), its answer dropped: its
7231            // slot waits no more.
7232            Action::ForgetHostCalls => {
7233                self.components
7234                    .host_calls
7235                    .retain(|_, slot| std::rc::Rc::strong_count(slot) > 1);
7236            }
7237            Action::OpenUrl(url, answer) => {
7238                if let Err(refused) = crate::open_url::check_url(&url) {
7239                    log::warn!(target: "js", "{refused}");
7240                    answer.borrow_mut().deliver(false);
7241                    return;
7242                }
7243                if !self.access.allows_open_url(&url) {
7244                    answer.borrow_mut().deliver(false);
7245                    self.deny(crate::open_url::not_granted(&url).message().to_owned());
7246                    return;
7247                }
7248                let id = self.components.next_url_open;
7249                self.components.next_url_open = id.wrapping_add(1);
7250                self.components.url_opens.insert(id, answer);
7251                self.components.url_requests.push((id, url));
7252            }
7253            Action::OpenAppSettings(answer) => {
7254                use crate::mobile::AppSettingsError;
7255                // The app's settings page acts on the application as a
7256                // whole (the embedding app's, embedded): an app declaring
7257                // capabilities needs `application`.
7258                let refused = if !self.access.allows_application() {
7259                    Some(AppSettingsError::Denied)
7260                } else if !self.components.environment.app_settings {
7261                    Some(AppSettingsError::Unavailable)
7262                } else {
7263                    None
7264                };
7265                if let Some(error) = refused {
7266                    answer.borrow_mut().deliver(Err(error));
7267                    return;
7268                }
7269                let id = self.components.next_app_settings_open;
7270                self.components.next_app_settings_open = id.wrapping_add(1);
7271                self.components.app_settings_opens.insert(id, answer);
7272                let _ = self.apply_op(Op::Command {
7273                    id: crate::ROOT_ID,
7274                    command: Command::OpenAppSettings { id },
7275                });
7276            }
7277            Action::AppSettingsAvailable(answer) => {
7278                let available =
7279                    self.components.environment.app_settings && self.access.allows_application();
7280                answer.borrow_mut().deliver(available);
7281            }
7282            Action::Audio(action) => self.audio_action(action),
7283            Action::Notification(action) => self.notification_action(action),
7284            Action::LoginItem(enabled, answer) => self.login_item_action(enabled, answer),
7285            Action::SnapToWindowMargin(margin) => self.set_snap_to_window_margin(margin),
7286            Action::ChooseMenuItem(item) => {
7287                // As the platform's menu bar reports a choice: a view's
7288                // handler runs here, JS's in JS.
7289                let payload =
7290                    EventPayload::Map(vec![("id", crate::PayloadValue::Number(f64::from(item)))]);
7291                if !self.dispatch_event(crate::ROOT_ID, EventKind::Menu, &payload) {
7292                    self.events.push(crate::element::JsEvent::Event(
7293                        crate::ROOT_ID,
7294                        EventKind::Menu,
7295                        payload,
7296                    ));
7297                }
7298            }
7299            Action::NextUrlSchemeOpen(task, answer) => {
7300                let executor = &self.components.executor;
7301                self.components
7302                    .url_schemes
7303                    .listen(task, answer, |task| executor.has_task(task));
7304            }
7305            Action::NextUrlSchemeOpenFor(scheme, answer) => {
7306                let links = &mut self.components.url_schemes;
7307                let claimed = links.links.schemes().contains(&scheme)
7308                    || (scheme == "https" && !links.links.web().is_empty());
7309                if !claimed {
7310                    log::warn!(
7311                        "next_url_scheme_open_for: the app does not claim `{scheme}` (nsh.json `schemes`), so no link of it comes"
7312                    );
7313                }
7314                links
7315                    .next_of_scheme
7316                    .retain(|(_, answer)| crate::element::task::awaited(answer));
7317                links.next_of_scheme.push((scheme, answer));
7318            }
7319            Action::NextOpenFiles(answer) => {
7320                let files = &mut self.components.open_files;
7321                if files.pending.is_empty() {
7322                    files.next = Some(answer);
7323                } else {
7324                    answer
7325                        .borrow_mut()
7326                        .deliver(files.pending.drain(..).collect());
7327                }
7328            }
7329            Action::NextSecondInstance(answer) => {
7330                let launches = &mut self.components.second_instances;
7331                match launches.pending.pop_front() {
7332                    Some(launch) => answer.borrow_mut().deliver(launch),
7333                    None => launches.next = Some(answer),
7334                }
7335            }
7336            Action::NextAppUrlChange(answer) => {
7337                let links = &mut self.components.url_schemes;
7338                links.hears_changes = true;
7339                match links.changes.pop_front() {
7340                    Some(change) => answer.borrow_mut().deliver(change),
7341                    None => links.next_change = Some(answer),
7342                }
7343            }
7344            Action::AppUrl(answer) => {
7345                let address = self.components.url_schemes.address.get();
7346                answer.borrow_mut().deliver(address);
7347            }
7348            Action::SetAppUrl(url, history) => {
7349                // Checked where the app called (`set_app_url`, `setUrl`);
7350                // where the app is the page, the address stays of its
7351                // origin (both refuse others first).
7352                let address = self.components.url_schemes.address.clone();
7353                if let Some(base) = address.page_base()
7354                    && !crate::url_scheme::same_origin(Some(base.as_str()), &url)
7355                {
7356                    log::warn!("set_app_url: {url} is not of the page's origin");
7357                    return;
7358                }
7359                // Again for `setUrl`, which wrote it as it was called: in
7360                // order with the page's address the core took since.
7361                address.set(url.clone());
7362                // The platform shows it: the web in its history entries,
7363                // iOS and macOS to the system when the app opts in
7364                // (Handoff).
7365                let command = match history {
7366                    crate::url_scheme::HistoryBehavior::Push => Command::PushAppUrl(url),
7367                    _ => Command::SetAppUrl(url),
7368                };
7369                let _ = self.apply_op(Op::Command {
7370                    id: crate::ROOT_ID,
7371                    command,
7372                });
7373            }
7374            Action::WebInputAvailable(answer) => {
7375                let available =
7376                    self.components.environment.web_input && self.access.allows_web_input();
7377                answer.borrow_mut().deliver(available);
7378            }
7379            Action::WebEvaluateAvailable(answer) => {
7380                let available =
7381                    self.components.environment.web_evaluate && self.access.allows_webviews();
7382                answer.borrow_mut().deliver(available);
7383            }
7384            Action::WebViewAvailable(answer) => {
7385                let available =
7386                    self.components.environment.web_views && self.access.allows_webviews();
7387                answer.borrow_mut().deliver(available);
7388            }
7389            Action::DownloadDecision {
7390                node,
7391                id,
7392                decision,
7393                answer,
7394            } => {
7395                let effects = self
7396                    .components
7397                    .downloads
7398                    .decide(node, &id, decision, answer);
7399                self.apply_download_effects(effects);
7400            }
7401            Action::PickScreenColor(answer) => {
7402                if !self.components.environment.screen_color {
7403                    answer.borrow_mut().deliver(None);
7404                    return;
7405                }
7406                let id = self.components.next_screen_color;
7407                self.components.next_screen_color = id.wrapping_add(1);
7408                self.components.screen_colors.insert(id, answer);
7409                let _ = self.apply_op(Op::Command {
7410                    id: crate::ROOT_ID,
7411                    command: Command::PickScreenColor { id },
7412                });
7413            }
7414            Action::RenderCanvas(request, answer) => self.start_canvas_render(*request, answer),
7415            Action::FileRequest(request, answer) => {
7416                use crate::file_dialog::FileRequest;
7417                if !self.components.environment.file_requests {
7418                    answer.deliver(
7419                        Vec::new(),
7420                        Some("this platform has no file dialogs, file manager or trash".into()),
7421                    );
7422                    return;
7423                }
7424                if let FileRequest::OpenPath(path)
7425                | FileRequest::RevealPath(path)
7426                | FileRequest::MoveToTrash(path) = &request
7427                    && !path.is_absolute()
7428                {
7429                    let refused = format!("`{}` is not an absolute path", path.display());
7430                    log::warn!("{refused}");
7431                    answer.deliver(Vec::new(), Some(refused));
7432                    return;
7433                }
7434                let id = self.components.next_file_request;
7435                self.components.next_file_request = id.wrapping_add(1);
7436                self.components.file_requests.insert(id, answer);
7437                let _ = self.apply_op(Op::Command {
7438                    id: crate::ROOT_ID,
7439                    command: Command::FileRequest {
7440                        id,
7441                        request: Box::new(request),
7442                    },
7443                });
7444            }
7445        }
7446    }
7447
7448    /// Applies what the downloads ask of the core
7449    /// ([`crate::webview::downloads::Effect`]).
7450    fn apply_download_effects(&mut self, effects: Vec<crate::webview::downloads::Effect>) {
7451        use crate::webview::downloads::Effect;
7452        for effect in effects {
7453            match effect {
7454                Effect::Event {
7455                    node,
7456                    kind,
7457                    payload,
7458                } => {
7459                    self.events
7460                        .push(crate::element::JsEvent::Event(node, kind, payload));
7461                }
7462                Effect::Command {
7463                    node,
7464                    operation,
7465                    track,
7466                } => {
7467                    let id = self.alloc_webview_request();
7468                    self.components.downloads.track(id, track);
7469                    let _ = self.apply_op(Op::Command {
7470                        id: node,
7471                        command: Command::WebViewRequest(crate::webview::WebViewRequest {
7472                            id,
7473                            operation,
7474                        }),
7475                    });
7476                }
7477                Effect::Answer { slot, result } => slot.borrow_mut().deliver(result),
7478            }
7479        }
7480    }
7481
7482    /// A request id no outstanding download command uses (downloads and
7483    /// the app's platform replies share one id space per core).
7484    fn alloc_webview_request(&mut self) -> u64 {
7485        loop {
7486            let id = self.components.next_webview_request;
7487            self.components.next_webview_request = id.wrapping_add(1);
7488            if !self.components.downloads.tracks(id) {
7489                break id;
7490            }
7491        }
7492    }
7493
7494    /// The node `id` is released (it unmounted): its downloads are
7495    /// cancelled with [`crate::webview::CancelReason::Teardown`]. The
7496    /// sessions (and their staging files) stay until the platform confirms
7497    /// its writer stopped, even though the node is gone: the reply or end
7498    /// still reaches the core, and only then is cleanup allowed.
7499    pub(super) fn webview_released(&mut self, id: NodeId) {
7500        let effects = self.components.downloads.teardown(id);
7501        // The node still exists but this commit's command queue was already
7502        // drained: put the cancel commands straight into the batch, before
7503        // the node's Delete, so the platform can still stop its writer.
7504        for effect in effects {
7505            match effect {
7506                crate::webview::downloads::Effect::Event {
7507                    node,
7508                    kind,
7509                    payload,
7510                } => self
7511                    .events
7512                    .push(crate::element::JsEvent::Event(node, kind, payload)),
7513                crate::webview::downloads::Effect::Command {
7514                    node,
7515                    operation,
7516                    track,
7517                } => {
7518                    let request = self.alloc_webview_request();
7519                    self.components.downloads.track(request, track);
7520                    self.mount.push(crate::MountItem::Command {
7521                        id: node,
7522                        command: Command::WebViewRequest(crate::webview::WebViewRequest {
7523                            id: request,
7524                            operation,
7525                        }),
7526                    });
7527                }
7528                crate::webview::downloads::Effect::Answer { slot, result } => {
7529                    slot.borrow_mut().deliver(result);
7530                }
7531            }
7532        }
7533    }
7534
7535    /// A platform's report of a download ([`EventKind::DownloadOffer`],
7536    /// `DownloadProgress`, `DownloadEnd`): consumed here, so it never
7537    /// reaches a listener or JS.
7538    fn download_event(&mut self, id: NodeId, kind: EventKind, payload: &EventPayload) -> bool {
7539        match kind {
7540            EventKind::DownloadOffer => {
7541                let EventPayload::Json(value) = payload else {
7542                    return true;
7543                };
7544                let Some(offer) = crate::webview::downloads::parse_offer(value) else {
7545                    log::debug!(target: "js", "web view: dropped a malformed download offer: {value}");
7546                    return true;
7547                };
7548                let events = self
7549                    .key(id)
7550                    .ok()
7551                    .map(|key| self.nodes[key as usize].events)
7552                    .unwrap_or_default();
7553                let mode = if events.contains(EventKind::DownloadPending) {
7554                    crate::webview::downloads::Mode::Manual
7555                } else if events.contains(EventKind::Download) {
7556                    crate::webview::downloads::Mode::Automatic
7557                } else {
7558                    crate::webview::downloads::Mode::None
7559                };
7560                let automatic =
7561                    crate::webview::downloads::automatic_destination(&offer.id, &offer.filename);
7562                // The offer's URL is the response's, after the platform
7563                // followed its redirects: a download from a host takes the
7564                // grant a page there would, so a redirect cannot carry it to
7565                // a host the web view may not show. One of the page's own
7566                // content (`data:`, `blob:`) reaches no host, and stays
7567                // allowed as it was.
7568                let refused = (!self.access.is_unrestricted()
7569                    && !page_content(&offer.url)
7570                    && !self.access.allows_webview(&offer.url))
7571                .then(|| super::not_granted("the download", &offer.url, "webview.hosts"));
7572                if let Some(message) = &refused {
7573                    self.deny(message.clone());
7574                }
7575                let effects = self
7576                    .components
7577                    .downloads
7578                    .offer(id, offer, mode, automatic, refused);
7579                self.apply_download_effects(effects);
7580            }
7581            EventKind::DownloadProgress => {
7582                // Progress is not an app event yet; the platform may still
7583                // report it, and it is dropped here.
7584            }
7585            EventKind::DownloadEnd => {
7586                let EventPayload::Json(value) = payload else {
7587                    return true;
7588                };
7589                let Some(end) = crate::webview::downloads::parse_end(value) else {
7590                    log::debug!(target: "js", "web view: dropped a malformed download end: {value}");
7591                    return true;
7592                };
7593                let effects = self.components.downloads.end(id, end);
7594                self.apply_download_effects(effects);
7595            }
7596            _ => return false,
7597        }
7598        true
7599    }
7600
7601    /// Applies the downloads' file work and deadlines (once per commit).
7602    pub(super) fn poll_downloads(&mut self) {
7603        let effects = self.components.downloads.poll(crate::time::now());
7604        if !effects.is_empty() {
7605            self.apply_download_effects(effects);
7606        }
7607    }
7608
7609    /// The downloads' listeners as a round's final masks leave them: a web
7610    /// view whose `onDownload` and `onDownloadPending` listeners are both
7611    /// gone can neither hear of its downloads nor decide their offers, so
7612    /// they are cancelled ([`crate::webview::CancelReason::NoListener`]).
7613    /// The view stays mounted, and a listener removed and added back in the
7614    /// same turn changes nothing: only the mask the turn ended with counts.
7615    pub(super) fn sync_download_listeners(&mut self) {
7616        let nodes = self.components.downloads.unobserved_nodes(|node| {
7617            self.key(node).is_ok_and(|key| {
7618                let events = self.nodes[key as usize].events;
7619                events.contains(EventKind::Download) || events.contains(EventKind::DownloadPending)
7620            })
7621        });
7622        for node in nodes {
7623            let effects = self.components.downloads.lost_listener(node);
7624            self.apply_download_effects(effects);
7625        }
7626    }
7627
7628    /// When the downloads' next deadline is due (the engine wakes then).
7629    pub fn download_deadline(&self) -> Option<crate::time::Instant> {
7630        self.components.downloads.deadline()
7631    }
7632
7633    /// Native animations that ended: the components' resolve their
7634    /// [`crate::element::AnimationEnd`]s; JS's stay in `finished`.
7635    pub fn animations_finished(&mut self, finished: &mut Vec<crate::animation::Finished>) {
7636        finished.retain(|f| match self.components.animations.remove(&f.animation) {
7637            Some(Awaited::End(end)) => {
7638                end.borrow_mut().deliver(f.finished);
7639                false
7640            }
7641            Some(Awaited::Value(value)) => {
7642                value.borrow_mut().deliver(f.value.unwrap_or_default());
7643                false
7644            }
7645            // JS's are even.
7646            None => f.animation % 2 == 0,
7647        });
7648    }
7649
7650    /// The answer to image info request `id`.
7651    pub(super) fn answer_image_info(&mut self, id: u32, size: Result<ImageSize, String>) {
7652        if let Some(answer) = self.components.image_infos.remove(&id) {
7653            answer.borrow_mut().deliver(size);
7654        }
7655    }
7656
7657    /// Moves the URLs the app asked to open (`openUrl`, [`crate::element::open_url`])
7658    /// since the last call to `out`, by request id, checked and granted
7659    /// ([`crate::open_url`]). The engine asks the embedding app first, then
7660    /// answers each with [`Core::answer_open_url`] (the embedding app took
7661    /// it) or [`Core::open_url_on_platform`].
7662    pub fn take_url_opens(&mut self, out: &mut Vec<(u32, String)>) {
7663        out.append(&mut self.components.url_requests);
7664    }
7665
7666    /// Answers the oldest clipboard write still waiting.
7667    pub(super) fn answer_clipboard_write(&mut self, result: crate::element::ClipboardWrite) {
7668        if let Some(answer) = self.components.clipboard_writes.pop_front() {
7669            answer.borrow_mut().deliver(result);
7670        }
7671    }
7672
7673    /// Answers URL request `id`: whether the URL opened.
7674    pub fn answer_open_url(&mut self, id: u32, opened: bool) {
7675        if let Some(answer) = self.components.url_opens.remove(&id) {
7676            answer.borrow_mut().deliver(opened);
7677        }
7678    }
7679
7680    /// Hands URL request `id` to the platform, which opens `url` and
7681    /// reports whether it did ([`crate::EventKind::OpenUrl`] on the root).
7682    pub fn open_url_on_platform(&mut self, id: u32, url: String) {
7683        if !self.components.url_opens.contains_key(&id) {
7684            return;
7685        }
7686        let _ = self.apply_op(Op::Command {
7687            id: crate::ROOT_ID,
7688            command: Command::OpenUrl { id, url },
7689        });
7690    }
7691
7692    /// Moves the HTTP requests tasks made (`ui::fetch`) since the last call
7693    /// to `start`, by request id: the engine makes them with its network
7694    /// stack and reports what happens with [`Core::fetch_event`]. Requests
7695    /// nothing waits for any more (their task ended) go to `abandoned`, for
7696    /// the engine to cancel.
7697    pub fn take_fetches(
7698        &mut self,
7699        start: &mut Vec<(u32, crate::platform::HttpRequest)>,
7700        abandoned: &mut Vec<u32>,
7701    ) {
7702        start.append(&mut self.components.fetch_requests);
7703        if self.components.fetches.is_empty() {
7704            return;
7705        }
7706        self.components.fetches.retain(|&id, pending| {
7707            // Only the slot is left: the task awaiting it is gone.
7708            let wanted = Rc::strong_count(&pending.answer) > 1;
7709            if !wanted {
7710                abandoned.push(id);
7711            }
7712            wanted
7713        });
7714        start.retain(|(id, _)| !abandoned.contains(id));
7715    }
7716
7717    /// What happened to the tasks' request `id`; false when nothing waits
7718    /// for it any more (the task ended, or the request is over): the engine
7719    /// then cancels it.
7720    pub fn fetch_event(&mut self, id: u32, event: crate::platform::FetchEvent) -> bool {
7721        use crate::platform::FetchEvent;
7722        let Some(pending) = self.components.fetches.get_mut(&id) else {
7723            return false;
7724        };
7725        // Only the slot is left: the task awaiting it is gone.
7726        if Rc::strong_count(&pending.answer) == 1 {
7727            self.components.fetches.remove(&id);
7728            return false;
7729        }
7730        match event {
7731            FetchEvent::BodyWanted => {}
7732            FetchEvent::Head(head) => pending.response.head = head,
7733            FetchEvent::Data(data) => pending.response.body.extend_from_slice(&data),
7734            FetchEvent::End => {
7735                if let Some(pending) = self.components.fetches.remove(&id) {
7736                    pending.answer.borrow_mut().deliver(Ok(pending.response));
7737                }
7738                return false;
7739            }
7740            FetchEvent::Failed(error) => {
7741                if let Some(pending) = self.components.fetches.remove(&id) {
7742                    pending
7743                        .answer
7744                        .borrow_mut()
7745                        .deliver(Err(FetchFailure::Failed(error)));
7746                }
7747                return false;
7748            }
7749        }
7750        true
7751    }
7752
7753    /// Fails the tasks' request `id`, which the app's capabilities do not
7754    /// grant: `url` is the URL refused, the request's or a redirect's (the
7755    /// engine checks every hop), `message` why. A task's
7756    /// [`fetch`](crate::element::fetch) fails with the message; a module
7757    /// function's call rejects with `ERR_ACCESS_DENIED`, `permission`
7758    /// `"network"` and `resource` the URL, as JS's `fetch` does
7759    /// (`registerFont`).
7760    pub fn fetch_refused(&mut self, id: u32, message: String, url: String) {
7761        if let Some(pending) = self.components.fetches.remove(&id) {
7762            let refused = FetchFailure::Refused { message, url };
7763            pending.answer.borrow_mut().deliver(Err(refused));
7764        }
7765    }
7766
7767    /// Resolves clipboard read `id` with the platform's answer (an empty
7768    /// one when the clipboard is not granted).
7769    pub(super) fn answer_clipboard(&mut self, id: u32, answer: ClipboardAnswer) {
7770        let ClipboardAnswer {
7771            has,
7772            text,
7773            denied,
7774            image,
7775            too_large,
7776            files,
7777        } = answer;
7778        let image = image.filter(|i| !i.url.is_empty());
7779        match self.components.clipboard_reads.remove(&id) {
7780            Some(ClipboardRead::Text(slot)) => slot.borrow_mut().deliver(text.unwrap_or_default()),
7781            Some(ClipboardRead::CheckedText(slot)) => slot
7782                .borrow_mut()
7783                .deliver((!denied).then(|| text.unwrap_or_default())),
7784            Some(ClipboardRead::Has(slot) | ClipboardRead::HasImage(slot)) => {
7785                slot.borrow_mut().deliver(has)
7786            }
7787            Some(ClipboardRead::Image(slot)) => slot.borrow_mut().deliver(image),
7788            Some(ClipboardRead::CheckedImage(slot)) => slot.borrow_mut().deliver(match too_large {
7789                Some(bytes) => Err(bytes),
7790                None => Ok(image),
7791            }),
7792            Some(ClipboardRead::Files(slot)) => slot.borrow_mut().deliver(files),
7793            None => {}
7794        }
7795    }
7796
7797    /// The answer to host call `id`: the host's value, or its error. A
7798    /// call that timed out ([`crate::element::host_call_with`]) takes none:
7799    /// its late answer is dropped.
7800    #[doc(hidden)]
7801    pub fn answer_host(
7802        &mut self,
7803        id: u64,
7804        result: Result<crate::JsonValue, crate::host_channel::HostError>,
7805    ) {
7806        match self.components.host_calls.remove(&id) {
7807            Some(answer) if std::rc::Rc::strong_count(&answer) > 1 => {
7808                answer.borrow_mut().deliver(result);
7809            }
7810            _ => {
7811                log::debug!(target: "js", "nsh/host: dropped the answer to call {id}, which no longer waits")
7812            }
7813        }
7814    }
7815
7816    /// Moves the host calls and posts of the app's Rust and JS
7817    /// ([`crate::element::host_call`], [`crate::element::host_post`])
7818    /// since the last call to `out`, checked and granted. The engine hands
7819    /// each to the embedding app's channel where it is configured (its
7820    /// answers come with [`Core::answer_host`]), else to
7821    /// [`Core::host_request_on_platform`].
7822    #[doc(hidden)]
7823    pub fn take_host_requests(&mut self, out: &mut Vec<crate::host_channel::HostRequest>) {
7824        out.append(&mut self.components.host_requests);
7825    }
7826
7827    /// Hands `request` to the platform's host (the web page's): a call
7828    /// goes out as [`Command::HostCall`], answered by the root's
7829    /// [`EventKind::Host`] `{ type: "reply" }`, a post as
7830    /// [`Command::HostPost`]. Without one ([`Environment::host`]) a call
7831    /// fails at once ([`crate::host_channel::HostError::Unavailable`]) and
7832    /// a post goes nowhere, as a channel without a handler drops it.
7833    ///
7834    /// [`Environment::host`]: crate::platform::Environment::host
7835    #[doc(hidden)]
7836    pub fn host_request_on_platform(&mut self, request: crate::host_channel::HostRequest) {
7837        use crate::host_channel::{HostError, HostRequest};
7838        let host = self.components.environment.host;
7839        let command = match request {
7840            HostRequest::Call { id, .. } if !host => {
7841                self.answer_host(id, Err(HostError::Unavailable));
7842                return;
7843            }
7844            HostRequest::Post { .. } if !host => return,
7845            HostRequest::Call { id, name, args } => Command::HostCall { id, name, args },
7846            HostRequest::Post { name, args } => Command::HostPost { name, args },
7847        };
7848        let _ = self.apply_op(Op::Command {
7849            id: crate::ROOT_ID,
7850            command,
7851        });
7852    }
7853
7854    /// The host's event `event` with `data`: the components' listeners of
7855    /// it ([`crate::element::on_host_event`]) run, oldest first. The
7856    /// engine calls it for the embedding app's events; the web page's come
7857    /// as the root's [`EventKind::Host`] events. Without a listener of its
7858    /// name the event is kept until one is added
7859    /// ([`Core::release_host_events`]), as JS keeps the embedding app's.
7860    #[doc(hidden)]
7861    pub fn host_event(&mut self, event: &str, data: &crate::JsonValue) {
7862        if !self.components.executor.host_events.borrow().listens(event) {
7863            // Quietly: in an app whose listeners are JS's, the events no
7864            // Rust code listens to fill this inbox, and JS warns of its own.
7865            if let Some((dropped, _)) = self
7866                .components
7867                .host_inbox
7868                .push(event.to_owned(), data.clone())
7869            {
7870                log::debug!(target: "js", "nsh/host: no Rust listener heard \"{dropped}\"; the oldest kept event was dropped");
7871            }
7872            return;
7873        }
7874        // Those kept for a listener added since the last commit go first.
7875        self.deliver_kept_host_events(event);
7876        self.dispatch_host_event(event, data);
7877    }
7878
7879    /// Hands the host's events kept for want of a listener
7880    /// ([`Core::host_event`]) to the listeners of their names added since
7881    /// the last call, so listeners added after the app started (once it
7882    /// loaded something, say) hear what came before them. The engine calls
7883    /// it after each commit. True when some were delivered: what their
7884    /// listeners changed shows in another round.
7885    #[doc(hidden)]
7886    pub fn release_host_events(&mut self) -> bool {
7887        let names = {
7888            let mut listeners = self.components.executor.host_events.borrow_mut();
7889            if !std::mem::take(&mut listeners.added) || self.components.host_inbox.is_empty() {
7890                return false;
7891            }
7892            listeners.names()
7893        };
7894        let mut delivered = false;
7895        for name in names {
7896            delivered |= self.deliver_kept_host_events(&name);
7897        }
7898        delivered
7899    }
7900
7901    /// Hands the kept events of `event` to its listeners, oldest first,
7902    /// while one is there: one that stops listening leaves the rest kept
7903    /// for the next. True when one was delivered.
7904    fn deliver_kept_host_events(&mut self, event: &str) -> bool {
7905        let mut delivered = false;
7906        while self.components.executor.host_events.borrow().listens(event) {
7907            let Some(data) = self.components.host_inbox.pop(event) else {
7908                break;
7909            };
7910            self.dispatch_host_event(event, &data);
7911            delivered = true;
7912        }
7913        delivered
7914    }
7915
7916    /// Runs the listeners of `event` there now with `data`, oldest first;
7917    /// one that panics is reported and the others still run.
7918    fn dispatch_host_event(&mut self, event: &str, data: &crate::JsonValue) {
7919        let listeners = self.components.executor.host_events.borrow().of(event);
7920        let _entered = self.components.runtime.enter();
7921        for listener in listeners {
7922            let result = caught(|| listener(data));
7923            self.apply_actions();
7924            if let Err(message) = result {
7925                log::error!(target: "js", "a listener of the host's \"{event}\" failed: {message}");
7926            }
7927        }
7928    }
7929
7930    /// What the platform reported of window `id` reaches the ref of the
7931    /// Rust components in it ([`Core::js_window_owner`]); a closed window's
7932    /// goes.
7933    fn report_window(&mut self, id: NodeId, event: &crate::desktop::WindowEvent) {
7934        use crate::desktop::WindowEvent;
7935        match event {
7936            WindowEvent::State(state) => {
7937                self.components.window_reports.entry(id).or_default().0 = Some(**state);
7938            }
7939            WindowEvent::TitleBar(area) => {
7940                self.components.window_reports.entry(id).or_default().1 = *area;
7941            }
7942            WindowEvent::Closed { .. } => {
7943                self.components.window_reports.remove(&id);
7944                if let Some((owner, _)) = self.components.js_windows.remove(&id) {
7945                    let _entered = self.components.runtime.enter();
7946                    owner.dispose();
7947                }
7948                return;
7949            }
7950            _ => return,
7951        }
7952        if let Some((_, this)) = self.components.js_windows.get(&id) {
7953            let _entered = self.components.runtime.enter();
7954            this.report(event);
7955        }
7956    }
7957
7958    /// Events the components handle before anything else: dialog answers
7959    /// (theirs never reach JS), insets of screens and modals.
7960    fn platform_event(&mut self, id: NodeId, kind: EventKind, payload: &EventPayload) -> bool {
7961        if matches!(
7962            kind,
7963            EventKind::DownloadOffer | EventKind::DownloadProgress | EventKind::DownloadEnd
7964        ) {
7965            return self.download_event(id, kind, payload);
7966        }
7967        let number = |key: &str| match payload {
7968            EventPayload::Map(entries) => entries.iter().find_map(|(k, v)| match v {
7969                crate::PayloadValue::Number(n) if *k == key => Some(*n),
7970                _ => None,
7971            }),
7972            _ => None,
7973        };
7974        match kind {
7975            // A window that keeps its placement saves it as it changes; the
7976            // event goes on to the app.
7977            EventKind::Window => {
7978                if let EventPayload::Window(event) = payload {
7979                    if id != ROOT_ID {
7980                        self.report_window(id, event);
7981                    }
7982                    match event.as_ref() {
7983                        crate::desktop::WindowEvent::State(state) => {
7984                            self.keep_window_placement(id, state);
7985                        }
7986                        // Rust listeners of the main window's; JS's hear it
7987                        // from the event.
7988                        crate::desktop::WindowEvent::ClosePress { reason }
7989                            if id == crate::ROOT_ID =>
7990                        {
7991                            self.components.runtime.main_close_pressed(*reason);
7992                        }
7993                        crate::desktop::WindowEvent::QuitRequest if id == crate::ROOT_ID => {
7994                            self.quit_requested();
7995                            return true;
7996                        }
7997                        _ => {}
7998                    }
7999                }
8000                false
8001            }
8002            EventKind::Dialog => {
8003                let Some(dialog) = number("id") else {
8004                    return false;
8005                };
8006                let Some(answer) = self.components.dialogs.remove(&(dialog as u32)) else {
8007                    return false;
8008                };
8009                let value = match payload {
8010                    EventPayload::Map(entries) => entries.iter().find_map(|(k, v)| match v {
8011                        crate::PayloadValue::Str(text) if *k == "value" => Some(text.clone()),
8012                        _ => None,
8013                    }),
8014                    _ => None,
8015                };
8016                answer.borrow_mut().deliver(crate::element::DialogReply {
8017                    index: number("index").unwrap_or(-1.0) as i32,
8018                    value,
8019                });
8020                true
8021            }
8022            // A view's shortcut runs here; JS's go to JS.
8023            EventKind::KeyCommand if id == crate::ROOT_ID => {
8024                let EventPayload::Value(crate::PayloadValue::Number(binding)) = payload else {
8025                    return false;
8026                };
8027                let binding = *binding as u32;
8028                if binding < crate::element::keys::FIRST_ID {
8029                    return false;
8030                }
8031                if binding == super::overlay::ESCAPE_BINDING {
8032                    self.overlay_escape();
8033                    return true;
8034                }
8035                let found = self.components.executor.keys.borrow().handler(binding);
8036                // A binding removed since the platform matched it.
8037                if let Some((text, handler)) = found {
8038                    let result = caught(|| handler(&text));
8039                    self.apply_actions();
8040                    if let Err(message) = result {
8041                        log::error!(target: "js", "a keyboard shortcut failed: {message}");
8042                    }
8043                }
8044                true
8045            }
8046            // A view's menu item runs here; JS's go to JS. A context menu
8047            // closing settles the one either side showed, so both hear it.
8048            EventKind::Menu if id == crate::ROOT_ID => {
8049                let menus = self.components.executor.menus.clone();
8050                let closed = matches!(payload, EventPayload::Map(entries)
8051                    if entries.iter().any(|(k, v)| *k == "closed" && *v == crate::PayloadValue::Bool(true)));
8052                if closed {
8053                    menus.borrow_mut().settle_popup();
8054                    return false;
8055                }
8056                let Some(item) = number("id").map(|n| n as u32) else {
8057                    return false;
8058                };
8059                if item < crate::element::menus::FIRST_ID {
8060                    return false;
8061                }
8062                // The platform's answer to a global shortcut's registration.
8063                let registered = match payload {
8064                    EventPayload::Map(entries) => entries.iter().find_map(|(k, v)| match v {
8065                        crate::PayloadValue::Bool(b) if *k == "registered" => Some(*b),
8066                        _ => None,
8067                    }),
8068                    _ => None,
8069                };
8070                if let Some(registered) = registered {
8071                    menus.borrow_mut().registered(item, registered);
8072                    self.apply_actions();
8073                    return true;
8074                }
8075                let click = menus.borrow().tray_click(item);
8076                if let Some(click) = click {
8077                    let bounds = match payload {
8078                        EventPayload::Map(entries) => entries.iter().find_map(|(k, v)| match v {
8079                            crate::PayloadValue::Bounds(b) if *k == "bounds" => Some(*b),
8080                            _ => None,
8081                        }),
8082                        _ => None,
8083                    };
8084                    let result = caught(|| click(bounds));
8085                    self.apply_actions();
8086                    if let Err(message) = result {
8087                        log::error!(target: "js", "the tray's click failed: {message}");
8088                    }
8089                    return true;
8090                }
8091                let handler = menus.borrow().handler(item);
8092                // An item of a menu replaced since the platform showed it.
8093                if let Some(handler) = handler {
8094                    let result = caught(|| handler());
8095                    self.apply_actions();
8096                    if let Err(message) = result {
8097                        log::error!(target: "js", "a menu item failed: {message}");
8098                    }
8099                }
8100                true
8101            }
8102            EventKind::BackPress if id == crate::ROOT_ID => {
8103                // The top overlay listening takes it first.
8104                if self.overlay_cancel() {
8105                    return true;
8106                }
8107                let listeners = self.components.executor.back.borrow().newest_first();
8108                for listener in listeners {
8109                    if self.back_pressed(&listener) {
8110                        return true;
8111                    }
8112                }
8113                // JS's listeners run next (and go back when none handles
8114                // it).
8115                if self.components.js_back {
8116                    return false;
8117                }
8118                let _ = self.apply_op(Op::Command {
8119                    id: crate::ROOT_ID,
8120                    command: Command::Back,
8121                });
8122                true
8123            }
8124            EventKind::BackProgress if id == crate::ROOT_ID => {
8125                let Some(event) = crate::BackProgressEvent::from_payload(payload) else {
8126                    return true;
8127                };
8128                // The press of a gesture the top overlay listening to
8129                // `onCancel` takes is the overlay's: the app follows only
8130                // the gestures that start without one.
8131                if event.phase == crate::BackPhase::Start {
8132                    self.components.back_gesture = !self.overlay_state.cancel;
8133                }
8134                if !self.components.back_gesture {
8135                    return true;
8136                }
8137                if matches!(
8138                    event.phase,
8139                    crate::BackPhase::End | crate::BackPhase::Cancel
8140                ) {
8141                    self.components.back_gesture = false;
8142                }
8143                let listeners = self
8144                    .components
8145                    .executor
8146                    .back_progress
8147                    .borrow()
8148                    .newest_first();
8149                for listener in listeners {
8150                    let result = caught(|| listener(&event));
8151                    self.apply_actions();
8152                    if let Err(message) = result {
8153                        log::error!(target: "js", "a back progress listener failed: {message}");
8154                    }
8155                }
8156                // JS's listeners hear it next.
8157                !self.components.js_back_progress
8158            }
8159            EventKind::WebEvaluation => {
8160                self.answer_web_evaluation(id, payload);
8161                true
8162            }
8163            EventKind::ImageInfo if id == crate::ROOT_ID => {
8164                let Some(request) = number("id") else {
8165                    return false;
8166                };
8167                let error = match payload {
8168                    EventPayload::Map(entries) => entries.iter().find_map(|(k, v)| match v {
8169                        crate::PayloadValue::Str(e) if *k == "error" => Some(e.clone()),
8170                        _ => None,
8171                    }),
8172                    _ => None,
8173                };
8174                let size = match (number("width"), number("height"), error) {
8175                    (Some(width), Some(height), None) => Ok(ImageSize {
8176                        width: pixels(width),
8177                        height: pixels(height),
8178                    }),
8179                    (_, _, error) => Err(error.unwrap_or_else(|| "no size".into())),
8180                };
8181                self.answer_image_info(request as u32, size);
8182                true
8183            }
8184            EventKind::Audio if id == crate::ROOT_ID => {
8185                let EventPayload::Audio { id: object, event } = payload else {
8186                    return false;
8187                };
8188                // Dropped once the object is closed.
8189                if let Some(sink) = self.components.audio.get(object) {
8190                    sink.send(event.clone());
8191                }
8192                true
8193            }
8194            EventKind::Pick if id == crate::ROOT_ID => {
8195                let EventPayload::Picked { id: request, files } = payload else {
8196                    return false;
8197                };
8198                if let Some((asked, answer)) = self.components.picks.remove(request) {
8199                    let files = asked.finish(files.clone());
8200                    answer.borrow_mut().deliver(files);
8201                }
8202                true
8203            }
8204            EventKind::Notification if id == crate::ROOT_ID => {
8205                self.notification_event(payload);
8206                true
8207            }
8208            EventKind::SecondInstance if id == crate::ROOT_ID => {
8209                let Some(launch) = crate::single_instance::SecondInstance::from_payload(payload)
8210                else {
8211                    return false;
8212                };
8213                let launches = &mut self.components.second_instances;
8214                if let Some(answer) = launches.next.take() {
8215                    answer.borrow_mut().deliver(launch);
8216                } else {
8217                    if launches.pending.len() == crate::single_instance::MAX_PENDING {
8218                        launches.pending.pop_front();
8219                    }
8220                    launches.pending.push_back(launch);
8221                }
8222                true
8223            }
8224            EventKind::UrlScheme if id == crate::ROOT_ID => {
8225                let EventPayload::Map(entries) = payload else {
8226                    return false;
8227                };
8228                let url = entries.iter().find_map(|(k, v)| match v {
8229                    crate::PayloadValue::Str(url) if *k == crate::url_scheme::URL => Some(url),
8230                    _ => None,
8231                });
8232                let Some(url) = url else {
8233                    return false;
8234                };
8235                let flag = |key: &str| {
8236                    entries.iter().find_map(|(k, v)| match v {
8237                        crate::PayloadValue::Bool(b) if *k == key => Some(*b),
8238                        _ => None,
8239                    })
8240                };
8241                let page = flag(crate::url_scheme::PAGE).unwrap_or(false);
8242                let quiet = flag(crate::url_scheme::QUIET).unwrap_or(false);
8243                // An address move the app did not make (the web's back or
8244                // forward), by its reason; one of a newer platform's reasons
8245                // is still the address, quietly.
8246                let change = entries.iter().find_map(|(k, v)| match v {
8247                    crate::PayloadValue::Str(s) if *k == crate::url_scheme::CHANGE => {
8248                        Some(crate::url_scheme::AppUrlChangeReason::parse(s))
8249                    }
8250                    _ => None,
8251                });
8252                let (quiet, change) = match change {
8253                    Some(None) => (true, None),
8254                    Some(reason) => (quiet, reason),
8255                    None => (quiet, None),
8256                };
8257                // The page's base URL (the web), which Rust's `set_app_url`
8258                // resolves against.
8259                if let Some(base) = entries.iter().find_map(|(k, v)| match v {
8260                    crate::PayloadValue::Str(s) if *k == crate::url_scheme::BASE => {
8261                        url::Url::parse(s).ok()
8262                    }
8263                    _ => None,
8264                }) {
8265                    self.components.url_schemes.address.set_page_base(base);
8266                }
8267                self.url_scheme(url.clone(), page, quiet, change);
8268                true
8269            }
8270            EventKind::ClipboardWrite if id == crate::ROOT_ID => {
8271                let written = match payload {
8272                    EventPayload::Map(entries) => entries
8273                        .iter()
8274                        .any(|(k, v)| *k == "written" && *v == crate::PayloadValue::Bool(true)),
8275                    _ => false,
8276                };
8277                self.answer_clipboard_write(if written {
8278                    crate::element::ClipboardWrite::Written
8279                } else {
8280                    crate::element::ClipboardWrite::Failed
8281                });
8282                true
8283            }
8284            EventKind::OpenUrl if id == crate::ROOT_ID => {
8285                let Some(request) = number("id") else {
8286                    return false;
8287                };
8288                let opened = match payload {
8289                    EventPayload::Map(entries) => entries
8290                        .iter()
8291                        .any(|(k, v)| *k == "opened" && *v == crate::PayloadValue::Bool(true)),
8292                    _ => false,
8293                };
8294                self.answer_open_url(request as u32, opened);
8295                true
8296            }
8297            EventKind::OpenAppSettings if id == crate::ROOT_ID => {
8298                let Some(request) = number("id") else {
8299                    return false;
8300                };
8301                let opened = match payload {
8302                    EventPayload::Map(entries) => entries
8303                        .iter()
8304                        .any(|(k, v)| *k == "opened" && *v == crate::PayloadValue::Bool(true)),
8305                    _ => false,
8306                };
8307                if let Some(answer) = self.components.app_settings_opens.remove(&(request as u32)) {
8308                    answer.borrow_mut().deliver(Ok(opened));
8309                }
8310                true
8311            }
8312            EventKind::ScreenColor if id == crate::ROOT_ID => {
8313                let Some(request) = number("id") else {
8314                    return false;
8315                };
8316                let color = number("color").map(|packed| crate::Color(packed as u32).into());
8317                if let Some(answer) = self.components.screen_colors.remove(&(request as u32)) {
8318                    answer.borrow_mut().deliver(color);
8319                }
8320                true
8321            }
8322            EventKind::CanvasImage if id == crate::ROOT_ID => self.answer_canvas_render(payload),
8323            EventKind::FileRequest if id == crate::ROOT_ID => {
8324                let EventPayload::FileRequest {
8325                    id: request,
8326                    paths,
8327                    error,
8328                } = payload
8329                else {
8330                    return false;
8331                };
8332                if let Some(answer) = self.components.file_requests.remove(request) {
8333                    answer.deliver(paths.clone(), error.clone());
8334                }
8335                true
8336            }
8337            // The platform's answer to a download command
8338            // ([`crate::webview::WebViewRequest`]), on the node it was sent
8339            // to. A reply whose writer stopped is the only thing that
8340            // permits cleaning a staging file.
8341            EventKind::WebViewReply => {
8342                let EventPayload::Json(reply) = payload else {
8343                    return false;
8344                };
8345                // JSON's numbers may come as floats (`1.0`); `1.5` is no
8346                // request.
8347                let request = reply.get("id").and_then(|id| {
8348                    id.as_u64().or_else(|| {
8349                        id.as_f64()
8350                            .filter(|n| n.is_finite() && n.fract() == 0.0 && *n >= 0.0)
8351                            .map(|n| n as u64)
8352                    })
8353                });
8354                let Some(request) = request else {
8355                    log::debug!(target: "js", "web view: dropped a reply without a request's id: {reply}");
8356                    return true;
8357                };
8358                if !self.components.downloads.tracks(request) {
8359                    log::debug!(target: "js", "web view: dropped a reply to unknown request {request}: {reply}");
8360                    return true;
8361                }
8362                let result = match reply.get("ok").and_then(crate::JsonValue::as_bool) {
8363                    Some(true) => Ok(()),
8364                    _ => Err(reply
8365                        .get("error")
8366                        .and_then(crate::JsonValue::as_str)
8367                        .unwrap_or("the web view did not answer")
8368                        .to_owned()),
8369                };
8370                let effects = self.components.downloads.reply(id, request, result);
8371                self.apply_download_effects(effects);
8372                true
8373            }
8374            EventKind::Clipboard if id == crate::ROOT_ID => {
8375                let Some(request) = number("id") else {
8376                    return false;
8377                };
8378                let answer = ClipboardAnswer::from_payload(payload);
8379                self.answer_clipboard(request as u32, answer);
8380                true
8381            }
8382            // The host's replies; its events reach the components'
8383            // listeners, then go on to `nsh/host`'s (`nsh-js`).
8384            EventKind::Host if id == crate::ROOT_ID => {
8385                let EventPayload::Json(reply) = payload else {
8386                    return false;
8387                };
8388                match reply.get("type").and_then(crate::JsonValue::as_str) {
8389                    Some("reply") => {}
8390                    Some("event") => {
8391                        if let Some(event) = reply.get("event").and_then(crate::JsonValue::as_str) {
8392                            let data = reply.get("payload").cloned().unwrap_or_default();
8393                            self.host_event(event, &data);
8394                        }
8395                        return false;
8396                    }
8397                    _ => return false,
8398                }
8399                // JSON's numbers may come as floats (`1.0`); `1.5` is no
8400                // call. Ids stay within JS' safe integers.
8401                let call = reply.get("id").and_then(|id| {
8402                    id.as_u64().or_else(|| {
8403                        id.as_f64()
8404                            .filter(|n| {
8405                                n.fract() == 0.0 && (1.0..=9_007_199_254_740_991.0).contains(n)
8406                            })
8407                            .map(|n| n as u64)
8408                    })
8409                });
8410                let Some(call) = call else {
8411                    log::debug!(target: "js", "nsh/host: dropped a reply without a call's id: {reply}");
8412                    return true;
8413                };
8414                let result = if reply.get("ok").and_then(crate::JsonValue::as_bool) == Some(true) {
8415                    Ok(reply.get("value").cloned().unwrap_or_default())
8416                } else {
8417                    Err(crate::host_channel::HostError::Failed(
8418                        reply
8419                            .get("error")
8420                            .and_then(crate::JsonValue::as_str)
8421                            .unwrap_or("nsh/host: the call failed")
8422                            .to_owned(),
8423                    ))
8424                };
8425                self.answer_host(call, result);
8426                true
8427            }
8428            EventKind::Insets => {
8429                let insets = EdgeInsets {
8430                    top: Points(number("top").unwrap_or(0.0) as f32),
8431                    right: Points(number("right").unwrap_or(0.0) as f32),
8432                    bottom: Points(number("bottom").unwrap_or(0.0) as f32),
8433                    left: Points(number("left").unwrap_or(0.0) as f32),
8434                };
8435                // The views reading them follow (`drain_views`).
8436                self.components.insets.insert(id, insets);
8437                // JS's screens keep them too.
8438                false
8439            }
8440            _ => false,
8441        }
8442    }
8443
8444    /// Runs a back listener: whether it handled the press.
8445    fn back_pressed(&mut self, listener: &crate::element::BackListener) -> bool {
8446        let result = caught(|| listener());
8447        self.apply_actions();
8448        result.unwrap_or_else(|message| {
8449            log::error!(target: "js", "a back press listener failed: {message}");
8450            false
8451        })
8452    }
8453
8454    /// The root listens to the back button while JS or a component does:
8455    /// follows the components' listeners coming and going.
8456    pub(super) fn sync_back(&mut self) {
8457        let rust = {
8458            let mut back = self.components.executor.back.borrow_mut();
8459            if !std::mem::take(&mut back.changed) {
8460                return;
8461            }
8462            !back.list.is_empty()
8463        };
8464        let _ = self.apply_op(Op::Listen {
8465            id: crate::ROOT_ID,
8466            event: EventKind::BackPress,
8467            enabled: rust || self.components.js_back || self.overlay_state.cancel,
8468        });
8469    }
8470
8471    /// The root listens to the back gesture's steps while JS or a component
8472    /// does: follows the components' listeners coming and going.
8473    pub(super) fn sync_back_progress(&mut self) {
8474        let rust = {
8475            let mut progress = self.components.executor.back_progress.borrow_mut();
8476            if !std::mem::take(&mut progress.changed) {
8477                return;
8478            }
8479            !progress.list.is_empty()
8480        };
8481        let _ = self.apply_op(Op::Listen {
8482            id: crate::ROOT_ID,
8483            event: EventKind::BackProgress,
8484            enabled: rust || self.components.js_back_progress,
8485        });
8486    }
8487
8488    /// The root's shortcuts follow the views' bindings coming and going:
8489    /// the table JS's and theirs make, listened to while either has one.
8490    pub(super) fn sync_keys(&mut self) {
8491        let escape_to_focus = self.focus_takes_escape();
8492        if escape_to_focus != self.overlay_state.escape_to_focus {
8493            self.overlay_state.escape_to_focus = escape_to_focus;
8494            self.components.executor.keys.borrow_mut().changed = true;
8495        }
8496        let rust = {
8497            // The windows' refs read the graph.
8498            let _entered = self.components.runtime.enter();
8499            let mut keys = self.components.executor.keys.borrow_mut();
8500            // A binding of a window that was not mounted yet is placed
8501            // once it is.
8502            if !std::mem::take(&mut keys.changed) && !keys.unplaced {
8503                return;
8504            }
8505            !keys.list.is_empty()
8506        };
8507        let keymap = self.keymap();
8508        let _ = self.apply_op(Op::SetProp {
8509            id: crate::ROOT_ID,
8510            prop: Prop::Keymap(keymap),
8511        });
8512        let _ = self.apply_op(Op::Listen {
8513            id: crate::ROOT_ID,
8514            event: EventKind::KeyCommand,
8515            enabled: rust
8516                || self.components.js_keys
8517                || self.overlay_state.cancel
8518                || self.overlay_state.hint_escape,
8519        });
8520    }
8521
8522    /// The surface's table: JS's bindings, then the views' (the newest that
8523    /// may fire wins, so a view's wins over JS's of the same keystroke).
8524    fn keymap(&self) -> Arc<crate::keymap::Keymap> {
8525        let mut keys = self.components.executor.keys.borrow_mut();
8526        let overlay = self.overlay_key_binding();
8527        if keys.list.is_empty() && overlay.is_none() {
8528            keys.unplaced = false;
8529            return self.components.js_keymap.clone();
8530        }
8531        let views = {
8532            let _entered = self.components.runtime.enter();
8533            // Bindings share a few owners (a component's effect binds many):
8534            // each is looked up once.
8535            let mut known: Vec<(crate::element::Owner, NodeId)> = Vec::new();
8536            keys.bindings(|owner| {
8537                if let Some(&(_, window)) = known.iter().find(|(o, _)| *o == owner) {
8538                    return window;
8539                }
8540                let window = self.window_of_owner(owner);
8541                known.push((owner, window));
8542                window
8543            })
8544        };
8545        drop(keys);
8546        // JS's first, then the views', where the newest that may fire wins:
8547        // a focused component's keys win over the app's. Bindings
8548        // `OverFocused::Always` come after both, so they win over the components';
8549        // the overlay's Escape (a popup closing) stays last.
8550        let js = self.components.js_keymap.bindings();
8551        let bindings = js
8552            .iter()
8553            .filter(|b| !b.comes_after_views())
8554            .chain(views.iter().filter(|b| !b.comes_after_views()))
8555            .chain(js.iter().filter(|b| b.comes_after_views()))
8556            .chain(views.iter().filter(|b| b.comes_after_views()))
8557            .copied()
8558            .chain(overlay)
8559            .collect();
8560        Arc::new(crate::keymap::Keymap::new(bindings))
8561    }
8562
8563    /// The insets where `host` renders: its screen's or modal's, else the
8564    /// surface's safe area.
8565    pub(super) fn insets_of(&self, host: NodeId) -> EdgeInsets {
8566        let safe = self.components.environment.safe_area;
8567        let mut key = self.key(host).ok();
8568        while let Some(k) = key {
8569            let node = &self.nodes[k as usize];
8570            if let Some(insets) = self.components.insets.get(&node.id) {
8571                return *insets;
8572            }
8573            match node.kind {
8574                // Not reported yet: a screen's header covers the top.
8575                Kind::Screen => {
8576                    return EdgeInsets {
8577                        top: Points::ZERO,
8578                        ..safe
8579                    };
8580                }
8581                Kind::Modal => return safe,
8582                _ => {}
8583            }
8584            key = (node.parent != NO_KEY).then_some(node.parent);
8585        }
8586        safe
8587    }
8588
8589    /// Whether `key` or a view around it already stands clear of the
8590    /// software keyboard (`Prop::ClearsKeyboard`, a bottom sheet the
8591    /// keyboard lifts): the keyboard takes nothing more from it.
8592    fn clears_keyboard(&self, key: super::Key) -> bool {
8593        let mut key = key;
8594        loop {
8595            let node = &self.nodes[key as usize];
8596            if node.clears_keyboard {
8597                return true;
8598            }
8599            if node.parent == NO_KEY {
8600                return false;
8601            }
8602            key = node.parent;
8603        }
8604    }
8605
8606    /// What `env` (a node's `env()` terms) comes to for `key` now: the
8607    /// insets of the root view it renders in ([`Self::insets_of`]) and the
8608    /// software keyboard's height, 0 where a view around it stands clear
8609    /// of the keyboard already ([`Self::clears_keyboard`]).
8610    pub(super) fn env_insets(
8611        &self,
8612        key: super::Key,
8613        env: &crate::style::EnvEdges,
8614    ) -> [EdgeInsets; 2] {
8615        use crate::style::EnvVar;
8616        let mut root = None;
8617        let mut value = |var: Option<EnvVar>| {
8618            let Some(var) = var else {
8619                return Points::ZERO;
8620            };
8621            if var == EnvVar::KeyboardInsetHeight {
8622                if self.clears_keyboard(key) {
8623                    return Points::ZERO;
8624                }
8625                return self
8626                    .components
8627                    .environment
8628                    .keyboard_height
8629                    .max(Points::ZERO);
8630            }
8631            let insets = *root.get_or_insert_with(|| self.insets_of(self.nodes[key as usize].id));
8632            match var {
8633                EnvVar::SafeAreaInsetTop => insets.top,
8634                EnvVar::SafeAreaInsetRight => insets.right,
8635                EnvVar::SafeAreaInsetBottom => insets.bottom,
8636                _ => insets.left,
8637            }
8638        };
8639        let mut edges = |vars: &[Option<EnvVar>; 4]| EdgeInsets {
8640            top: value(vars[0]),
8641            right: value(vars[1]),
8642            bottom: value(vars[2]),
8643            left: value(vars[3]),
8644        };
8645        [edges(&env.padding), edges(&env.margin)]
8646    }
8647
8648    /// The nodes whose padding or margin uses `env()` follow the
8649    /// environment: restyled where what their terms come to changed (a
8650    /// safe area, a page's insets, the keyboard, a move to another root
8651    /// view). What a change of the keyboard's height moves (those terms,
8652    /// or the styles an app derives from `keyboardFrame()` in the same
8653    /// commit) animates with the keyboard, natively, unless the app
8654    /// configured this commit's animation itself.
8655    pub(super) fn sync_env(&mut self) {
8656        let mut keyboard_moved = std::mem::take(&mut self.keyboard_moved);
8657        if !self.env_styled.is_empty() {
8658            keyboard_moved |= self.restyle_env();
8659        }
8660        let duration = self.components.environment.keyboard_duration;
8661        if keyboard_moved && duration > 0.0 && self.layout_animation.is_none() {
8662            use crate::props::{LayoutAnimation, LayoutCurve, LayoutProperty, LayoutTransition};
8663            self.layout_animation = Some(LayoutAnimation {
8664                create: None,
8665                update: Some(LayoutTransition {
8666                    curve: LayoutCurve::Keyboard,
8667                    property: LayoutProperty::Opacity,
8668                    duration_ms: duration,
8669                    delay_ms: 0.0,
8670                }),
8671                delete: None,
8672            });
8673        }
8674    }
8675
8676    /// Restyles the nodes whose `env()` terms came to something else;
8677    /// whether the keyboard moved one of them.
8678    fn restyle_env(&mut self) -> bool {
8679        let mut ids = std::mem::take(&mut self.env_scratch);
8680        ids.extend(self.env_styled.iter().copied());
8681        let mut keyboard_moved = false;
8682        for &id in &ids {
8683            let node = self.key(id).ok().and_then(|key| {
8684                let env = self.nodes[key as usize].env.as_deref().copied()?;
8685                Some((key, env))
8686            });
8687            let Some((key, (env, applied))) = node else {
8688                self.env_styled.remove(&id);
8689                continue;
8690            };
8691            let now = self.env_insets(key, &env);
8692            if now == applied {
8693                continue;
8694            }
8695            // The edges the keyboard moves.
8696            let keyboard = |vars: &[Option<crate::style::EnvVar>; 4],
8697                            was: &EdgeInsets,
8698                            now: &EdgeInsets| {
8699                let (was, now) = (
8700                    [was.top, was.right, was.bottom, was.left],
8701                    [now.top, now.right, now.bottom, now.left],
8702                );
8703                (0..4).any(|i| {
8704                    vars[i] == Some(crate::style::EnvVar::KeyboardInsetHeight) && was[i] != now[i]
8705                })
8706            };
8707            keyboard_moved |= keyboard(&env.padding, &applied[0], &now[0])
8708                || keyboard(&env.margin, &applied[1], &now[1]);
8709            self.restyle(key);
8710        }
8711        ids.clear();
8712        self.env_scratch = ids;
8713        keyboard_moved
8714    }
8715
8716    /// Applies what handlers, handles (element refs, animated values) and
8717    /// services asked for, in order.
8718    pub(super) fn apply_actions(&mut self) {
8719        for action in self.components.executor.take_actions() {
8720            self.apply_action(action);
8721        }
8722    }
8723
8724    /// An event the component on `host` emitted: to the component whose
8725    /// view has it, if it handles it (a list row's handlers run with the
8726    /// component whose list it is), else to JS.
8727    pub(super) fn route_emit(
8728        &mut self,
8729        host: NodeId,
8730        event: Box<dyn crate::element::builder::AnyEvent>,
8731    ) {
8732        match self.components.owners.get(&host).copied() {
8733            Some(parent) => {
8734                let Some(owner) = self.state_owner(parent) else {
8735                    return;
8736                };
8737                // In order, found one at a time (no list per event).
8738                let mut from = 0;
8739                while let Some((at, listener)) =
8740                    self.components.instances.get(&parent).and_then(|inst| {
8741                        inst.event_handlers
8742                            .iter()
8743                            .enumerate()
8744                            .skip(from)
8745                            .find(|(_, (n, _))| *n == host)
8746                            .map(|(at, (_, l))| (at, l.clone()))
8747                    })
8748                {
8749                    from = at + 1;
8750                    if let Err(message) = caught(|| listener.call(event.as_any())) {
8751                        self.component_failed(owner, message);
8752                    }
8753                    self.apply_actions();
8754                }
8755            }
8756            None => self.events.push(JsEvent::Component { host, event }),
8757        }
8758    }
8759}
8760
8761/// Drops `value`, which holds the app's values (a call's arguments or
8762/// result): a panic in their `Drop` is logged instead of unwinding
8763/// through the core.
8764fn drop_caught<T>(value: T) {
8765    if let Err(message) = caught(move || drop(value)) {
8766        log::error!(target: "js", "a value of a call into Rust panicked as it dropped: {message}");
8767    }
8768}
8769
8770/// Disposes the contents of a list's cells: the run that made the list went.
8771fn dispose_rows(rows: &std::rc::Weak<RefCell<CellRowMap>>) {
8772    let Some(rows) = rows.upgrade() else {
8773        return;
8774    };
8775    let owners: Vec<_> = rows.borrow_mut().drain().map(|(_, (_, o))| o).collect();
8776    for owner in owners {
8777        owner.dispose();
8778    }
8779}
8780
8781/// Moves the live cells of a view's list as its rows moved (`diff`, now
8782/// `count` rows): each keeps its row, at the row's new index. A cell whose
8783/// row went keeps its index, and shows the row now there, unless that row
8784/// came there with its own cell: then, as past the rows, its content is
8785/// disposed before its bindings could read there, so a row never shows in
8786/// two cells (`ListState::adopt_orphans` in `core/list.rs`, by the same
8787/// rule).
8788fn move_rows(cells: &CellRows, diff: Option<&ListDiff>, count: u32) {
8789    let parts: Vec<_> = cells
8790        .borrow()
8791        .iter()
8792        .map(|(&id, &(index, owner))| (id, index, owner))
8793        .collect();
8794    let mut gone = Vec::new();
8795    // The new index of each cell's row, `None` for a row that went.
8796    let moves: Vec<_> = parts
8797        .iter()
8798        .map(|&(id, index, owner)| {
8799            let i = index.get_untracked();
8800            let to = match diff {
8801                Some(d) => d.new_index(i as u32).map(|(to, _)| to as usize),
8802                None => Some(i),
8803            };
8804            (id, index, owner, i, to)
8805        })
8806        .collect();
8807    let mut taken: Vec<usize> = moves
8808        .iter()
8809        .filter(|m| m.2.is_live())
8810        .filter_map(|m| m.4)
8811        .collect();
8812    taken.sort_unstable();
8813    for (id, index, owner, i, to) in moves {
8814        if !owner.is_live() {
8815            gone.push(id);
8816            continue;
8817        }
8818        let to = match to {
8819            Some(to) => Some(to),
8820            // The row went: the cell reads the row now at its index, if
8821            // that one's cell is not there too.
8822            None => Some(i).filter(|i| taken.binary_search(i).is_err()),
8823        };
8824        match to {
8825            Some(to) if to < count as usize => index.set(to),
8826            _ => {
8827                owner.dispose();
8828                gone.push(id);
8829            }
8830        }
8831    }
8832    let mut cells = cells.borrow_mut();
8833    for id in gone {
8834        cells.remove(&id);
8835    }
8836}
8837
8838/// The position of row `index` of `count` that a cell's content reads: in a
8839/// view (`count_signal`), its index a signal of the cell's (handed back in
8840/// `made`) and the list's count, both written by the list's memo `moves`
8841/// when its rows are bound; else fixed.
8842fn row_position(
8843    index: usize,
8844    count: usize,
8845    count_signal: Option<crate::element::Signal<usize>>,
8846    moves: Option<crate::element::reactive::Node>,
8847    made: &std::cell::Cell<Option<crate::element::Signal<usize>>>,
8848) -> Position {
8849    match count_signal {
8850        Some(count) => {
8851            let index = crate::element::signal(index);
8852            made.set(Some(index));
8853            Position::of_row(index.node(), count.node(), moves)
8854        }
8855        None => Position::fixed(index, count),
8856    }
8857}
8858
8859/// A pixel count a platform reports as a number (whole for what it
8860/// decodes).
8861fn pixels(n: f64) -> crate::geometry::DevicePixels {
8862    crate::geometry::DevicePixels(n.round() as i32)
8863}
8864
8865/// Whether `url` names content of the page itself (`data:`, `blob:`), which
8866/// a download takes from the page rather than from a host.
8867fn page_content(url: &str) -> bool {
8868    let scheme = url.split(':').next().unwrap_or_default();
8869    url.contains(':')
8870        && (scheme.eq_ignore_ascii_case("data") || scheme.eq_ignore_ascii_case("blob"))
8871}