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